3

该程序的重​​点是询问用户的姓名(首字母自动大写)。

然后它会询问年龄和性别。如果年龄超过 130 或为负数,则会抛出错误

该程序应该打印出所有信息,但我无法弄清楚while循环条件。谁能帮我弄清楚while循环条件?

-edit- 虽然Pastebin 的链接已被删除,但我认为那里有重要信息。所以,我还是会给你链接: http: //pastebin.com/UBbXDGSt

name = input("What's your name? ").capitalize()
age = int(input("How old are you "))
gender = input("From what gender are you? ").capitalize()

while #I guess I should write something behind the "while" function. But what?
    if age >= 130:
        print("It's impossible that you're that old. Please try again!")
    elif age <= 0:
        print('''It should be logical that ages are written in positive numbers! Well, try again! =)''')

age = int(input("How old are you? "))   

print("Your name is ",name, ". You are ", age, "years old." "\nYou are ", gender, ".")
4

2 回答 2

1

如果有有效输入,您可以设置一个关闭/打开的标志。这将解决你的while循环问题

 name = input("What's your name? ").capitalize()
 gender = input("From what gender are you? ").capitalize()
 ok = False #flag
 while not ok:
    age = int(input("How old are you "))
    if age >= 130:
       print("It's impossible that you're that old. Please try again!")
    elif age <= 0:
       print('''It should be logical that ages are written in positive numbers! Well, try again! =)''')
    else:
       ok = True
 print("Your name is ",name, ". You are ", age, "years old." "\nYou are ", gender, ".")
于 2012-10-28T01:21:28.980 回答
0

通常在这里你使用while True.

while True:
    age = int(input("How old are you? "))

    if age >= 130:
        print("It's impossible that you're that old. Please try again!")
    elif age <= 0:
        print('''It should be logical that ages are written in positive numbers! Well, try again! =)''')
    else:
        break

这将重复这个问题,直到它得到一个可以接受的答案,在这种情况下,它break会跳出循环。

为了完整起见,您还应该检查他们是否输入了任何内容,以及他们是否输入了一个数字。在这里,我还将使用continue,它将从头开始重新启动循环,忽略其余代码。这是一个很好的例子:

while True:
    age = input("How old are you? ")
    if not age:
        print("Please enter your age.")
        continue
    try:
        age = int(age)
    except ValueError:
        print("Please use numbers.")
        continue

    if age >= 130:
        print("It's impossible that you're that old. Please try again!")
    elif age <= 0:
        print('''It should be logical that ages are written in positive numbers! Well, try again! =)''')
    else:
        break
于 2012-10-28T04:14:58.963 回答