簡體   English   中英

將列表中的隨機元素與 Python 中的用戶輸入連接起來

[英]Concatenate random element from list with user input in Python

我正在編寫一個代碼,允許用戶輸入他們去過的城市。 用戶輸入后,我希望我的代碼從我的列表中返回一個隨機生成的關於城市的評論。 但是,每當我運行代碼時,它都會將用戶輸入與一個隨機字母連接起來,這不是我的代碼意圖。

import random

message = "Type your city here: "

#Comments to concatenate with user input
comments = [f"what a lovely {}", f"I always wanted to visit {}", "I hope you enjoyed your trip to {}"]

#While loop for user input
while True:
   message = input(message)

   for elem in comments:
      message += random.choice(elem)

   if message == "quit":
      break

我想這就是你要找的東西?

import random
#Comments to concatenate with user input 
comments = ["what a lovely ", "I always wanted to visit ", "I hope you enjoyed your trip to "]

#While loop for user input
message = None
while message != "quit":
   message = input("Type your city here: ")
   print(random.choice(comments)+message)

我建議編寫一個 function ,它將城市作為輸入,然后在最后返回列表。 像這樣

def random_quote(city):
    comments = [f"what a lovely ", f"I always wanted to visit ", "I hope you 
     enjoyed your trip to "]
    comment = random.choice(comments)
    return comment + city

random.choice()接受一個列表(查看文檔),不要遍歷您的comments變量,將其傳遞給random.choice()並且不要忘記將{}替換為城市:

city = input('Please enter a city')

comment = random.choice(comments)

comment.replace('{}', city)

print(comment)

您不需要在 while 中使用 for 循環。 您應該始終避免while True因為它是錯誤的開口。 在循環內有一個break通常標志着糟糕的編程。

您可能應該在使用f-string的內容,您似乎也不知道random.choice的作用,因為您將它放入 for which 給了它消息,它隨機從中取出一個字符.

import random


def main():
    prompt = "Type your city here: "

    # Comments to concatenate with user input
    comments = ["what a lovely ", "I always wanted to visit ", "I hope you enjoyed your trip to "]

    usr_input = input(prompt)
    # While loop for user input
    while usr_input != 'quit':
        message = random.choice(comments) + usr_input
        usr_input = input(prompt)


if __name__ == '__main__':
    main()

暫無
暫無

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

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