Reputation: 11
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
Upvotes: 1
Views: 362
Reputation: 5889
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)
Upvotes: 1
Reputation: 978
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()
Upvotes: 0
Reputation: 1116
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)
Upvotes: 0
Reputation: 83
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
Upvotes: 0