用户输入未打印?

问题描述 投票:0回答:1

我正在编写代码,用于将用户询问过的信息转换为字符串格式,但由于某种原因,我这样做时遇到了错误。

name = input("What is your name: ")
age = int(input("How old are you: ")

print("Hello "+name)
print("You are "+str(age)+" years old")
python
1个回答
0
投票

首先,确保关闭所有括号。为年龄输入添加错误处理,以避免输入不是有效整数时崩溃。

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")
© www.soinside.com 2019 - 2024. All rights reserved.