输入回车时结束循环python_python-用户输入退出以在循环时中断
最簡單的解決方案可能是創(chuàng)建一個函數(shù),該函數(shù)將顯示的消息作為輸入,并在測試其滿足條件后返回用戶輸入:
def guess_input(input_message):
flag = False
#endless loop until we are satisfied with the input
while True:
#asking for user input
guess = input(input_message)
#testing, if input was x or exit no matter if upper or lower case
if guess.lower() == "x" or guess.lower() == "exit":
#return string "x" as a sign that the user wants to quit
return "x"
#try to convert the input into a number
try:
guess = int(guess)
#it was a number, but not between 1 and 9
if guess > 9 or guess < 1:
#flag showing an illegal input
flag = True
else:
#yes input as expected a number, break out of while loop
break
except:
#input is not an integer number
flag = True
#not the input, we would like to see
if flag:
#give feedback
print("Sorry, I didn't get that.")
#and change the message displayed during the input routine
input_message = "I can only accept numbers from 1 to 9 (or X for eXit): "
continue
#give back the guessed number
return guess
您可以從主程序中調(diào)用此命令,例如
#the first guess
guess = guess_input("Guess a number from 1 to 9: ")
要么
#giving feedback from previous input and asking for the next guess
guess = guess_input("Too high! Guess again (or X to eXit): ")
總結(jié)
以上是生活随笔為你收集整理的输入回车时结束循环python_python-用户输入退出以在循环时中断的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果市值一夜蒸发457亿美元 或因产品创
- 下一篇: 建设银行cvv是什么意思