在"Are you sure for exit"问题中写"y"时如何打印"yes"?



我想在用户写"y"时打印"是",当用户在"你确定退出吗"问题中写"n"时打印"否"。第二个问题是;如果我写任何字母而不是"y"或"n",代码仍在运行。如何解决?

residuary = 1000
while True:
    operation = input("Select operation: ")
    if(operation == "q"):
        print("Are you sure for exit? (y/n)")
        answer = input("Answer:")
        y = "yes"
        n = "no"
        if(answer == "y"):
            print("See you again ")
            break
        else:
            continue
    elif(operation== "1"):
        print("Residuary is ${} .".format(residuary))
    elif (operation== "2"):
        amount = int(input("Amount you want to invest: "))
        residuary += amount
        print("${} sent to account.".format(amount))
        print("Available Residuary ${} ".format(residuary))
    elif (operation == "3"):
        amount = int(input("Amount you want to withdraw: "))
        if(amount > residuary):
                print("You can not withdraw more than available residuary!")
                continue
        residuary -= amount
        print("${} taken from account.".format(amount))
        print("Available Resiaduary ${} ".format(residuary))
    else:
        print("Invalid Operation!")

你的问题不是很清楚。您说我想在用户写"y"时打印"是",当用户在"您确定退出"问题中输入"n"时打印"否"。 但是当您使用 input("Answer:"( 语句收集用户愿望时,此行会打印出来。

您是否在追求以下代码片段之类的东西?

if(operation == "q"):
    quit = False
    while(True):
        print("Are you sure you want to exit? ([y]es/[n]o)")
        answer = input("Answer:")
        if(answer.lower() == 'y': #You may check startswith() as well
            quit = True
            print('You chose yes')
            break
        elif(answer.lower() == 'n':
            print('You chose no')
            break
    if quit:
        print("See you again ")
        break
else:
    continue

您可以在打印条件下添加 print 语句:

    if(answer == "y"):
        print(y)
        print("See you again ")
        break
    elif (answer == "n"):
        print(n)
        continue
    else:
        break

添加 else:如果插入任何其他输入而不是 y 和 n,中断将退出循环。

最新更新