使用 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")

更新於:2020 年 6 月 16 日

2K+ 檢視

開啟您的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.