Python “如何打印”;是”;“当写下时”;“是”;在;你确定要退出吗;问题
当用户在“确定退出”问题中写入“y”时,我想打印“是”,当用户在“确定退出”问题中写入“n”时,我想打印“否”。 第二个问题是;如果我写任何字母而不是“y”或“n”,代码仍在运行。如何修复它Python “如何打印”;是”;“当写下时”;“是”;在;你确定要退出吗;问题,python,python-3.x,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)")
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!")
您只需在打印条件下添加打印语句:
if(answer == "y"):
print(y)
print("See you again ")
break
elif (answer == "n"):
print(n)
continue
else:
break
adding else:break将在插入任何其他inout而不是y和n时退出循环 你的问题不是很清楚。您说当用户在“是否确定退出”问题中写入“y”时,我想打印“是”,当用户在“确定退出”问题中写入“n”时,我想打印“否”。但在您使用输入(“回答:”)语句收集用户愿望时,这一行已经打印出来 您是在寻找下面的代码片段吗
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”,并将继续运行,直到在代码中建立适当的约束。要在用户键入“y”后立即打印“是”需要在键入时获取单个击键,这取决于操作系统。有一些第三方模块允许这样做,请参阅。回答:y(我想在这里打印“是”,而不是y)是的,再见。您已经定义了一个名为y的变量,它将“是”作为字符串保存。请再次查看您的代码。现在我得到了我的答案,谢谢您。但是我刚刚开始学习Python,现在我才刚刚开始。。。我还没学会“.lower”所以你说除了这个没有别的办法,对吧?Furkan:看到了吗