Struggling with printing - python

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)

Related

Python: Error occurring in IF/ELIF statement

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

How to get final grand total in a program?

This program will ask the user for the number of half-dollars, quarters, dimes, nickels, and pennies s/he has and then compute the total value. The total value of the change is shown both as the total number of cents and then as the separate number of dollars and cents. I want to include a final total that displays after the user is finished; which will display the total of all amounts entered throughout the session(i.e. all loop iterations). So how can I code this?
#getCoin function
def getCoin(coinType):
c = -1
while c < 0:
try:
c = int(input("How many " + coinType + " do you have? "))
if c < 0:
print("Coin counts cannot be negative. Please re-enter.")
except ValueError:
print("llegal input. Must be non-negative integer. Re-enter.")
c = -1
return c
print("Welcome to the Change Calculator")
print()
choice = input ("Do you have any change (y/n)?")
while choice.lower() == "y":
h = getCoin("Half-Dollars")
q = getCoin("Quarters")
d = getCoin("Dimes")
n = getCoin("Nickel")
p = getCoin("Pennies")
print()
TotalVal = (h*50) + (q*25) + (d*10) + (n*5) + p
print("You have " + str(TotalVal) + " cents.")
dollars = TotalVal // 100 # // is for division but only returns whole num
cents = TotalVal % 100 # % is for modulos and returns remainder of whole number
print("Which is " + str(dollars) + " dollars and " + str(cents) + " cents.")
choice = input("Do you have more change (y/n)? ")
print("Thanks for using the change calculator.")
finalTotal = TotalVal
print("You had a total of" + finalTotal + " cents.")
print("Which is" + str(finalTotalDollars) + " dollars and" + str(finalTotalCents) + " cents.")
To make it so when a user wants to play again, you could use an external file to write to and read from using open, read and write, to store user info.
You could use notepad as .txt and write user name, money, and repeat, so login checks and calls the money at the line after the name.

Python: local variable referenced before assigment

