首页 > 解决方案 > 如果输入的值错误,我将如何返回菜单?

问题描述

所以我有这个代码

import csv
def menu():
    print ("""
         1.Enter airport details
         2.Enter flight details
         3.Enter price plan and calculate profit
         4. Clear data
         5.Quit
            """)
menu()
b = input("What would you like to choose?")
if b == '4':
    print('Goodbye')

if b == '1':
    a = input('Enter three letter code: ')
    if a == 'LPL' or a == 'BOH':
        d = input('Enter overseas airport code: ')
        airport_info = open('airports.csv', 'r')
        csvreader = csv.DictReader(airport_info,delimiter = ',', fieldnames = ('overseasCode','overseasName','distLPL','distBOH'))
        for row in csvreader:
            if row['overseasCode'] == d:
                print(row['overseasName'],d)

因此,如果用户输入的内容与 LPL 或 BOH 不同,则应显示错误代码,并且用户返回菜单重试。我认为它必须是一个while循环,但我不确定如何实现它,所以有人可以帮忙吗?

标签: python-3.x

解决方案


这确实是一个 while 循环。就像这样:

flag = False
while flag == False:
    menu()
    b = input("What would you like to choose?")
    if b == '4':
        print('Goodbye')

    if b == '1':
        a = input('Enter three letter code: ')
        if a == 'LPL' or a == 'BOH':
            flag = True
            ...
        else:
            print("Error")

推荐阅读