3. Casting and rounding

Casting converts a value from one type to another. The conversion functions are named after the target type:

  • int("100") → 100; int(3.9) → 3 (the decimal part is dropped, not rounded).
  • float("3.5") → 3.5.
  • str(42) → "42".
  • bool(0) → False; bool("") → False; most other values → True.

Converting text that is not a number, such as int("hello"), raises a ValueError.

round() is not a casting function, but it lives here because it is the counterpart of int() when you have a decimal number:

Called with one argument, round() returns an int.

Coming from JavaScript? int() truncates toward zero like Math.trunc(), not Math.floor(). round() rounds halfway to the even neighbour (round(2.5) is 2), unlike Math.round().

#01

Text to integer

"100" is text, so + would join it to another string. Use int() to turn it into a number first, then add 2.

Print exactly:

Output
Run your code to see the output here.
#02

Number to text

str() turns a number into text. Use it to join "100" and 2 with +.

Print exactly:

Output
Run your code to see the output here.
#03

Drop the decimals

int() does not round: it keeps only the whole part. Convert the float 3.1416 to an integer and print it.

Print exactly:

Output
Run your code to see the output here.
#04

Text to float

float() converts text with a decimal number into a float. Convert "3.5" and print the result.

Print exactly:

Output
Run your code to see the output here.
#05

Values that become booleans

bool() converts a value to True or False. Zero and an empty string are False; any other value is True, even the text "False".

Print these three results in a single print() call, in this order: bool(0), bool(""), bool("False").

Print exactly:

Output
Run your code to see the output here.
#06

Round a number

round() returns the nearest whole number. Unlike int(), it does not just drop the decimals: round(3.9) is 4.

Round 3.1416 and print the result.

Print exactly:

Output
Run your code to see the output here.
#07

Round half to even

When a number is exactly halfway between two integers, round() picks the even one: round(2.5) is 2 and round(3.5) is 4.

Print both results in a single print() call, in this order: round(2.5), then round(3.5).

Print exactly:

Output
Run your code to see the output here.
#08

Truncate or round?

int() truncates toward zero, while round() goes to the nearest whole number. For negative numbers the two results differ: int(-2.9) is -2, but round(-2.9) is -3.

Print int(-2.9) and round(-2.9) in a single print() call.

Print exactly:

Output
Run your code to see the output here.