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!")
CodePudding user response:
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!")
CodePudding user response:
You can try the code below to display the name of the person who is going to buy the meal after the random method returns a value.
# get the input names of friends separated by comma
names=input("Enter the names of every person separated by a comma")
# get the list of names by splitting the string above using the comma delimiter
name_collection=names.split(",")
# get the random index of the person who is going to pay for the bills
choice=random.randint(0,4)
#print the name of the person who is going to buy the meal
print(name_colection[choice])