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) )
CodePudding user response:
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:
CodePudding user response:
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')