我应该如何退出此python程序?

时间:2019-10-02 15:13:52

标签: python

quit2 = True
while quit2 == True:
    delete = input('\nIf you would like to delete a guest, enter their guest number. '
                   '\nIf you would  like to skip this step press Enter.')

if isinstance(delete, int):
    list[delete].remove()
else:
    break

我不能使用quit2 ='',而不能使用quit2。

2 个答案:

答案 0 :(得分:1)

假设if语句不在while循环中是问题的格式问题,那么此代码的唯一问题是if语句条件永远不会正确,因为input()总是返回string,而不是int

代替使用if/else块,可以尝试使用try/except块:

while True:  # Don't need 'quit2', since it's never going to change
    delete = input('\nIf you would like to delete a guest, enter their guest number. '
                   '\nIf you would  like to skip this step press Enter.')

    try:
        delete = int(delete)
        list[delete].remove()
    except ValueError:  # if int(delete) fails because the string isn't numeric, exit loop
        break
    except IndexError:  # if list index out of range, let them try again
        print("That guest doesn't exist. Please try again.")
        continue

答案 1 :(得分:0)

if 中的while循环内

使用 break ,以便其余代码继续执行,但是如果要终止它:导入sys并使用sys.exit ()