input() always returns a string. Even if the user types 42, the program receives the four characters "42". Convert the text before doing arithmetic.
age_text = input("Your age: ")
age = int(age_text)
print(age + 1)Numeric conversions#
print(int("42")) # 42
print(int(3.9)) # 3: truncates toward zero
print(float("2.5")) # 2.5
print(float(7)) # 7.0
print(str(42)) # "42"
print(str(True)) # "True"int("3.5") raises ValueError because the text is not a valid integer literal. Convert to float first if decimals are possible:
value = int(float("3.5")) # 3Be aware that this silently truncates. Decide whether that is acceptable for the task.
Booleans from other values#
bool() converts values by truthiness:
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("False")) # True: non-empty string
print(bool([])) # False
print(bool(None)) # FalseThe string "False" is non-empty, so it is truthy. To parse a yes/no answer, compare the text explicitly.
Safe conversion#
Invalid input should not crash the whole program. Use try and except:
text = input("Enter a whole number: ")
try:
number = int(text)
except ValueError:
print("That was not a whole number.")
else:
print(f"Double is {number * 2}")The else block runs only when no exception occurred. Put as little code as possible inside try.
Converting collections#
letters = list("abc") # ['a', 'b', 'c']
numbers = list(map(int, ["1", "2", "3"]))
text = " ".join(["Python", "rocks"])map() applies a conversion to each item lazily. Wrapping it in list() materialises the results.
Rounding versus formatting#
round(value, 2) returns a float. An f-string with .2f produces display text:
value = 3.14159
print(round(value, 2)) # 3.14
print(f"{value:.2f}") # 3.14Use formatting for output and keep full precision in calculations unless the problem requires rounding at each step.
Practice#
Ask for a price and a quantity. Convert the price to float and the quantity to int, then print the total with two decimal places. If either conversion fails, print a clear message instead of a traceback.
