Exercises
User Input
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
The typed answer has stray spaces and capitals. Clean it up and print True when it means yes.
Python
answer = " Yes \n"
# print True when the cleaned answer is y or yes
strip() removes the whitespace, lower() flattens the capitals.
answer = " Yes \n"
cleaned = answer.strip().lower()
print(cleaned in ("y", "yes"))Exercise 2Passed
The line holds two numbers separated by a space. Print their sum.
Python
line = "3 4"
# print the sum of the two numbers
split() breaks the line up; each piece is still text.
line = "3 4"
x, y = line.split()
print(int(x) + int(y))Exercise 3Passed
Return None for text that is not a whole number, and the number otherwise.
Python
def parse_age(text):
# return the number, or None
pass
print(parse_age("30"))
print(parse_age("thirty"))try the conversion, and return None from the except branch.
def parse_age(text):
try:
return int(text)
except ValueError:
return None
print(parse_age("30"))
print(parse_age("thirty"))