在“您确定要退出”问题中写为“ y”时,如何打印“是”?

时间:2019-03-24 11:27:30

标签: python python-3.x

我想在用户写“ 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!")

4 个答案:

答案 0 :(得分:0)

您的问题不是很清楚。您说我想在用户输入“ 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

答案 1 :(得分:-1)

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

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

添加其他:在插入其他inout而不是y和n的情况下,break将退出循环。

答案 2 :(得分:-1)

我认为您想在按Enter键时将“ y”替换为“ yes”。 如果是这样,我认为这是不可能的。

答案 3 :(得分:-1)

这是我的代码:

import os

while True:
    print('Answer: ', end='', flush=True)
    answer = os.system('choice /n /c:yn>nul')

    y = "yes"
    n = "no"

    if answer == 1:
        print(y)
        print("See you again")
        break

    elif answer == 2:
        print(n)
        continue

    else:
        print(answer)
        break

我认为这不是使用“ choice.exe”的最佳方法,它仅适用于Windows,但可以使用!