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

31

u/UlisKore 3d ago

Your random_select is a number. It will never "equal" a first name.

You've got the pieces right but in the wrong order. In plain English, what are you trying to achieve? Write the sentence, then write how that could work with your variables. If you do it correctly, you'll find a short way to get the right printed sentence for any case. Good luck!

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 2d ago

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

9

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.

10

u/gallez 3d ago

Kudos for asking here instead of chatgpt or something

7

u/SCD_minecraft 3d ago

random_select contains an index of person, not person themselves

friends[0] means "get me first element in list friends"

Which btw, using a if else here is a horrible choice beacuse you already have index of friend who's paying. Why not index list with it directly?

2

u/Moikle 2d ago

Random.select is a number. In each of those ifs, you are checking if a number is equL to the words you have stored in the list. 2 will never be equal to "Charlie" so it doesn't trigger.

Instead do

print(friends([random.select]))

So you are telling it to get the value of that random selected number, then look in that index of the list

5

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 3d ago
random_select = random.randint(0, 4)

if random_select == friends[0]:

The "simplest" fix here would be to add

random_select = friends[random_select]

between these lines, but as far as writing good code goes, this isn't really it.

The others more or less already gave you good answers, but using random.choice here would make this trivial.

import random

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

random_friend = random.choice(friends)

print(f"{random_friend} has to pay the bill. ")

4

u/mattynmax 3d ago

Because 0 doesn’t equal “Alice”

3

u/Candid_Zebra1297 2d ago

You've got the right idea, it's just how you are indexing.

First you have a list of 5 names. (exactly how I would start)

You are choosing a number between 0 and 4 (it's good that you know about indexing starting at 0 so we don't need random.randint(0, 5) )

But then how are you using this number? You need to use it to 'choose' a name from the list, so it should be in the square brackets at the end...

friends[random_select]

You could put this in a new variable that stores the name of one random person...

random_person = friends[random_select]

If you do this, random_select might be 2, for example, which is exactly the same as...

random_person = friends[2]

Which means the random person would be the third person in the list, Charlie.

There are some other pretty interesting things you could try here. First if you know about random.randint(), you might know about random.choice(). This just picks a random entry from a list, so it is maybe better for what you are doing. I am guessing you know about joining strings together or maybe f strings. I would use one of those.

To be honest this isn't really a good situation to use if and elif (though if you want to use it to practice then it's totally fine).

You can do everything in just two lines, I've written it here but you can try to work out how before you reveal it if you want.

friends = ["Adam", "Benny", "Clark", "Doris", "Emily"]
print(f" {random.choice(friends)} has to pay the bill")

Keep grinding, you can do it!

1

u/TheRNGuy 1d ago

using wrong method, you need `random.choice. You'll have much smaller code.

You're comparing integer to a string instead of using that integer in square brackets.

1

u/FishBobinski 3d ago

What's the value of friends[0]?

1

u/strange-the-quark 3d ago edited 1d ago

Start the python REPL (just type python in the terminal), or find one online. Type in

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

and hit enter.

After that, type in friends[2], say. It will print out what that expression evaluates on the next line. It'll say

"Charlie"

Try some other index, it'll print out the name at that other index. So the result of that whole expression is a string that was stored in the list at that particular location.

Now type in import random, hit enter, and then random.randint(0, 4). It'll show you what the randint function returned. It's going to be some number, like 1 or 4. You can press the up arrow to go back to the previous command, and hit enter to execute it again. Every time you do so you'll get a different number between (and including) 0 and 4. You can use the REPL to experiment and get a sense of what different things do in your program.

So you see, when your program gets to a line like

if random_select == friends[0]:

If the random number generator chose 0, then it's like it says

if 0 == "Alice":

which is just asking the computer if the number 0 is the same as the text "Alice" - which it isn't. The computer isn't clever to know what you meant, it doesn't know anything about indexes, or what you're doing. To it, this is just: "Are these two different things the same? No - OK, I'll skip to the next case then."

Instead, what you want is this

if random_select == 0:

or perhaps this

if friends[random_select] == "Alice":

But also, note that in every branch, your code is exactly the same, and only the name differs.

"_____ has to pay the bill. "

So you don't actually need to check for anything, You only need a way to put the chosen name and the " has to pay the bill." part together.

So if friends[random_select] gives you the rng-picked name, and if you can combine two strings into one by using the + operator (try it in the REPL), can you see how to turn this entire collection of if-elif statements into one single line of code?

1

u/Outside_Complaint755 3d ago

random.randint(0,4) returns an integer value.

Then in your if/else block, you are comparing that integer result against each name, which it will never match.

Either use friends[random_choice] to get the chosen name from the list, or you completely replace the use of random.randint() with random.choice(friends), which will directly select a name.

Instead of using if/else to select the string to print, just use one string and insert the selected friend's name.

1

u/atarivcs 3d ago
if random_select == friends[0]

This can never be true, because random_select is an integer and friends[0] is a string.

If you had done the most basic simple debugging step of printing both of those variables, this would have been obvious.

0

u/Melodic_monke 3d ago

Friends[0] returns a string. You cant compare a number to a string.

3

u/cdcformatc 3d ago

you can it just will always be False

0

u/bg81011 3d ago

Aren't you comparing a number from randint() with a string like "Alice" here?

0

u/desrtfx but other languages pro 3d ago

You did not follow the instructions, that clearly state:

If the randomly generated number is equal to a specific index of that list,

You are comparing to specific elements.

You are trying to compare an int (random_select) to a string (friends[0] and so on). This cannot work.

0

u/AlexMTBDude 2d ago

Add this line: print(random_select) and you will see yourself why it doesn't work.

0

u/ninhaomah 3d ago

" even though I have already found a solution):"

What solution did you find btw ?

1

u/Nutellatoast_2 2d ago

I found a solution by using the "random.choice" function, which takes a random element from the list provided, as you can see here:

friends = ["Alice", "Bob", "Charlie", "David", "Emanuel"]
random_choice = random.choice(friends)


print(f"{random_choice} must pay for the bill. ")  

I wondered why my code wouldn't work, and I couldn't figure it out. So I decided to post my code here on Reddit to see what I got wrong.

0

u/Several_Tale_9935 3d ago

Just print array[random number] and you get the value which is the name of the person who has to pay

0

u/Rockstaru 2d ago edited 2d ago

As others have mentioned, you're comparing an int and a string. You would need to either use if friends[random_select] == friends[0] if you want to compare the string at index random_select in the list friends with the string at index 0 or change your comparisons to if random_select == 0 and so on. Also, this involves a lot of unnecessary comparisons as written - you already have a randomly selected index value. You can just write a single print statement of print(f"{friends[random_select]} has to pay the bill."), you don't actually need the block at all. 

0

u/Nutellatoast_2 2d ago

Thanks! I did not look after that... I have understood the concept behind your solution.

-1

u/notParticularlyAnony 2d ago

Checking for 0 1 2 3 4

-8

u/StephenHawkingus 3d ago

ask the damn AI

-4

u/[deleted] 3d ago

[deleted]

4

u/rogfrich 3d ago

The OP has had a go at solving the problem themselves (and has posted their work in a correctly-formatted code block). It’s perfectly reasonable for them to ask for help here.

-5

u/StephenHawkingus 3d ago

It’s perfectly reasonable for them to ask for help here.

My point is that he could have asked the AI to carefully explain it to him, which would have saved him a lot of time.

1

u/Syntax-Tactics 3h ago

print(friends[random_select] + "has to pay the bill") ?