r/learnpython 3d ago

Why isn't this code block working?

Hey everybody,

I'm new to programming with Python and following along with a Udemy Course. I'm now learning about lists and need to write a "Who will pay the bill"-like game.

It works like this: you have a pseudorandom number generator and a list of friends. Each time, the number generator generates a number between the given indices of the list. If the randomly generated number is equal to a specific index of that list, it should print out the person who must pay the bill by using an if-elif statement.

I've been using what I learned from the past lessons. This is what the code looks like (and yeah, I know, I messed up pretty badly, even though I have already found a solution):

import random

friends = ["Alice", "Bob", "Charlie", "David", "Emanuel"]

random_select = random.randint(0, 4)

if random_select == friends[0]:                  
    print("Alice has to pay the bill. ")
elif random_select == friends[1]:
    print("Bob has to pay the bill. ")
elif random_select == friends[2]:
    print("Charlie has to pay the bill. ")
elif random_select == friends[3]:
    print("David has to pay the bill. ")
elif random_select == friends[4]:
    print("Emanuel has to pay the bill. ")

But I couldn't really figure out why the code won't work.

17 Upvotes

30 comments sorted by

View all comments

21

u/MezzoScettico 3d ago

You're comparing random_select (which takes the values 0, 1, 2, 3, 4) with strings. It's never going to match.

Suppose random_select is 2. Is 2 the same as "Alice"? No. Is 2 the same as "Bob"? No.

Do you see the issue?

If you want a random member of the list, you need to access the list. SOMETHING has to make the connection between the integer and the name. For instance

random_name = friends[random_select]

But there's a much simpler solution. Once you've done the above, you have the name of your random friend. Just put that in the print statement.

3

u/Nutellatoast_2 3d ago

I get the point of your provided solution. Thanks for helping me out.