我试图在完成后循环回到代码的开头。选项后' C'按下,程序应该结束,(我也在努力)。但我希望程序循环到开头,除非按下C。如果' A'或者' B'如果按下,程序应该要求用户再次输入选项。这个问题有所不同,因为它有一个具体的例子。我试着查看Stack Overflow并发现了类似的问题并尝试了它们,但它们都没有成功?不确定为什么
#input your full name
def startagain():
firstName=raw_input("Enter your first name: ")
middleName=raw_input("Enter your middle name: ")
lastName=raw_input("Enter your last name: ")
#select what option you want.
options=str(raw_input("Type 'A' for printing the length of your name,
'B' for printing your initials and 'C' to exit"))
#prints first, middle and last name
if (options == "A" or options == "a"):
print firstName + " " + middleName + " " + lastName
#prints your initials
elif (options == "B" or options == "b"):
print firstName[0] + "." + middleName[0] + "." + lastName[0] + "."
#exit
elif (options == "C" or options == "c"):
exit()
print ("OK, bye!")
#invalid selection
else:
print "Invalid selection. Please select A, B, or C."
if options == "A" or options == "B":
startagain()
提前感谢:)
答案 0 :(得分:0)
删除对startagain()的调用,并将所有代码放在
中while True:
环。
答案 1 :(得分:0)
这是一种常见的程序类型,通常具有这种结构
while True:
# print instructions for user
# get his input
# have a series of if/elif for handling each option
# the option that indicates exit just does a break statement
# to break out of loop
这解决了有关循环的问题,但您的代码还存在其他问题。如果您是初学者,您应该尝试花时间调试您的程序,并采用渐进的方法来构建您的程序