import datetime
now = datetime.datetime.now()
current_year = now.year
while True:
user_name = str(input('What is your name?'))
if user_name.isalpha():
break
else:
print('Invalid input. Make sure to enter your name.')
continue
while True:
user_age = input('How old are you?')
if user_age.isdigit():
break
else:
print("Invalid input. Make sure to enter a number for your age.")
continue
birth_year = (now.year - ***user_age***)
greeting = f"Hello {user_name}! You were born in {birth_year}."
print(greeting)
当我以这种方式编码时,当我尝试从
user_age
中减去 now.year
时,会出现错误。 TypeError: unsupported operand type(s) for -: 'int' and 'str'
。在尝试使用 while True 循环之前,代码运行良好。程序告诉用户出生年份和年龄。如果我将 int 放在输入前面,则会在 isdigit
上出现错误。感谢您的帮助。
与其尝试通过检查字符串来确定字符串是否可以转换为 int,不如尝试将其转换并管理可能出现的任何异常。
为此目的拥有一个可重用的函数很有用。
这是一个例子:
def getint(prompt):
while True:
x = input(prompt)
try:
return int(x)
except ValueError:
print(f"{x} is not a valid integer")
print(getint("How old are you? "))