I'm very new to python (~1 wk). I got this error when trying to run this code, intended to be a simple game where you guess heads or tails and it keeps track of your score. Is there any way I can avoid this error? I get the error for the "attempts" variable when I run attempts += 1, but I assume I'd get it for "score" too when I do the same.
import random
coin = ['heads', 'tails']
score = 0
attempts = 0
def coin_flip():
print("Heads or tails?")
guess = input()
result = random.choice(coin)
print("Your guess: " + guess)
print("Result: " + result)
attempts += 1
if result == guess:
print('You guessed correctly!')
score += 1
else:
print('Your guess was incorrect.')
percentCorrect = str((score / attempts) * 100) + '%'
print("You have " + str(score) + " correct guesses in " + str(attempts) + ' attempts.')
print("Accuracy: " + percentCorrect)
print('Do you want to play again?')
if input() == 'y' or 'yes':
return coin_flip()
else:
quit()
coin_flip()
import random
coin = ['heads', 'tails']
score = 0
attempts = 0
def coin_flip():
global attempts
global score
print("Heads or tails?")
guess = input()
result = random.choice(coin)
print("Your guess: " + guess)
print("Result: " + result)
attempts += 1
if result == guess:
print('You guessed correctly!')
score += 1
else:
print('Your guess was incorrect.')
percentCorrect = str((score / attempts) * 100) + '%'
print("You have " + str(score) + " correct guesses in " + str(attempts) + ' attempts.')
print("Accuracy: " + percentCorrect)
print('Do you want to play again?')
if input() == 'y' or 'yes':
return coin_flip()
else:
quit()
coin_flip()
What was missing:
global attempts
global score
This is an issue with scoping. Either put the word global in front of attemps and score, or create a class (which would not be ideal for what I assume you're doing).

How To Create A Table in Python

I've posted this before, but I'm reposting it with more detailed information.
This is my assignment:
And, so far, this is my code:
# Define a function that caculates average test scores
def calculate_average(score1, score2, score3, score4, score5):
total = score1 + score2 + score3 + score4 + score5
average = total % 5
print(average)
# Define a function that determines a letter grade
# Based on the given score
def determine_grade(score):
if score < 60:
print 'F'
elif score => 60 or score <= 69:
print 'D'
elif score => 70 or score <= 79:
print 'C'
elif score => 80 or score <= 89:
print 'B'
elif score => 90 or score <= 100:
print 'A'
# Define a function that prompts the user to input names and test scores
def input_data():
score1 = input('Enter score 1:')
name1 = input('Enter name 1:')
score2 = input('Enter score 2:')
name2 = input('Enter name 2:')
score3 = input('Enter score 3:')
name3 = input('Enter name 3:')
score4 = input('Enter score 4:')
name4 = input('Enter name 4:')
score5 = input('Enter score 5:')
name5 = input('Enter name 5:')
# Define a function that displays a letter grade for each score
# followed by the student's name and the average test score
def display_menu():
As I said in the first post, I don't have a real problem with anything except setting up that table. I'm really confused!
I asked my instructor (this is an online course, BTW), and he said: "Its just using the print operator, like you have done in previous modules, your printing text , variables and the return value of a function."
Now I'm just wondering where to start.
EDIT: I've updated my code this:
# Define a function that prompts the user to input names and test scores
def input_data():
score1 = input('Enter score 1:')
name1 = input('Enter name 1:')
score2 = input('Enter score 2:')
name2 = input('Enter name 2:')
score3 = input('Enter score 3:')
name3 = input('Enter name 3:')
score4 = input('Enter score 4:')
name4 = input('Enter name 4:')
score5 = input('Enter score 5:')
name5 = input('Enter name 5:')
# Define a function that determines a letter grade
# Based on the given score
def determine_grade(score):
if score < 60:
print ('F')
elif 60 <= score <= 69:
print ('D')
elif 70 <= score <= 79:
print ('C')
elif 80 <= score <= 89:
print ('B')
elif 90 <= score <= 100:
print ('A')
# Define a function that caculates average test scores
def calculate_average(score1, score2, score3, score4, score5):
total = score1 + score2 + score3 + score4 + score5
average = total / 5
print(average)
# Define a function that displays a letter grade for each score
# followed by the student's name and the average test score
def display_menu():
for x in range(10):
print("{:<10}".format("{:0.1f}".format(x)), end='')
print ("Name\t\t\tnumeric grade\t\tletter grade")
print ("---------------------------------------------------------------")
print ("%s:\t\t\t%f\t\t%s") % ('name1', 'score1', determine_grade)
print ("%s:\t\t\t%f\t\t%s") % ('name2', 'score2', determine_grade)
print ("%s:\t\t\t%f\t\t%s") % ('name3', 'score3', determine_grade)
print ("%s:\t\t\t%f\t\t%s") % ('name4', 'score4', determine_grade)
print ("%s:\t\t\t%f\t\t%s") % ('name5', 'score5', determine_grade)
print ("---------------------------------------------------------------")
But when I run it:
EDIT #2: This is my code currently:
# Define a function that prompts the user to input names and test scores
def input_data():
score1 = input('Enter score 1:')
name1 = input('Enter name 1:')
score2 = input('Enter score 2:')
name2 = input('Enter name 2:')
score3 = input('Enter score 3:')
name3 = input('Enter name 3:')
score4 = input('Enter score 4:')
name4 = input('Enter name 4:')
score5 = input('Enter score 5:')
name5 = input('Enter name 5:')
# Define a function that caculates average test scores
def calculate_average(score1, score2, score3, score4, score5):
total = score1 + score2 + score3 + score4 + score5
average = total / 5
print(average)
# Define a function that determines a letter grade
# Based on the given score
def determine_grade(score):
if score < 60:
print ('F')
elif 60 <= score <= 69:
print ('D')
elif 70 <= score <= 79:
print ('C')
elif 80 <= score <= 89:
print ('B')
elif 90 <= score <= 100:
print ('A')
# Define a function that displays a letter grade for each score
# followed by the student's name and the average test score
def display_menu():
print ("Name\t\t\tnumeric grade\t\tlettergrade")
print ("---------------------------------------------------------------")
print ("%s:\t\t\t%f\t\t%s" % ('name1', 93, 'A'))
print ("%s:\t\t\t%f\t\t%s" % ('name2', 89, 'B'))
print ("%s:\t\t\t%f\t\t%s" % ('name3', 76, 'C'))
print ("%s:\t\t\t%f\t\t%s" % ('name4', 58, 'F'))
print ("%s:\t\t\t%f\t\t%s" % ('name5', 98, 'A'))
print ("---------------------------------------------------------------")
print (calculate_average)
And this is what happens when I run it:
Now, I have mainly two problems:
1) How do I get the input statements to execute and enter the data BEFORE the table is displayed?
2) How do I convert the numbers displayed so that they are in the '.2f' format? (I've already tried a few ways and none of them worked).
HOPEFULLY THE FINAL EDIT: I'm getting really close to the solution, but need help with a few more things.
Here is my code:
# Define a function that prompts the user to input names and test scores
score = input('Enter score 1:')
name1 = input('Enter name 1:')
score = input('Enter score 2:')
name2 = input('Enter name 2:')
score = input('Enter score 3:')
name3 = input('Enter name 3:')
score = input('Enter score 4:')
name4 = input('Enter name 4:')
score = input('Enter score 5:')
name5 = input('Enter name 5:')
# Define a function that determines a letter grade
# Based on the given score
def determine_grade(score):
if score < 60:
print ('F')
elif 60 <= score <= 69:
print ('D')
elif 70 <= score <= 79:
print ('C')
elif 80 <= score <= 89:
print ('B')
elif 90 <= score <= 100:
print ('A')
determine_grade(score)
# Define a function that caculates average test scores
def calculate_average(score):
total = score + score + score + score + score
average = total / 5
print(average)
calculate_average(score)
# Define a function that displays a letter grade for each score
# followed by the student's name and the average test score
def display_menu():
print ("Name\t\t\tnumeric grade\t\tlettergrade")
print ("---------------------------------------------------------------")
print ("%s:\t\t\t%f\t\t%s" % ('name1', 'score', determine_grade('score')))
print ("%s:\t\t\t%f\t\t%s" % ('name2', 'score', determine_grade('score')))
print ("%s:\t\t\t%f\t\t%s" % ('name3', 'score', determine_grade('score')))
print ("%s:\t\t\t%f\t\t%s" % ('name4', 'score', determine_grade('score')))
print ("%s:\t\t\t%f\t\t%s" % ('name5', 'score', determine_grade('score')))
print ("---------------------------------------------------------------")
calculate_average(score)
And this is what happens when I press F5:
GUYS, I'M ALMOST DONE JUST NEED HELP WITH FORMATTING:
I created another file so I could reorganize my code a bit, so that's why there's no comments. This is what I have:
score1 = float(input('Enter score 1:'))
name1 = input('Enter name 1:')
score2 = float(input('Enter score 2:'))
name2 = input('Enter name 2:')
score3 = float(input('Enter score 3:'))
name3 = input('Enter name 3:')
score4 = float(input('Enter score 4:'))
name4 = input('Enter name 4:')
score5 = float(input('Enter score 5:'))
name5 = input('Enter name 5:')
def determine_letter_grade1(score1):
if score1 < 60.0:
print ('F')
elif 60.0 <= score1 <= 69.0:
print ('D')
elif 70.0 <= score1 <= 79.0:
print ('C')
elif 80.0 <= score1 <= 89.0:
print ('B')
elif 90.0 <= score1 <= 100.0:
print ('A')
def determine_letter_grade2(score2):
if score2 < 60.0:
print ('F')
elif 60.0 <= score2 <= 69.0:
print ('D')
elif 70.0 <= score2 <= 79.0:
print ('C')
elif 80.0 <= score2 <= 89.0:
print ('B')
elif 90.0 <= score2 <= 100.0:
print ('A')
def determine_letter_grade3(score3):
if score3 < 60.0:
print ('F')
elif 60.0 <= score3 <= 69.0:
print ('D')
elif 70.0 <= score3 <= 79.0:
print ('C')
elif 80.0 <= score3 <= 89.0:
print ('B')
elif 90.0 <= score3 <= 100.0:
print ('A')
def determine_letter_grade4(score4):
if score4 < 60.0:
print ('F')
elif 60.0 <= score4 <= 69.0:
print ('D')
elif 70.0 <= score4 <= 79.0:
print ('C')
elif 80.0 <= score4 <= 89.0:
print ('B')
elif 90.0 <= score4 <= 100.0:
print ('A')
def determine_letter_grade5(score5):
if score5 < 60.0:
print ('F')
elif 60.0 <= score5 <= 69.0:
print ('D')
elif 70.0 <= score5 <= 79.0:
print ('C')
elif 80.0 <= score5 <= 89.0:
print ('B')
elif 90.0 <= score5 <= 100.0:
print ('A')
average = (score1 + score2 + score3 + score4 + score5) / 5.0
def determine_letter_grade_avg(average):
if average < 60.0:
print ('F')
elif 60.0 <= average <= 69.0:
print ('D')
elif 70.0 <= average <= 79.0:
print ('C')
elif 80.0 <= average <= 89.0:
print ('B')
elif 90.0 <= average <= 100.0:
print ('A')
def display_menu():
for x in range(10):
print("{:<10}".format("{:0.1f}".format(x)), end='')
print ("Name\t\t\tnumeric grade\t\tletter grade")
print ("---------------------------------------------------------------")
print ("%s:\t\t\t%f\t\t%s" % (name1, score1, determine_letter_grade1(score1)))
print ("%s:\t\t\t%f\t\t%s" % (name2, score2, determine_letter_grade2(score2)))
print ("%s:\t\t\t%f\t\t%s" % (name3, score3, determine_letter_grade3(score3)))
print ("%s:\t\t\t%f\t\t%s" % (name4, score4, determine_letter_grade4(score4)))
print ("%s:\t\t\t%f\t\t%s" % (name5, score5, determine_letter_grade5(score5)))
print ("---------------------------------------------------------------")
print ('Average Score:', average, determine_letter_grade_avg(average))
And when I run it:
You should be looking towards str.format() and end='' for your print statement
Here's a little example
for x in range(10):
print("{:<10}".format("{:0.1f}".format(x)), end='')
The first part for the rounding to 1 decimal place for your float values is
"{:0.1f}".format(x)
The 0 is for no left padding, the following .1f is for rounding to 1 decimal place. Next is the main part
"{:<10}".format(...)
This will print with a minimum string length of 10 characters. So if you have a string such as Hello it is printed as Hello_____ ( _ to represent empty spaces) The 10 can be changed to a value of your choosing.
Finally the end=''. By default the end parameter is \n which is what creates the new line after each print, but by changing it you can form lines from multiple print statements. Just print normally or set end='\n' when you want to end the line.
Little something to note as well. When checking if a value is between two integers you can use this instead of checking it twice (also you would need and and operator instead of or )
elif 60 <= score <= 69:
You could do something like this:
def display_menu():
print "Name\t\t\tnumeric grade\t\tlettergrade"
print "---------------------------------------------------------------"
print "%s:\t\t\t%f\t\t%s" % ('name1', 50, 'F')
print "%s:\t\t\t%f\t\t%s" % ('name2', 50, 'F')
print "%s:\t\t\t%f\t\t%s" % ('name3', 23, 'F')
print "%s:\t\t\t%f\t\t%s" % ('name4', 44, 'F')
print "%s:\t\t\t%f\t\t%s" % ('name5', 48, 'F')
print "---------------------------------------------------------------"
display_menu()
I used \t to give tabs in between.
This is the screenshot of the PythonShell Output
Well, I just got the solution back, and I did a real butchering on the code. But, I will post this so no one will have to suffer like I did:
# main function
def main():
# Local variables only have to define floats
average = 0.0
score1 = 0.0
score2 = 0.0
score3 = 0.0
score4 = 0.0
score5 = 0.0
# Get scores
score1 = float(input('Enter score 1:'))
name1 = input('Enter name 1:')
score2 = float(input('Enter score 2:'))
name2 = input('Enter name 2:')
score3 = float(input('Enter score 3:'))
name3 = input('Enter name 3:')
score4 = float(input('Enter score 4:'))
name4 = input('Enter name 4:')
score5 = float(input('Enter score 5:'))
name5 = input('Enter name 5:')
# Calculate average grade
average = calculate_average(score1, score2, score3, score4, score5)
#Display grade and average information in tabular form
print('Name\t\tnumeric grade\tletter grade')
print('----------------------------------------------------')
print(name1 + ':\t\t', score1, '\t\t', determine_grade(score1))
print(name2 + ':\t\t', score2, '\t\t', determine_grade(score2))
print(name3 + ':\t\t', score3, '\t\t', determine_grade(score3))
print(name4 + ':\t\t', score4, '\t\t', determine_grade(score4))
print(name5 + ':\t\t', score5, '\t\t', determine_grade(score5))
print('----------------------------------------------------')
print ('Average score:\t', average, '\t\t', \
determine_grade(average))
# The calc_average function returns average of 5 grades
def calculate_average(s1, s2, s3, s4, s5):
return (s1 + s2 + s3 + s4 + s5) / 5.0
# The determine_grade function receives a numeric
# grade and returns the corresponding letter grade
def determine_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
# Call the main function.
main()

grade input program python if else elif

I am trying to solve this grade input program. I need to input the grades between 0.6 to 1.0 and assign them a letter value. I can only use the if else method as we haven't gotten to the other methods yet in class...
score = raw_input("Enter Score Grade:")
sco = int(float(score))
if score < 0.60:
print "Your grade is an F"
elif score >= 0.6:
print "grade d"
elif score >= 0.7:
print "grade c"
elif score >= 0.8:
print "grade b"
elif score >= 0.9:
print "grade a"
else:
print "wrong score"`
You don't have to go highest to lowest score, you can also do this:
score = float(raw_input("Enter Score Grade:"))
if score < 0.60:
print "Your grade is an F"
elif score < 0.7:
print "grade d"
elif score < 0.8:
print "grade c"
elif score < 0.9:
print "grade b"
elif score <= 1.0:
print "grade a"
else:
print "wrong score"
If you do decide to check from highest to lowest, being consistent is a good practice. You can check your failing grade last:
score = float(raw_input("Enter Score Grade:"))
if score > 1:
print "wrong score"
elif score >= 0.9:
print "grade a"
elif score >= 0.8:
print "grade b"
elif score >= 0.7:
print "grade c"
elif score >= 0.6:
print "grade d"
else:
print "Your grade is an F"
As a reusable function :
def grade(score):
if score > 1:
return "wrong score"
if score >= 0.9:
return "grade a"
if score >= 0.8:
return "grade b"
if score >= 0.7:
return "grade c"
if score >= 0.6:
return "grade d"
return "Your grade is an F"
score = float(raw_input("Enter Score Grade:"))
print grade(score)
You should start from the largest grade first:
as you see 0.92 > 0.6 and also 0.92 > 0.9
But according to yout logic, it will satisfy the first if and will never reach last if.
Do something like this:
score = raw_input("Enter Score Grade:")
sco = int(float(score))
if score < 0.60:
print ("Your grade is an F")
elif score >= 0.9:
print ("grade a")
elif score >= 0.8:
print ("grade b")
elif score >= 0.7:
print ("grade c")
elif score >= 0.6:
print ("grade d")
else:
print ("wrong score")
You need to go from high grade to low grade. You need to change sco = int(float(score)) to score = float(score). It is not required to change it to int as you are comparing float
score = raw_input('Enter the Score')
score = float(score)
if score >= 0.9:
grade = 'A'
elif score >= 0.8:
grade = 'B'
elif score >= 0.7:
grade = 'C'
elif score >= 0.6:
grade = 'D'
else:
grade = 'F'
print 'Your Grade : ' + grade
You have to take not of the first condition. If the first condition is equal to 0.9, it will equate to false and give the grade of 'B'. Also, it will be wise to convert the input to int first
score = int(raw_input('Enter the Score'))
score = float(score)
if score > 0.9:
grade = 'A'
elif score >= 0.8:
grade = 'B'
elif score >= 0.7:
grade = 'C'
elif score >= 0.6:
grade = 'D'
else:
grade = 'F'
print 'Your Grade : ' + grade
It is therefore advisable to use the greater than or equal to so as to handle the situation when it is equal to the upper value(ie 0.9).
score = int(raw_input('Enter the Score'))
score = float(score)
if score >= 0.9:
grade = 'A'
elif score >= 0.8:
grade = 'B'
elif score >= 0.7:
grade = 'C'
elif score >= 0.6:
grade = 'D'
else:
grade = 'F'
print 'Your Grade : ' + grade

Categories