简体   繁体   中英

Concatenate random element from list with user input in Python

I'm writing a code that allows a user to enter a city they have been to. After the user inputs it, I want my code to return a randomly generated remark about the city from my list. However, whenever I run the code, it concatenates the user input with a random letter, which is not my intention of the code.

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

I assume this is what your looking for?

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)

I recommend coding a function that takes the city as input then at the end returns the list. Like this

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() accepts a list (take a look at the docs ), Don't iterate over your comments variable, pass it to random.choice() and don't forget to replace {} with the city:

city = input('Please enter a city')

comment = random.choice(comments)

comment.replace('{}', city)

print(comment)

You do not need a for loop inside your while. You should always avoid while True as it is an opening for bugs. Having a break inside a loop usually marks bad programming.

You should probably read a bit about what f-string is before using it, you also don't seem to know what random.choice does since you put it into the for which gave it the messages, which it randomly took a character out of.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM