Exercises
Casting
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
typed holds the text "25". Print the number 35 by converting before adding.
Python
typed = "25"
# print typed plus 10, as a number
int() turns text into a whole number.
typed = "25"
print(int(typed) + 10)Exercise 2Passed
int("3.5") fails. Convert the text to a whole number anyway, in two steps.
Python
text = "3.5"
# print it as a whole number
Go through float first.
text = "3.5"
print(int(float(text)))Exercise 3Passed
Print ok for text that converts to a number and no for text that does not.
Python
for text in ["12", "twelve"]:
# print ok or no
passint() raises ValueError. Catch it with try and except.
for text in ["12", "twelve"]:
try:
int(text)
print("ok")
except ValueError:
print("no")