Issue
I'm trying to write a program that will select a random name from a list of names. The person selected will have to pay for everybody's food bill. I don't know how to convert names back to original input from the user. If there is a cleaner way to do this, please advise. Thank you in advance everyone. Example below:
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
names = len(names)
names = random.randint(0, 4)
if names == 0:
print(f"{names} is going to buy the meal today!")
elif names == 1:
print(f"{names} is going to buy the meal today!")
elif names == 2:
print(f"{names} is going to buy the meal today!")
else:
print(f"{names} is going to buy the meal today!")
Solution
Be careful not to reassign the names
identifier, as you will lose the result of the previous operation. You can use the list[index]
syntax (called subscription) to get the element of the list at the given index:
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
random_name = names[random.randint(0, len(names))]
print(f"{random_name} is going to buy the meal today!")
You can also use random.choice
to make a random choice without worrying about the indices.
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
random_name = random.choice(names)
print(f"{random_name} is going to buy the meal today!")
Answered By - Patrick Haugh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.