程序的要点是询问用户的姓名(自动将第一个字母大写)。
然后会询问年龄和性别。如果年龄超过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, ".")
答案 0 :(得分: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, ".")
答案 1 :(得分: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