簡體   English   中英

給定輸入時,如何從列表中打印隨機字符串? (Python)

[英]How to print a random string from a list, when given an input? (Python)

我對編碼很陌生,所以如果答案很簡單,我很抱歉,但我目前正在嘗試編寫一個魔術 8 球游戲。 我希望計算機在用戶提供輸入時從我制作的列表中提供一個隨機字符串給用戶。 這是我到目前為止所做的代碼:

import random
print("Welcome to the Magic 8 Ball Game!")

#Create phrases the maigc 8 ball will say to the user
phrases = ["Ask again", "Reply hazy, try again.", "I do see that in your near future...", "My sources say no", "Very possible", "Yes. Very soon."]
#Ask the user to ask a question to start the game
answer = input("The game has started. Ask a question.\n")
#Make a loop


for i in answer:

     print(random.choice(phrases))

當我運行代碼時,它不會給用戶一個字符串,而是隨機給出多個字符串。 我想我可能沒有正確使用 for 循環......

它應該是一個無限循環,它會在某個條件下中斷,例如當用戶鍵入 none 或某些內容時:

import random
print("Welcome to the Magic 8 Ball Game!")

#Create phrases the maigc 8 ball will say to the user
phrases = ["Ask again", "Reply hazy, try again.", "I do see that in your near future...", "My sources say no", "Very possible", "Yes. Very soon."]
#Ask the user to ask a question to start the game
answer = input("The game has started. Ask a question.\n")
#Make a loop


while True:
    print(random.choice(phrases))
    answer = input("Ask a question.\n")
    if answer == 'None':
        break

對於初學者來說是一個驚喜,但對於高級程序員來說,如果變量由於某種原因是字符串,有時很難for item in some_variable錯誤。 在這種情況下,for 循環將字符串的單個字符作為項進行迭代。

問題中的循環將運行與用戶輸入中的字符數一樣多的次數。 這解釋了你所經歷的。

如果您在其他答案中使用建議的代碼替換if answer == 'None':if not answer: ,則可以避免代碼的其他問題。

快樂編碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM