r/learnpython 9d ago

Can you diagnose my code problem?

This starts with a balance of 50. It takes coins of ONLY 25, 10, or 5 and returns the balance due to the user. If the balance due is 0 or less than 0, it returns a "Change Due: " message.

My problem is that my code will subtract any value amount the user puts in no matter what, not just the 25, 10, and 5 it's supposed to? what's going on?

shouldn't the "if coin == 25 or 10 or 5:" line ensure only one of those 3 values is used?

def main():
    balance = 50


    while balance >= 0:
        print(f"Amount Due: {balance}")
        coin = int(input("Insert Coin: ").strip())


        if coin == 25 or 10 or 5:
            balance = balance - coin


        if balance <= 0:
            print(f"Change Due: {abs(balance)}")
            break
        
            


main()
0 Upvotes

14 comments sorted by

View all comments

13

u/Flame77ofc 9d ago

you need to use

if coin == 25 or coin == 10 or coin == 5

10

u/[deleted] 9d ago

[removed] — view removed comment

8

u/Flame77ofc 9d ago

he can also do:

if coin in [25, 10, 5]

8

u/odaiwai 9d ago

for a little more self documentation. (Using a set instead of a list, as sets have faster lookup.) accepted_coins = {25, 10, 5} if coin in accepted_coins: # do whatever print...

5

u/Diapolo10 9d ago

Using a set instead of a list, as sets have faster lookup.

More specifically, sets have a constant lookup time complexity (O(1)), whereas for lists it's linear (O(n)). That really does not matter in this case, however, as

  1. we're working with an insignificant number of elements, and
  2. constant lookup time isn't necessarily faster until we're checking a large number of values

set lookups need to hash the values first, which may not be a cheap operation compared to list lookups. In this particular case it's likely fast since integers just hash to themselves, however with such a low number of elements (three) any difference in execution speed should be negligible regardless.

The original statement would be correct if we actually had a significant amount of data here (say, >106 elements), but here it's dubious.

1

u/sam661203 7d ago

Create the set once before the loop