How do I stop from printing an extra input line? I'm new with python/coding
class1 = "Math"
class2 = "English"
class3 = "PE"
class4 = "Science"
class5 = "Art"
def get_input(className):
classInput = raw_input("Enter the score you received for " + className + ": ")
while int(classInput) >= 101 or int(classInput) <= -1:
print "Needs to be in the range 0 to 100"
classInput = raw_input("Enter the score you received for " + className + ": ")
return int(classInput)
def get_letter_grade(grade):
if grade >= 93:
return"A"
elif grade >= 90:
return"A-"
elif grade >= 87:
return"B+"
elif grade >= 83:
return"B"
elif grade >= 80:
return"B-"
elif grade >= 77:
return"C+"
elif grade >= 73:
return"C"
elif grade >= 70:
return"C-"
elif grade >= 67:
return"D+"
elif grade >= 63:
return"D"
elif grade >= 60:
return"D-"
else:
return"F"
print "Your " + class1 + " score is " + str(get_input(class1)) + ", you got a " +
get_letter_grade(get_input(class1))
Prints out:
Enter the score you received for Math: 85
Enter the score you received for Math: 85
Your Math score is 85, you got a B
Inside your print, you call get_input() method twice:
print "Your " + class1 + " score is " + str(get_input(class1)) + ", you got a " +
get_letter_grade(get_input(class1))
What you need to do is store your score by calling get_input() method once and use the stored value in print method:
score = get_input(class1)
print("Your " + class1 + " score is " + str(score) + ", you got a " +
get_letter_grade(score))
I would separate out your calls to get_input from your print statement, not just here, but generally.
score = str(get_input(class1))
print "Your " + class1 + " score is " + score + ", you got a " +
get_letter_grade(score)
As a rule of thumb, any user input should almost always be immediately stored in a variable to be manipulated and/or used later.
Related
I tried to append but whenever I would try to print it down in the main(), it would print the average but added up.
def letter_grade(test_score):
if int(test_score) >= 90:
grade = 'A'
elif int(test_score) >= 80:
grade = 'B'
elif int(test_score) >= 70:
grade = 'C'
elif int(test_score) >= 60:
grade = 'D'
else:
grade = 'F'
return grade
def calc_avg_grade(test_score):
average = []
func_sum = sum(test_score)
avg = func_sum/5.00
average.append(avg)
average.reverse()
return average
def main():
grades = []
i = 0
outfile = open('studentgrades.txt', 'w')
while i < 4:
name = input("Enter the student name: ")
for x in range(5):
score = float(input("Enter number grade: "))
grades.append(score)
gradle = letter_grade(score)
print(str(score) + ' - ' + gradle)
avg_grade = calc_avg_grade(grades)
avgg = avg_grade
print(name + "'s average grade is: " + str(avgg))
outfile.write(name + ', ' + str(avg_grade) + "\n")
txtcontents = outfile.read()
print(txtcontents)
if __name__ == "__main__":
main()
The part where it runs the append that I have the problem at is:
print(name + "'s average grade is: " + str(avgg))
This is def main().
I think that you are not reinitialising grades:
def main():
# grades = [] # Not Here!
i = 0
outfile = open('studentgrades.txt', 'w')
while i < 4:
name = input("Enter the student name: ")
grades = [] # here instead
for x in range(5):
score = float(input("Enter number grade: "))
grades.append(score)
gradle = letter_grade(score)
print(str(score) + ' - ' + gradle)
avg_grade = calc_avg_grade(grades)
avgg = avg_grade
print(name + "'s average grade is: " + str(avgg))
outfile.write(name + ', ' + str(avg_grade) + "\n")
txtcontents = outfile.read()
print(txtcontents)
This way you get a new empty grades for each student and avg_grade will be the right average for that student.
I wrote some code for the following problem:
"Write a program to continuously asks the user an exam score given as integer percentages in the range 0 to 100. Calculate the total number of grades in each letter-grade category as follows: 90 to 100 is an A, 80 to 89 is a B, 70 to 79 is a C, 60 to 69 is a D, and 0 to 59 is an F. Use a negative score as a sentinel value to indicate the end of the input. (The negative value is used only to end the loop, so do not use it in the calculations.)"
Here is my code:
count = 0
gradeA = 0
gradeB = 0
gradeC = 0
gradeD = 0
gradeF = 0
score = int(input("Enter an exam score: "))
while score != -1:
count = count + 1
score = int(input("Enter an exam score: "))
if score >= 90 and score <= 100:
gradeA = gradeA + 1
elif score >= 80 and score <= 89:
gradeB = gradeB + 1
elif score >= 70 and score <= 79:
gradeC = gradeC + 1
elif score >= 60 and score <= 69:
gradeD = gradeD + 1
elif score >= 0 and score <= 59:
gradeF = gradeF + 1
print ("You entered " + str(count) + " exam scores.")
print ("Number of A's = " + str(gradeA))
print ("Number of B's = " + str(gradeB))
print ("Number of C's = " + str(gradeC))
print ("Number of D's = " + str(gradeD))
print ("Number of F's = " + str(gradeF))
The issue is that when I run the code, the number of grades in each letter-grade category are all showing up as 0.
How could I fix this so that the correct numbers are shown?
You forgot to indent your if statements.
count = 0
gradeA = 0
gradeB = 0
gradeC = 0
gradeD = 0
gradeF = 0
score = int(input("Enter an exam score: "))
while score != -1:
count = count + 1
score = int(input("Enter an exam score: "))
if score >= 90 and score <= 100:
gradeA = gradeA + 1
elif score >= 80 and score <= 89:
gradeB = gradeB + 1
elif score >= 70 and score <= 79:
gradeC = gradeC + 1
elif score >= 60 and score <= 69:
gradeD = gradeD + 1
elif score >= 0 and score <= 59:
gradeF = gradeF + 1
print ("You entered " + str(count) + " exam scores.")
print ("Number of A's = " + str(gradeA))
print ("Number of B's = " + str(gradeB))
print ("Number of C's = " + str(gradeC))
print ("Number of D's = " + str(gradeD))
print ("Number of F's = " + str(gradeF))
It looks like the if/elif statements arent included in the while loop so the variables arent actually getting updated. Try indenting that block so its inside the loop and see if that works!
I am attempting to write a Python script that calculates the average score and the numbers of A's, B's, C's, D's and F's from a user input number of exams and exam scores.
I've tried a variety of methods for the part of the script currently in the function:
"def letter_score(scores):"
but have had no success with being able to assign the input exam grades with their corresponding letters.
sum_of_scores = 0
number_of_exams = int(input("What is the size of the class? "))
print("Now enter the scores below.")
for i in range(1, number_of_exams + 1):
scores = int(input("Student %d : " %(i)))
sum_of_scores += scores
def letter_score(scores):
if scores >= 90:
scores = "A"
elif scores < 90 and scores >= 80:
scores = "B"
elif scores < 80 and scores >= 70:
scores = "C"
elif scores < 70 and scores >= 60:
scores = "D"
else:
scores = "F"
average_score = sum_of_scores/number_of_exams
print("The average is " + str(average_score))
print("There are " + str(scores) + " A's.")
print("There are " + str(scores) + " B's.")
print("There are " + str(scores) + " C's.")
print("There are " + str(scores) + " D's.")
print("There are " + str(scores) + " F's.")
I was successful in finding the average score, but the letter grades are giving me trouble.
Consider using python dictionary to store the count of letter_score
You can initialize the dictionary with all 0 by:
letter_score_count = { "A": 0, "B": 0, "C": 0, "D": 0, "F": 0}
Give return value in the function letter_score using return keyword
def letter_score(scores):
if scores >= 90:
return "A"
elif scores < 90 and scores >= 80:
return "B"
elif scores < 80 and scores >= 70:
return "C"
elif scores < 70 and scores >= 60:
return "D"
else:
return"F"
By then, call the letter_score method, use the result as the key of dictionary to increase the counter of each letter score when inputting the scores
letter_score_count[letter_score(scores)] += 1
In the end, you can print the result
print("There are " + str(letter_score_count["A"]) + " A's.")
The edited version from your code. Hope this help
sum_of_scores = 0
number_of_exams = int(input("What is the size of the class? "))
print("Now enter the scores below.")
letter_score_count = { "A": 0, "B": 0, "C": 0, "D": 0, "F": 0}
def letter_score(scores):
if scores >= 90:
return "A"
elif scores < 90 and scores >= 80:
return "B"
elif scores < 80 and scores >= 70:
return "C"
elif scores < 70 and scores >= 60:
return "D"
else:
return"F"
for i in range(1, number_of_exams + 1):
scores = int(input("Student %d : " % (i)))
sum_of_scores += scores
letter_score_count[letter_score(scores)] += 1
average_score = sum_of_scores / number_of_exams
print("The average is " + str(average_score))
print("There are " + str(letter_score_count["A"]) + " A's.")
print("There are " + str(letter_score_count["B"]) + " B's.")
print("There are " + str(letter_score_count["C"]) + " C's.")
print("There are " + str(letter_score_count["D"]) + " D's.")
print("There are " + str(letter_score_count["F"]) + " F's.")
Let me know if this helps. You need to include count logic in your letter score function.
from collections import defaultdict
def letter_score(scores,counter_store):
if scores >= 90:
scores = "A"
counter_store["A"]+=1
elif scores < 90 and scores >= 80:
scores = "B"
counter_store["B"]+=1
elif scores < 80 and scores >= 70:
scores = "C"
counter_store["C"]+=1
elif scores < 70 and scores >= 60:
scores = "D"
counter_store["D"]+=1
else:
scores = "F"
counter_store["F"]+=1
return(counter_store)
sum_of_scores = 0
counter_store=defaultdict(int)
number_of_exams = int(input("What is the size of the class? "))
print("Now enter the scores below.")
for i in range(1, number_of_exams + 1):
scores = int(input("Student %d : " %(i)))
score_count=letter_score(scores,counter_store)
sum_of_scores += scores
average_score = sum_of_scores/number_of_exams
print("The average is " + str(average_score))
print("There are " + str(counter_store["A"]) + " A's.")
print("There are " + str(counter_store["B"]) + " B's.")
print("There are " + str(counter_store["C"]) + " C's.")
print("There are " + str(counter_store["D"]) + " D's.")
print("There are " + str(counter_store["F"]) + " F's.")
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
This is my first program in Python and I am having some trouble so forgive me if I have some simply syntax issues.
I am writing a program that calculates a student's final score based on one exam grade worth 60% and 7 other test scores worth a combined 40% of the final grade. The user is asked to input the one exam score then asked to input the 7 test scores which are read in a loop. The letter grade is then determined from the final score calculated from the exam and tests. After that a grade comment is printed corresponding to the letter grade given to the student. This is my code so far:
def read_test_scores() :
print("ENTER STUDENT ID: ")
id = int(input())
print("ENTER EXAM SCORE: ")
exam = int(input())
print("ENTER ALL TEST SCORES: ")
score1 = int(input())
score2 = int(input())
score3 = int(input())
score4 = int(input())
score5 = int(input())
score6 = int(input())
score7 = int(input())
sum = (score1 + score2 + score3 + score4 + score5 + score6 + score7)
tavge = sum/7
return tavge
def compute_final_score(tavge, exam) :
final_score = 0.4 * tavge + 0.6 * exam
return final_score
def get_letter_grade(final_score) :
if 90 <= final_score <= 100:
grade = 'A'
elif 80 <= final_score <= 89:
grade = 'B'
elif 70 <= final_score <= 79:
grade = 'C'
elif 60 <= final_score <= 69:
grade = 'D'
else:
grade = 'F'
return grade
def print_comment(grade) :
if grade = 'A':
print "COMMENT: Very Good"
elif grade = 'B':
print "COMMENT: Good"
elif grade = 'C':
print "COMMENT: Satisfactory"
elif grade = 'D':
print "COMMENT: Need Improvement"
elif grade = 'F'
print "COMMENT: Poor"
read_test_scores()
print "TEST AVERAGE IS: " + str(tavge)
compute_final_score()
print "FINAL SCORE IS: " + str(final_score)
get_letter_grade(final_score)
print "LETTER GRADE IS: " + str(grade)
print_comment(grade)
Here's my answer. The code should run. Notes are inserted as comments.
# NOTE: I haven't checked whether your math is right, or
# if the computed values are correct. I did however get your
# script to work.
def read_test_scores():
print("ENTER STUDENT ID: ")
id = int(input())
print("ENTER EXAM SCORE: ")
exam = int(input())
print("ENTER ALL TEST SCORES: ")
score1 = int(input())
score2 = int(input())
score3 = int(input())
score4 = int(input())
score5 = int(input())
score6 = int(input())
score7 = int(input())
sum = (score1 + score2 + score3 + score4 + score5 + score6 + score7)
tavge = sum / 7.0
# NOTE: if you want to use any variables from this function,
# then you have to "bring them outside" by "returning"
# them. Here, I return the values tavge, id, and exam. I noticed
# that bringing out "exam" is necessary since you'll
# be using it later on.
return tavge, id, exam
def compute_final_score(tavge, exam):
final_score = 0.4 * tavge + 0.6 * exam
return final_score
def get_letter_grade(final_score):
if 90 <= final_score <= 100:
grade = 'A'
elif 80 <= final_score <= 89:
grade = 'B'
elif 70 <= final_score <= 79:
grade = 'C'
elif 60 <= final_score <= 69:
grade = 'D'
else:
grade = 'F'
return grade
def print_comment(grade):
# NOTE `=` is for assignment. We use it when we want to
# tell python to make a variable mean something. For example:
# a = "some_name" basically means that when we call a, it would
# return the string "some_name".
# What you want to use here is `==` which is the equality operator.
# This checks whether or thing are equal.
if grade == 'A':
print("COMMENT: Very Good")
elif grade == 'B':
print("COMMENT: Good")
elif grade == 'C':
print("COMMENT: Satisfactory")
elif grade == 'D':
print("COMMENT: Need Improvement")
elif grade == 'F':
print("COMMENT: Poor")
# NOTE 1: you need to assign the function results to a
# variable (or variables), otherwise, the result or return value
# will go nowhere and you can't use it
tavge, id, exam = read_test_scores()
print "TEST AVERAGE IS: " + str(tavge)
# NOTE 2: variable names do not have to be the same as
# the name in their respective functions. Here, you can see
# that it will still run even if I changed the variable
# name final_score to my_variable. Although, of course, using
# final_score would still work.
# NOTE 3: the final_score function requires 2 inputs,
# namely tavge and exam. This basically means that you have to feed
# it with these 2 values for it to work. I took the
# tavge and exam variables as the results from your read_test_scores
# function
my_variable = compute_final_score(tavge, exam)
print("FINAL SCORE IS: " + str(my_variable))
grade = get_letter_grade(my_variable)
print("LETTER GRADE IS: " + str(grade))
print_comment(grade)
# FINAL NOTE: I haven't commented regarding coding style etc (like say
# for instance, there are best practices regarding variable names
# within functions, that is, if they should be similar to variable names
# outside the function), but regardless, the code is a good start. I
# would also advise you to try to narrow down your question first
# before posting. This can be done by running your code, and searching
# the internet for the particular erro messages, and if you're still stuck,
# ask here on stackoverflow.
there are many errors in your code, some of them are in the comment, but the most critical part is that you use global and local variables incorrectly
here is and example of fixing your code using the correct way to use global variables.
https://repl.it/repls/SorrowfulOddballSongbird
tavge = 0
exam = 0
sid = 0
final_score = 0
grade = ''
def read_test_scores() :
global sid
print("ENTER STUDENT ID: ")
sid = int(input())
global exam
print("ENTER EXAM SCORE: ")
exam = int(input())
print("ENTER ALL TEST SCORES: ")
score1 = int(input())
score2 = int(input())
score3 = int(input())
score4 = int(input())
score5 = int(input())
score6 = int(input())
score7 = int(input())
total = (score1 + score2 + score3 + score4 + score5 + score6 + score7)
global tavge
tavge = total/7
#return tavge
def compute_final_score() :
global final_score
final_score = 0.4 * tavge + 0.6 * exam
#return final_score
def get_letter_grade() :
global grade
if 90 <= final_score <= 100:
grade = 'A'
elif 80 <= final_score <= 89:
grade = 'B'
elif 70 <= final_score <= 79:
grade = 'C'
elif 60 <= final_score <= 69:
grade = 'D'
else:
grade = 'F'
#return grade
def print_comment() :
if grade == 'A':
print("COMMENT: Very Good")
elif grade == 'B':
print ("COMMENT: Good")
elif grade == 'C':
print ("COMMENT: Satisfactory")
elif grade == 'D':
print ("COMMENT: Need Improvement")
elif grade == 'F':
print ("COMMENT: Poor")
read_test_scores()
print ("TEST AVERAGE IS: " + str(tavge))
compute_final_score()
print ("FINAL SCORE IS: " + str(final_score))
get_letter_grade()
print ("LETTER GRADE IS: " + str(grade))
print_comment()
but you should consider using parameters instead using globals
As several people have mentioned you need to use == for comparison, you also are missing a colon after one of your if/else.
This is my take on your code. Keep in mind that this doesn't have and tests to make sure someone is actually entering in a number for a test score instead of text
"sum" is also the name of a built in function to Python, which sums up anything you provide it.
def read_test_scores():
scores = []
num_tests = 7
print("ENTER ALL TEST SCORES: ")
for i in range(num_tests):
score = input("Test " + str(i + 1) + ":")
scores.append(int(score))
return sum(scores) / num_tests
def compute_final_score(average, exam_score):
score = 0.4 * average + 0.6 * exam_score
return score
def get_letter_grade(finalized_score):
if 90 <= finalized_score <= 100:
letter_grade = 'A'
elif 80 <= finalized_score <= 89:
letter_grade = 'B'
elif 70 <= finalized_score <= 79:
letter_grade = 'C'
elif 60 <= finalized_score <= 69:
letter_grade = 'D'
else:
letter_grade = 'F'
return letter_grade
def print_comment(letter_grade):
if letter_grade == 'A':
print("COMMENT: Very Good")
elif letter_grade == 'B':
print("COMMENT: Good")
elif letter_grade == 'C':
print("COMMENT: Satisfactory")
elif letter_grade == 'D':
print("COMMENT: Need Improvement")
elif letter_grade == 'F':
print("COMMENT: Poor")
def get_student_id():
print("ENTER STUDENT ID: ")
identity = int(input())
return identity
def get_exam_score():
print("ENTER EXAM SCORE: ")
exam_score = int(input())
return exam_score
if __name__ == '__main__':
student_id = get_student_id()
exam = get_exam_score()
tavge = read_test_scores()
print("TEST AVERAGE IS: " + str(tavge))
final_score = compute_final_score(tavge, exam)
print("FINAL SCORE IS: " + str(final_score))
grade = get_letter_grade(final_score)
print("LETTER GRADE IS: " + str(grade))
print_comment(grade)
This question already has answers here:
Date Ordinal Output?
(14 answers)
Closed 6 years ago.
I have been developing a small program.
It works perfectly how it is but I want to make the code a bit smaller.
import time, math
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
end= "th"
if age == 3 or age == 13 or age == 23 or age == 33 or age == 43 or age == 53 or age == 63 or age == 73 or age == 83 or age == 93:
end= "rd"
if age == 2 or age == 22 or age == 32 or age == 42 or age == 52 or age == 62 or age == 72 or age == 82 or age == 92:
end= "nd"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)
I would like to have an easier way to change the 'end' to other values without having to write them all, can I have it start at 3 then do it for everything 10 more than three.
Use the modulo operator:
if age % 10 == 3:
end = "rd"
elif age % 10 == 2:
end = "nd"
Or use a dict:
ends = {2: "nd", 3: "rd"}
end = ends[age % 10]
You can also use a default:
ends = {1: "st", 2: "nd", 3: "rd"}
end = ends.get(age % 10, "th)
Extract the digit at tenth's place. Then it's straightforward. Though this question belongs to the codereview counterpart of SO.
import time, math
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
tenth_place = age % 10
if tenth_place == 3:
end = "rd"
elif tenth_place == 2:
end = "nd"
else:
end = "th"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)
if age in range(3,93,10) :
end = "rd"
You can try this:
if int(age[-1]) == 3:
end= "rd"
if int(age[-1]) == 2:
end= "nd"
Might not be shorter necessarily, but it works (and keeps 12th and 13th proper).
import time, math
name = input("Enter Your Name:")
age = int(input("Enter Your Age:"))
end = "th"
# initializing age lists
list1 = []
list2 = []
# filling list1 with ages 3-93
for i in range(0,10):
list1.append(10*i+3)
# filling list2 with ages 2-92
for i in range(0,10):
list2.append(10*i+2)
# if block to include correct suffix
for ages in list1:
if ages == 13:
end = end;
elif ages == age:
end = "rd"
for ages in list2:
if ages == 12:
end = end
elif ages == age:
end = "nd"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)
Thanks For All Of It Guys,
I have also found another flaw and fixed it, here is my current code.
Thanks.
import time, math
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
end= "th"
if age % 10 == 3:
end = "rd"
elif age % 10 == 2:
end = "nd"
elif age % 10 == 1:
end = "st"
if age < 20 and age > 10:
end = "th"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(2)
Thanks,
Bilbo