以下代码的主菜单选项运行正常,直到在选项1或2中进行“无效输入”,即使输入正确也是如此。接下来发生的是,当选择选项3或4来显示任一文件时,即使用户不在该菜单选项中,也会向用户显示来自名称注册过程的“无效条目”错误消息。
似乎脚本在某处循环,但我无法弄清楚在哪里。正如我所说,只有在选项1或2中调用初始的“无效条目”消息时才会发生这种情况。如果没有调用它,我可以继续注册名称并显示文件而不会出现问题。
非常感谢任何帮助。
import sys
def main():
main_menu_choice = input("""Please choose from the following
1. Register a child.
2. Register a staff member.
3. Children.
4. Staff.
5. Exit.""")
if main_menu_choice == "1":
child_first_name = input("Enter the child's first name")
# check that no empty string or digit is entered
while child_first_name == "" or any(str.isdigit(c) for c in child_first_name):
print("Invalid entry.")
main()
else:
child_last_name = input("Enter the child's last name")
while child_last_name == "" or any(str.isdigit(c) for c in child_last_name):
print("Invalid entry.")
main()
child_name = (child_first_name + " " + child_last_name).title()
file = open("Children.txt", 'a')
file.write(child_name + "\n")
file.close()
main()
elif main_menu_choice == "2":
staff_first_name = input("Enter the staff member's first name")
while staff_first_name == "" or any(str.isdigit(c) for c in staff_first_name):
print("Sorry I didn't catch that\nPlease start again.")
main()
else:
staff_last_name = input("Enter the staff member's last name")
while staff_last_name == "" or any(str.isdigit(c) for c in staff_last_name):
print("Sorry I didn't catch that\nPlease start again.")
main()
staff_name = (staff_first_name + " " + staff_last_name).title()
file = open("Staff.txt", 'a')
file.write(staff_name + "\n")
file.close()
main()
elif main_menu_choice == "3":
file = open("Children.txt", 'r')
lineList = file.readlines()
lineList.sort()
print("List of children's names in alphabetical order:")
for line in lineList:
print(line, end="")
file.close()
elif main_menu_choice == "4":
file = open("Staff.txt", 'r')
lineList = file.readlines()
lineList.sort()
print("List of staff member's names in alphabetical order:")
for line in lineList:
print(line, end="")
file.close()
elif main_menu_choice == "5":
print("Exit.")
sys.exit(0)
else: #If an invalid choice was made from main_menu_choice
print("Invalid Command, try again.")
main()
main()
答案 0 :(得分:2)
我认为你的问题在于:
while child_first_name == "" or any(str.isdigit(c) for c in child_first_name):
print("Invalid entry.")
main()
您在此条件检查中使用while
。这使得它继续循环,因为条件仍然是正确的。
使用if
替换此条件检查。
希望这会有所帮助。
编辑:
要在某个时刻终止程序,您需要使用return
。您可以在调用main()
后添加此项以避免执行其余代码。
在没有必要时尽量避免递归调用。这段代码可以使用循环完成。
当您从main()方法调用main()方法时,控件不会简单地跳转到函数的顶部并再次开始执行它。相反,函数的全新“副本”在内存中进行,这与您刚刚调用的函数完全不同。这是递归概念的关键。
说完这个,控件需要“记住”新的main()调用结束后返回的位置。因此,返回地址被推入堆栈。现在,无论控件何时再次返回到调用main(),它都将执行剩余的代码行(当然,除非程序被强制从外部终止)。