python if elif else statement
- you should get integer from raw_input, not string. use
int()
. - comparison values like 50, 100, 150, ... also should be
integer
.
below is fixed code.
total = int(raw_input('What is the total amount for your online shopping?'))
country = raw_input('Shipping within the US or Canada?')
if country == "US":
if total <= 50:
print "Shipping Costs $6.00"
elif total <= 100:
print "Shipping Costs $9.00" # improved indentation
elif total <= 150:
print "Shipping Costs $12.00" # improved indentation
else:
print "FREE"
if country == "Canada":
if total <= 50:
print "Shipping Costs $8.00"
elif total <= 100:
print "Shipping Costs $12.00"
elif total <= 150:
print "Shipping Costs $15.00"
else:
print "FREE"
You are comparing strings numerically. That's impossible, like comparing apple
with orange
, which one is bigger? The computer won't understand that, it needs to compare the size.
To do that, we need to convert it to an integer. Use the int()
function. Here:
#convert it to an integer straight away
total = int(raw_input('What is the total amount for your online shopping?'))
country = raw_input('Shipping within the US or Canada?')
if country == "US":
if total <= 50:
print "Shipping Costs $6.00"
elif total <= 100:
print "Shipping Costs $9.00"
elif total <= 150:
print "Shipping Costs $12.00"
else:
print "FREE"
if country == "Canada":
if total <= 50:
print "Shipping Costs $8.00"
elif total <= 100:
print "Shipping Costs $12.00"
elif total <= 150:
print "Shipping Costs $15.00"
else:
print "FREE"
Hope this helps!
You can't compare Strings numerically. Instead convert to an int first and then compare.
For example:
if int(total) < 50
Variables to avoid duplication would help too.
When you compare strings it does so lexicographically, like in a phone book. For example:
"a" < "b"
: True"bill" < "bob"
: True"100" < "3"
: True
If you want to compare numbers in the order that we count them you need to use the int type.
total = int(raw_input('What is the total amount for your online shopping?'))
Then change all of the string literals in your code like "50"
to integer literals like 50
.