我正在编写代码,用于将用户询问过的信息转换为字符串格式,但由于某种原因,我这样做时遇到了错误。
name = input("What is your name: ")
age = int(input("How old are you: ")
print("Hello "+name)
print("You are "+str(age)+" years old")
首先,确保关闭所有括号。为年龄输入添加错误处理,以避免输入不是有效整数时崩溃。
name = input("What is your name? ")
# Loop to ensure valid age input
while True:
try:
age = int(input("How old are you? ")) # Expecting integer input
break # Exit the loop if the input is valid
except ValueError:
print("Please enter a valid number for age.") # Error handling for invalid input
print("Hello " + name)
("You are " + str(age) + " years old")