0

im new to coding and am learning python atm. I was writing this simple code for a discount system and it wont work for some weird reason. pls tell me whats wrong with this code

price = (input('Please type the value of your item.'))
if price >= 300:
    price = (price + ((price) * (30/100) )
elif price >= 200 and < 300:
    price = (price + ((price) * (20/100) )
elif price >= 100 and <200:
print('You need to pay' + price + '$ for your item')


    price = (price + ((price) * (10/100) ) 
  • 3
    `price >= 200 and price < 300` etc., or indeed `200 <= price < 300` – Passerby Dec 06 '21 at 04:43
  • 2
    price is still a string, use `price = int(input())` – sahasrara62 Dec 06 '21 at 04:46
  • Does this answer your question? [Determine Whether Integer Is Between Two Other Integers?](https://stackoverflow.com/questions/13628791/determine-whether-integer-is-between-two-other-integers) – wjandrea Dec 06 '21 at 04:46

2 Answers2

1

This statement isn't valid:

elif price >= 200 and < 300:

It would correctly be written as:

elif price >= 200 and price < 300:

Note that for this to work, price needs to be a numeric value; you need to convert your input() result to a float or int before trying anything mathematical with it!

However, specifying price < 300 isn't necessary in the first place, since this is an elif that can only happen if price >= 300 was false (hence price < 300 is logically implied to be true).

You can also simplify the arithmetic down; this:

price = (price + ((price) * (30/100) )

is really just the same (algebraically) as:

price = price * (1 + 30/100)

which is the same as:

price *= 1.3

Since you're going to end up with floating point numbers in most cases, you probably want to round this output to 2 decimal places:

print('You need to pay' + price + '$ for your item')

which you can do easily with an f-string:

print(f'You need to pay ${price:.2f} for your item')

All together:

price = float(input('Please type the value of your item.'))
if price >= 300:
    price *= 1.3
elif price >= 200:
    price *= 1.2
elif price >= 100:
    price *= 1.1
print(f'You need to pay ${price:.2f} for your item')
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

change from this:

if price >= 300:
    price = (price + ((price) * (30/100) )
elif price >= 200 and < 300:
    price = (price + ((price) * (20/100) )
elif price >= 100 and <200:

to this:

if price >= 300:
    price = (price + ((price) * (30/100) )
elif price >= 200 and price < 300:
    price = (price + ((price) * (20/100) )
elif price >= 100 and price < 200: