使用 Python 回覆使用者文字


你可以使用 if-elif-else 語句來解決這個問題。並且為了更貼合要求,它將詢問有效選項,直到給定的選項出現在列表中,我們可以使用 while 迴圈。當選項有效時,就中斷迴圈,否則,它將一再請求輸入。

你應該將輸入當作整數,為此你需要使用 int() 方法將輸入強制轉換位整數。

示例

請檢視以下程式碼以遵循給定要點。

print("Come-on in. Need help with any bags?")
while True:
# loop is used to take option until it is not valid.
bag = int(input("(1)Yes (2)No Thanks (3)I'll get 'em later\nTYPE THE NUMBER OF YOUR RESPONSE: "))
if bag == 1:
print("You have chosen YES. We'll help with bags")
break
# Stop the loop as the option is valid
elif bag == 2:
print("Ok you don't want any help.")
break
elif bag == 3:
print("Tell us, when you want the help")
break
else:
print("Invalid Choice, Please select number from 1 to 3")

更新於: 16-06-2020

2 000+ 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.