首页 > 解决方案 > How to print "yes" when written "y" in "Are you sure for exit" question?

问题描述

I want to print "yes" when the user writes "y" and print"no" when the user writes "n" in "Are you sure for the exit" question. And the second problem is; if I write any letter instead of "y" or "n", the code is still running. How to fix it?

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!")

标签: pythonpython-3.x

解决方案


你的问题不是很清楚。你说我想在用户写“y”时打印“yes”,当用户在“你确定退出”问题中写“n”时打印“no”。但是当您使用 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

推荐阅读