我正在尝试使用while循环询问一系列问题并在询问最后一个问题时重新启动。问题是,我希望用户能够通过在任何问题上键入特定单词来退出。我还想在循环中尽可能少地编写代码,因此if / elif语句位于函数中。
我的问题是:我可以继续或断开函数的循环吗?
我的代码:
def check_gender(q):
if q == "f":
number_women = number_women + 1
elif q == "m":
number_men = number_men + 1
elif q == "foo":
#break the loop
else:
print("Please answer M or F: ")
q = input("Are you a male or female (M/F)? ").lower()
check_gender(q)
def check_age(q):
if not(16 <= int(q) <= 25):
print("You are not in the age range for this survey")
#Jump back to first question here
if q == "foo":
#break the loop
while True:
gender = input("Are you a male or female (M/F)? ").lower()
check_gender(gender)
age = input("Please enter your age: ")
check_age(age)
#And so on with questions
这可能吗?
答案 0 :(得分:1)
最好的方法可能是在问题函数内部引发自定义异常,如下所示:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
NUMBER_MEN, NUMBER_WOMEN = 0, 0
class ExitLoop(Exception):
pass
def check_gender(reply):
global NUMBER_WOMEN, NUMBER_MEN
while True:
if reply == "f":
NUMBER_WOMEN += 1
return
elif reply == "m":
NUMBER_MEN += 1
return
elif reply == "foo":
raise ExitLoop
else:
print("Please answer M or F: ")
reply = input("Are you a male or female (M/F)? ").lower()
def check_age(reply):
if reply == "foo":
raise ExitLoop
if not 16 <= int(reply) <= 25:
print("You are not in the age range for this survey")
return False
return True
while True:
try:
gender = input("Are you a male or female (M/F)? ").lower()
check_gender(gender)
age = input("Please enter your age: ")
inrange = check_age(age)
if not inrange:
continue
except ExitLoop:
break
我对您的代码进行了一些其他更改,使其更加pythonic。请注意,当用户输入“foo”或回答年龄问题的数字时,上面的代码会失败。
顺便说一句,如果您想向用户提出很多问题,可能需要查看优秀的Click package。
希望这有帮助!
答案 1 :(得分:0)
你应该尝试这个代码,有人把其他字母循环打破
def check_gender(q):
if q == "f":
number_women = number_women + 1
elif q == "m":
number_men = number_men + 1
# elif q == "foo":
#break the loop
else:
print("Please answer M or F: ")
q = input("Are you a male or female (M/F)? ").lower()
check_gender(q)
def check_age(q):
if not(16 <= int(q) <= 25):
print("You are not in the age range for this survey")
#Jump back to first question here
#if q == "foo":
#break the loop
while True:
gender = input("Are you a male or female (M/F)? ").lower()
if gender != "f" and gender != "m":
break
else:
check_gender(gender)
age = input("Please enter your age: ")
try:
ageValue = int(age)
check_age(age)
except ValueError:
print ("You must enter a number")
break