Type Casting · Examples
Beginner

Type Casting Examples

Short, runnable programs that show python casting in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Casting lesson.

1Reading a quantity typed as text

A value read from a form or file is a string, so cast it before using it in a calculation.

Reading a quantity typed as text
quantity_text = "4"
unit_price = 2.5
total = int(quantity_text) * unit_price
print("Total:", total)
Expected outputTotal: 10.0

2Float to int: truncate versus round

int() removes the decimals, round() picks the nearest whole number. Choose on purpose.

Float to int: truncate versus round
average = 84.6
print("Truncated:", int(average))
print("Rounded:", round(average))
print("One decimal:", round(average, 1))
Expected outputTruncated: 84
Rounded: 85
One decimal: 84.6

3Turning text into a list of digits

list() splits a string into characters and int() converts each digit, handy for checksum-style tasks.

Turning text into a list of digits
card = "4539"
digits = [int(ch) for ch in card]
print(digits)
print("Digit sum:", sum(digits))
Expected output[4, 5, 3, 9]
Digit sum: 21

4Building a dictionary from pairs

dict() accepts a list of pairs, which is what zip() or a parsed file often gives you.

Building a dictionary from pairs
names = ["apples", "pears", "plums"]
stock = [12, 5, 0]
inventory = dict(zip(names, stock))
print(inventory)
print(inventory["pears"])
Expected output{'apples': 12, 'pears': 5, 'plums': 0}
5

5Parsing a yes/no answer correctly

bool("no") would be True, so compare the text instead.

Parsing a yes/no answer correctly
answers = ["yes", "No", "YES", "maybe"]
for answer in answers:
    accepted = answer.strip().lower() in ("yes", "y", "true")
    print(answer, "->", accepted)
Expected outputyes -> True
No -> False
YES -> True
maybe -> False

6Hexadecimal colours and characters

int(text, 16) reads base-16 numbers; chr() and ord() convert between characters and their codes.

Hexadecimal colours and characters
colour = "ff8800"
red = int(colour[0:2], 16)
green = int(colour[2:4], 16)
blue = int(colour[4:6], 16)
print(red, green, blue)
print(chr(ord("a") + 1))
Expected output255 136 0
b

Practise next

Python Casting exercises → Back to the lesson

Python Data Types examplesPython Numbers examplesPython Input and Output examplesPython ValueError examples