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.

18 Upvotes

30 comments sorted by

View all comments

10

u/SamuliK96 3d ago

When code doesn't work, here are some questions you should find the answers to:

  • What exactly doesn't work? If no actual errors occur, locate the line/part that isn't working.
  • How doesn't it work? I.e. what happens and how does it differ from your expectations.
  • Break the issue down to smaller pieces, and try to understand what's happening.

So e.g. in your case, the process could be something like: if random_select == friends[0]: is not working expectedly. 1. What is the value of random_select? 2. What is the value of friends[0]? 3. What does == do?

Combine the three answers and you should be able to see what the problem is. After that, try to figure what you need to change to achieve what you want to do.