Python: Error occurring in IF/ELIF statement - python

I have a program I need to write for college and I have an error in my code that I don't know how to fix
#calculate savings and print users total cost
if voucher_quant < 20:
print("Your total will be £", str(voucher_value*voucher_quant))
elif voucher_quant => 20 and voucher_quant=<40:
print("Your total will be £", str((voucher_value*voucher_quant)*0.05)
elif voucher_quant =>41 and voucher_quant =<70:
print("Your total will be £", str((voucher_value*voucher_quant)*0.075)
elif voucher_quant =>71 and voucher_quant =<100:
print("Your total will be £", str((voucher_value*voucher_quant)*0.1)
can anyone help me on how to fix this?

elif has to be at same identation level as its if is.
Comparison operators are like <= and not =<. = would be latter
Your print statements do not complete brackets
This code is correct syntactically
voucher_quant = 50 # Change as you want
voucher_value = 10 # Change as you want
if voucher_quant < 20:
print("Your total will be £", str(voucher_value*voucher_quant))
elif voucher_quant >= 20 and voucher_quant<=40:
print("Your total will be £", str((voucher_value*voucher_quant)*0.05))
elif voucher_quant >= 41 and voucher_quant <= 70:
print("Your total will be £", str((voucher_value*voucher_quant)*0.075))
elif voucher_quant >= 71 and voucher_quant<=100:
print("Your total will be £", str((voucher_value*voucher_quant)*0.1))
#Output
#Your total will be £ 37.5

Related

Struggling with printing

Below is a program that's meant to calculate a percentage and print a message telling them what grade they received based on what percentage of their score was. problem is every time I run it I get the message:
TypeError: can only concatenate str (not "float") to str
I'm incredibly new to python and would appreciate any help.
score = input("Please enter your score:")
percentage = float(score) / 50 * 100
print(percentage)
if float(score) <59.99:
print("you have passed with " + percentage + "%" + " , and received a grade F")
elif float(score) >60 and float(score) <69.99:
print("you have passed with " + percentage + "%" + " , and received a grade D")
elif float(score) >70 and float(score) <79.99:
print("you have passed with " + percentage + "%" + " , and received a grade C")
elif float(score) >80 and float(score) <89.99:
print("you have passed with " + percentage + "%" + " , and received a grade B")
elif float(score) >90 and float(score) <100:
print("you have passed with " + percentage + "%" + " , and reveived a grade A")
elif float(score) <50:
print("Score is greater than 50.")
update: thanks for the help it's running perfectly now, code below is for reference
score = input("Please enter your score:")
percentage = float(score) / 50 * 100
print(percentage)
if float(score) < 30:
print("you have passed with ", percentage, "%", " , and received a grade F")
elif float(score) >=30 and float(score) <35:
print("you have passed with ", percentage, "%", " , and received a grade D")
elif float(score) >=35 and float(score) <40:
print("you have passed with ", percentage, "%", " , and received a grade C")
elif float(score) >=40 and float(score) <45:
print("you have passed with ", percentage, "%", " , and received a grade B")
elif float(score) >=45 and float(score) <=50:
print("you have passed with ", percentage, "%", " , and reveived a grade A")
elif float(score) >50:
print("Score is greater than 50.")
Line 15
elif float(score) <50:
score is a string. So you need to do the same thing you did in line 2.
Try this
# Python Program to Calculate Total Marks Percentage and Grade of a Student
print("Enter the marks of five subjects::")
subject_1 = float (input ())
subject_2 = float (input ())
subject_3 = float (input ())
subject_4 = float (input ())
subject_5 = float (input ())
total, average, percentage, grade = None, None, None, None
# It will calculate the Total, Average and Percentage
total = subject_1 + subject_2 + subject_3 + subject_4 + subject_5
average = total / 5.0
percentage = (total / 500.0) * 100
if average >= 90:
grade = 'A'
elif average >= 80 and average < 90:
grade = 'B'
elif average >= 70 and average < 80:
grade = 'C'
elif average >= 60 and average < 70:
grade = 'D'
else:
grade = 'E'
# It will produce the final output
print ("\nThe Total marks is: \t", total, "/ 500.00")
print ("\nThe Average marks is: \t", average)
print ("\nThe Percentage is: \t", percentage, "%")
print ("\nThe Grade is: \t", grade)

Implement program to accept only certain coins

I've nearly finished my program but have to add a feature so it only accepts certain coins and will throw a message if a wrong coin is inserted.
any help would be appreciated
def main():
total = 0
coins = [10, 20, 30]
while True:
total += int(input("Insert one coin at a time: ").replace('"', '').replace("'", '').strip())
coke = 50
print(total)
if total > coke:
print("Change Owed =", total - coke)
return
elif total == coke:
print("No Change Owed, Here's a coke ")
return
else:
print("Amount Due =", coke-total)
main()
As suggested by #Barmar, create a list of allowed coins and make sure the input falls in the list:
def main():
total = 0
allowed_coins = [25,50,100]
coke = 50
while True:
coin_input = int(input("Insert one coin at a time: ").replace('"', '').replace("'", '').strip())
if coin_input not in allowed_coins:
print("Invalid Coin Amount Due =", coke - total)
return
total = total + coin_input
if total > coke:
print("Change Owed =", total - coke)
return
elif total == coke:
print("No Change Owed, Here's a coke ")
return
else:
print("Amount Due =", coke-total)
main()
You need to check the coin before adding it to total. If it's not valid, skip the rest of the loop and ask again
def main():
total = 0
coins = [10, 20, 30]
while True:
coin = int(input("Insert one coin at a time: ").replace('"', '').replace("'", '').strip())
if coin not in coins:
print("That's not an allowed coin, try again")
continue
total += coin
coke = 50
print(total)
if total > coke:
print("Change Owed =", total - coke)
return
elif total == coke:
print("No Change Owed, Here's a coke ")
return
else:
print("Amount Due =", coke-total)
main()

If else statement not outputting correctly?

I'm a beginner to Python and am struggling with a project I am working on. The program takes monthly income, fixed monthly expenses, asks for any additional expenses, and then outputs with an if else statement. My issue is in this function:
def spending(income, totals):
finalTotal = income - totals
if income > finalTotal:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif finalTotal > income:
print("You overspent by $", "%.2f"%finalTotal, "this month!")
else:
print("You broke even this month!")
It is printing:
You saved $ -805.00 this month!
When I'd like it to print:
You overspent by $ 805.00 this month!
Any feedback would be greatly appreciated!!
Here is my code:
https://replit.com/#ashleyshubin/BudgetProgram#main.py
If totals is your monthly expenses, then subtracting totals from income gives you how much money you made this month. The first if statement should be
if finalTotal > 0:
The second if statement would be
if finalTotal < 0:
And you would want to use abs(finalTotal) when printing finalTotal so it does not display a negative number
Your checks are wrong. You can do the following:
def spending(income, totals):
finalTotal = income - totals
if income > totals:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif totals > income:
print("You overspent by $", "%.2f"%-finalTotal, "this month!")
else:
print("You broke even this month!")
This section is where it is going wrong:
finalTotal = income - totals
if income > finalTotal:
print("You saved $", "%.2f"%finalTotal, "this month!")
It looks like you're comparing the wrong variables in your "if" statement. your "finalTotal" variable already includes your income. Think of it like alegbra, and replace "finalTotal" with "income - totals", and your if statement now looks like:
if income > (income - totals):
this statement will always evaluate to true, no matter what values you are using. You probably want to rewrite your if statements to compare "income > totals", rather than finalTotal.
your comparison shoud be based on finaltotal , as fianaltotal is finalTotal = income - totals, also else never runs based on the other conditions in your code:
def spending(income, totals):
finalTotal = income - totals
if finalTotal > 0:
print("You saved $", "%.2f" % finalTotal, "this month!")
else:
print("You overspent by $", "%.2f" % abs(finalTotal), "this month!")
you should be comparing Income with total spends.
def spending(income, totals):
finalTotal = abs(income - totals)
if totals < income:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif totals > income:
print("You overspent by $", "%.2f"%finalTotal, "this month!")
else:
print("You broke even this month!")

BMI Calculator not outputting Python

I'm building a BMI Calculator in Python and after choosing the metric or imperial system it won't post. The code is 100% functional other than that.
I added the option to choose if you want to use the imperial system or the metric system.
How could I improve the code?
def WeightCalMetric() :
print("BMI-Calculator")
while True:
try:
UserHeight = float(input("What's your height in meters? "))
break
except:
print("Your height has to be a number")
while True:
try:
UserWeight = float(input("What's your weight in Kg? "))
break
except:
print("Your weight has to be a number")
Bmi = UserWeight / (UserHeight ** 2)
FloatBmi = float("{0:.2f}".format(Bmi))
if FloatBmi <= 18.5:
print('Your BMI is', str(FloatBmi),'which means you are underweight.')
elif FloatBmi > 18.5 and FloatBmi < 25:
print('Your BMI is', str(FloatBmi),'which means you are a healthy weight.')
elif FloatBmi > 25 and FloatBmi < 30:
print('your BMI is', str(FloatBmi),'which means you are overweight.')
elif FloatBmi > 30:
print('Your BMI is', str(FloatBmi),'which means you are obese.')
def WeightCalImperial() :
print("BMI-Calculator")
while True:
try:
UserHeight = float(input("What's your height in inches? "))
break
except:
print("Your height has to be a number")
while True:
try:
UserWeight = float(input("What's your weight in Lbs? "))
break
except:
print("Your weight has to be a number")
Bmi = 703 * (UserWeight / (UserHeight ** 2))
FloatBmi = float("{0:.2f}".format(Bmi))
if FloatBmi <= 18.5:
print('Your BMI is', str(FloatBmi),'which means you are underweight.')
elif FloatBmi > 18.5 and FloatBmi < 25:
print('Your BMI is', str(FloatBmi),'which means you are a healthy weight.')
elif FloatBmi > 25 and FloatBmi < 30:
print('your BMI is', str(FloatBmi),'which means you are overweight.')
elif FloatBmi > 30:
print('Your BMI is', str(FloatBmi),'which means you are obese.')
print("Hi welcome to this BMI Calculator")
print("First choose if you want to use the metric system or the imperial system")
print('Write "Metric" for the metric system or write "Imperial" for the imperial system')
KgOrLbs = None
while KgOrLbs not in ("metric", "Metric", "imperial", "Imperial"):
KgOrLbs = input("Metric or Imperial? ")
if KgOrLbs == "metric, Metric":
WeightCalMetric()
elif KgOrLbs == "imperial" "Imperial":
WeightCalImperial()
I'm supposed to add more details, but I don't really have any more details, to be honest, so now I'm just writing all of this just so I can post this
You should change the while loop where you check the inputs. The code below lowercases the input and checks whether it is "metric" or "imperial", so there is no need to check for capitalized parameters
KgOrLbs = input("Metric or Imperial? ")
while KgOrLbs.lower() not in ["metric", "imperial"]:
KgOrLbs = input("Metric or Imperial? ")
if KgOrLbs.lower() == "metric":
WeightCalMetric()
elif KgOrLbs.lower() == "imperial":
WeightCalImperial()

python: grading assignment, negative value

I am working on a python lettering assignment.
90 or above is an A and so on and so on for the rest of the letter grades; but when a value is inputted as a negative number, I need the code to do nothing other than display an error.
This is what i tried so far:
#Design a Python program to assign grade to 10 students
#For each student, the program first asks for the user to enter a positive number
#A if the score is greater than or equal to 90
#B if the score is greater than or equal to 80 but less than 90
#C if the score is greater than or equal to 70 but less than 80
#D if the score is greater than or equal to 60 but less than 70
#F is the score is less than 60
#Ihen the program dispalys the letter grade for this student.
#Use while loop to repeat the above grade process for 10 students.
keep_going = 'y'
while keep_going == "y":
num = float(input("Enter a number: "))
if num >= 90:
print("You have an A")
elif num >= 80:
print("You have an 3")
elif num >= 70:
print("You have an C")
elif num >= 60:
print("You have an D")
elif (num < 60 and <= 0:
print ("You have an F")
else:
print("lnvalid Test Score.")
Original screenshot
I see three problems, all in the same line:
elif (num < 60 and <= 0:
Syntax: num < 60 and <= 0 is not a valid expression; should be num < 60 and num <= 0
Logic: num <= 0 is not what you want, it should be num >= 0
Syntax: you missed a closing bracket ).
If you change those, it should work.
grade = int(input("Enter Score:"))
print "FFFFFDCBAA"[grade//10] if grade >= 0 else "ERROR!!!!"
you just have to change your elif for below 60.
keep_going = 'y'
while keep_going == "y":
num = float(input("Enter a number: "))
if num >= 90:
print("You have an A")
elif num >= 80:
print("You have an 3")
elif num >= 70:
print("You have an C")
elif num >= 60:
print("You have an D")
elif 60 > num >= 0:
print ("You have an F")
else:
print("lnvalid Test Score.")

Categories