Write a snippet that converts between int, float, str and bool, and shows the conversions that fail.
Python has no cast syntax like the parentheses you would use in C. A conversion is done by calling the type you want as if it were a function, and that call either gives you a new object or raises an error. That makes conversion ordinary code that you can read and inspect, instead of a special operator.
print(int('42')) # 42
print(float('3.5')) # 3.5
print(str(42) + '!') # 42!
print(bool(0), bool('')) # False False
print(bool([0])) # True, the list is not empty
try:
int('abc')
except ValueError as error:
print('ValueError:', error)
try:
int('3.5')
except ValueError as error:
print('ValueError:', error)
print(int(3.9), int(-3.9)) # 3 and -3, it cuts off the decimal
print(round(3.9), round(-3.9)) # 4 and -4, it goes to the nearest even
The two failures are the interesting part of this example. int('abc') raises a ValueError with the message "invalid literal for int() with base 10: 'abc'". int('3.5') also raises a ValueError, because the int constructor will not accept a decimal point. If you really want that path, then you have to write int(float('3.5')).
The last two lines show a genuine difference in behaviour. int() cuts the decimal off towards zero, so int(-3.9) is -3. round() gives you the nearest whole number and uses banker's rounding for exact halves, so round(-3.9) is -4 and round(2.5) is 2 and not 3.
One more thing to know is that int() also accepts a base, so int('ff', 16) is 255 and int('0b1010', 2) is 10.