Loop occurs twice within one range - python

I've been struggling with this problem for a while now since loops are a bit confusing to me. Essentially, I think I got some of the more difficult stuff (for me at least) out of the way. The issue is that I need the average of 3 students per exam not 6 students per exam, which is what my current code gives.
If what I am asking isn't clear let me know and I will clear it up.
My inputs are n = 3 and m = 2.
def readGrade():
grade = int(input("Enter the grade: "))
while grade > 100 or grade < 0:
print("Invalid Grade")
grade = int(input("Enter the grade: "))
return grade
def examAverage(m):
average = 0
for i in range(n):
readGrade()
average = average + readGrade()
return (average / n)
n = int(input("Enter the number of students: "))
m = int(input("Enter the number of exams: "))
for i in range(m):
print("The average of exam", i + 1, "is:", examAverage(m))

You are calling readGrade() two times within examAverage()
I think this is what examAverage() should be:
def examAverage(m):
average = 0
for i in range(n):
this_grade = readGrade()
average = average + this_grade
return (average / n)

Related

Minimum number and interest does not print correctly

I am in a Python class and a few weeks ago we were given these sets of instructions for an assignment:
Write a program that utilizes a loop to read a set of five floating-point
values from user input. Ask the user to enter the values, then print the
following data:
Total,
Average,
Maximum,
Minimum,
Interest at 20% for each original value entered by the user.
Use the formula: Interest_Value = Original_value + Original_value*0.2
I uploaded a different assignment for the class, but this problem is driving me crazy because I cannot figure out why minimum number, and interest does not work correctly. Any suggestions would be appreciated. Thank you.
This is the code I wrote. My problem is the minimum number does not output and the printed interest is wrong.
entered_number = 0
sum = 0
average = 0
max_number = 0
min_number = 0
interest = 0.2
for entered_number in range(5):
entered_number = float(input('Enter a number: '))
if entered_number > max_number:
max_number = entered_number
if entered_number < min_number:
min_number = entered_number
sum = sum + entered_number
average = sum / 5
interest = entered_number + (entered_number * interest) # removing the () didn't solve
print('Total:', sum)
print('Average:', average)
print('Maximum number:', max_number)
print('Minimum number:', min_number)
print('Interest at 20% for each entered number is: ', interest)
My output example:
Enter a number: 20
Enter a number: 30
Enter a number: 40
Enter a number: 50
Enter a number: 60
Total: 200.0
Average: 40.0
Maximum number: 60.0
Minimum number: 0
Interest at 20% for each entered number is: 90123060.0
Try setting your min_number and max_number values to positive and negative infinity respectively, upon intialization.
Then for the interest it sounds like you need to collect multiple values and output all of them if I understand correctly. And you don't want to overwrite the interest variable because that is constant between all numbers so use current_interest and move it inside the loop.
For the total you shouldn't use sum as a variable name since it overwrites the function. instead use total, and move it inside the loop so that the value updates for each input received.
import math
entered_number = 0
total = 0
average = 0
max_number = -math.inf
min_number = math.inf
interest = 0.2
interest_list = []
for entered_number in range(5):
entered_number = float(input('Enter a number: '))
if entered_number > max_number:
max_number = entered_number
if entered_number < min_number:
min_number = entered_number
current_interest = entered_number + (entered_number * interest)
interest_list.append(current_interest) # collect all interest values
total += entered_number # dont use sum as a variable name
average = total / 5
print('Total:', total)
print('Average:', average)
print('Maximum number:', max_number)
print('Minimum number:', min_number)
print('Interest at 20% for each entered number is: ', interest_list)
OUTPUT
Enter a number: 20
Enter a number: 30
Enter a number: 40
Enter a number: 50
Enter a number: 60
Total: 200.0
Average: 40.0
Maximum number: 60.0
Minimum number: 20.0
Interest at 20% for each entered number is: [24.0, 36.0, 48.0, 60.0, 72.0]

Im new to python and having an issue with my list being out of range

so im getting a list index out of range here:
for i in range(len(empNr)):
print(empNr[i], rate[i], hrs[i], wkPay[i])
and I haven't really figured lists out, so I may just be confused and am unable to understand why i would be out of range. here the rest of the code below. thanks!
SENTINEL = 0
wkTotal = payHigh = wkPay = empHigh = 0
empNr = []
rate = []
hrs = []
wkPay = []
i = 0
empNr.append(input("Input first employee number: "))
#iteration if 0 is entered it should stop
while (empNr[i] != str(SENTINEL)):
rate.append(int(input("Input rate: ")))
hrs.append(int(input("Input hours: ")))
wkPay.append(rate[i] * hrs[i])
i = i + 1
empNr.append(input("Input employee number or '0' to stop: "))
#calculations using list functions
wkTotal = sum(wkPay)
payHigh = max(wkPay)
wkAvg = float(wkTotal) / len(empNr)
#output summary for pay calculator
print("\n\n Data entry complete " +" \n --------------------------------------")
print("\n Employee Number Pay Rate Hours worked Pay ")
print("--------------------------------------------------------")
for i in range(len(empNr)):
print(empNr[i], rate[i], hrs[i], wkPay[i])
print("Summary: ")
print("WEEK TOTAL: ", str(wkTotal))
print("EMPLOYEE HIGH: ", str(empHigh))
print("PAY HIGH: ", str(payHigh))
print("WEEK AVERAGE: ", str(wkAvg))
empNr.append(input("Input employee number or '0' to stop: ")) this line appends '0' to empNr. But it has no corresponding values for rate, hrs or wkPay. Meaning rate, hrs or wkPay these have one element less than that of empNr. A quick fix (but not recommended) would be to loop for rate or hrs instead of empNr. So your code would be:
for i in range(len(rate)):
print(empNr[i], rate[i], hrs[i], wkPay[i])
A better fix would be:
i = 0
inp = input("Do you want to add anew record? Y/n: ")
while (inp == "Y"):
empNr.append(input("Input first employee number: "))
rate.append(int(input("Input rate: ")))
hrs.append(int(input("Input hours: ")))
wkPay.append(rate[i] * hrs[i])
i = i + 1
inp = input("Do you want to add anew record? Y/n: ")
So while I enter 'Y' I can add new entries and length of each empNr, rate, hrs, wkPay would match. If I enter anything other than Y, the loop will terminate and the lengths will still remain the same...
SENTINEL = 0
wkTotal = payHigh = wkPay = empHigh = 0
empNr = []
rate = []
hrs = []
wkPay = []
i = 0
empNr.append(input("Input first employee number: "))
#iteration if 0 is entered it should stop
while (empNr[i] != str(SENTINEL)):
rate.append(int(input("Input rate: ")))
hrs.append(int(input("Input hours: ")))
wkPay.append(rate[i] * hrs[i])
i = i + 1
empNr.append(input("Input employee number or '0' to stop: "))
#calculations using list functions
wkTotal = sum(wkPay)
payHigh = max(wkPay)
wkAvg = float(wkTotal) / len(empNr)
#output summary for pay calculator
print("\n\n Data entry complete " +" \n --------------------------------------")
print("\n Employee Number Pay Rate Hours worked Pay ")
print("--------------------------------------------------------")
for i in range(len(empNr)-1):
print(empNr[i], rate[i], hrs[i], wkPay[i])
print("Summary: ")
print("WEEK TOTAL: ", str(wkTotal))
print("EMPLOYEE HIGH: ", str(empHigh))
print("PAY HIGH: ", str(payHigh))
print("WEEK AVERAGE: ", str(wkAvg))
Please use the above.
Lets say the list had 2 employee details. According to your solution len(empNr) gives 3. The range function will make the for loop iterate for 0,1 and 2. Also one mistake you did was even for the exiting condition when u r accepting the value for 0 you had used the same list which increases the count of the list by 1 to the no. of employees. Hence do a -1 so that it iterates only for the employee count

Running into some logical errors with my code

I am the given the following problem and asked to write a solution algorithm for it using python.
problem:
Write a Python program to determine the student with the highest average. Each student takes a midterm and a final. The grades should be validated to be between 0 and 100 inclusive. Input each student’s name and grades and calculate the student’s average. Output the name of the student with the best average and their average.
Here is my code:
def midTerm():
midtermScore = int(input("What is the midterm Score: "))
while (midtermScore <= 0 or midtermScore >= 100):
midtermScore = int(input("Please enter a number between 0 and 100: "))
return midtermScore
def final():
finalScore = int(input("What is the final Score: "))
while (finalScore < 0 or finalScore > 100):
finalScore = int(input("Please enter a number between 0 and 100: "))
return finalScore
total = 0
highest = 0
numStudents = int (input("How Many Students are there? "))
while numStudents < 0 or numStudents > 100:
numStudents = int (input("Please enter a number between 0 and 100? "))
for i in range (1, numStudents+1):
students = (input("Enter Student's Name Please: "))
score = (midTerm()+ final())
total += score
avg = total/numStudents
if (highest < avg):
highest = avg
winner = students
print ("The Student with the higgest average is: ", winner, "With the highest average of: ", avg)
The issue I am running into is the last part. The program does not print the name of the person with the highest average, but the name of the person that was entered at the very last. I am very confused on how to go forward from here. Can you please help? Thanks in advance for any help.
You're not far off. Take a look here:
for i in range (1, numStudents+1):
students = (input("Enter Student's Name Please: "))
score = (midTerm()+ final())
total += score
avg = total/numStudents
if (highest < avg):
highest = avg
winner = students
Besides the indentation error (hopefully just clumsy copy-pasting) You're not actually calculating each student's average score anywhere. Try something like this:
for i in range (numStudents):
student_name = (input("Enter Student's Name Please: "))
student_avg = (midTerm() + final()) / 2 # 2 scores, summed and divided by 2 is their average score
if (highest < student_avg):
highest = student_avg
winner = student_name # save student name for later
print ("The Student with the higgest average is: ", winner, "With the highest average of: ", highest)
It looks like you were originally trying to calculate the total class average, which is not what's described by the problem statement. Hope this helps!

I need help finishing a grade calculator program in python

For my computer science class I have to make a program that will calculate grades.
This is my first computer science class (no prior experience) so I am struggling through it.
These are the directions:
Ask the user for the number of tests, assignments, quizzes, and labs in their course.
Ask the user if there is a final with a separate weight from the tests above, e.g. a course has 2 tests, each weighing 12.5%, and 1 final weighing 15%.
For each category having a number > 0
a. Prompt the user for the weighted percent, out of 100%, which should total
100% for all categories!!!
b. Get the score(s) for the category.
c. If the category is labs, then sum all the scores.
d. Else, average the scores.
e. Calculate the weighted average for the category.
Using the weighted average of each category, calculate the grade in the course.
Ask the user if he/she wants to calculate a grade for another class.
If the user responds yes, then go back to step 1.
Else, end the program.
My code so far:
def main():
lists = get_user_input()
get_scores(lists);
get_weighted_average(lists)
def get_user_input():
# How many?
t = int(input("How many tests?: "))
a = int(input("How many assignments?: "))
q = int(input("How many quizzes?: "))
l = int(input("How many labs?: "))
# How much weight on grade?
tw = float(input("Enter weight of tests: "))
aw = float(input("Enter weight of assignments: "))
qw = float(input("Enter weight of quizzes: "))
lw = float(input("Enter weight of labs: "))
lists = [t, a, q, l, tw, aw, qw, lw]
return lists
def get_scores(lists):
# What are the scores?
scores = [0] * 5
for(x in range(lists[0]):
test_scores = float(input("enter your test scores: "))
scores[x] = test_scores
for(x in range(lists[1]):
test_scores = float(input("enter your assignment scores: "))
scores[x] = assignment_scores
for(x in range(lists[2]):
test_scores = float(input("enter your quiz scores: "))
scores[x] = quiz_scores
for(x in range(lists[3]):
test_scores = float(input("enter your lab scores: "))
scores[x] = lab_scores
sumlabs = 0
for(x in range(lists[3]):
sumlabs = sumlabs + scores[x]
print(sumlabs)
def get_weighted_average(lists):
main()
I am not sure how to proceed so any help is much appreciated.
Averaging a score means adding them up and dividing by the number of them. You can use the fact that a list has a way to tell you how many elements it has. For example if x is a list then len(x) is the number of things in the list. You should be careful about not trying to calculate the score of an empty list, because that would mean dividing by zero. In the following function the 'if score_list:' will be true if there is something in the list. Otherwise it returns None (since the average is not defined).
def average_score(score_list):
if score_list: # makes sure list is not empty
total = 0 # our total starts off as zero
for score in score_list: # starts a loop over each score
total += score # increases the total by the score
return total / len(score_list) # returns aveage
To form a list of scores from user input, presuming the user will put them all on the same line when you prompt them, you can get a string from the user (presumably like: "13.4 12.9 13.2" And then use the string's split method to convert this to a list of strings like ["13.4", "12.9", "13.2"], and then convert this list of strings to a list of floats. Finally using the average function above you can get an average:
test_score_entry = raw_input("Enter your test scores separated by spaces: ")
test_sore_strings = test_score_entry.split()
test_scores = [float(_) for _ in test_score_strings]
average_score = average(test_scores)

Calculting GPA using While Loop (Python)

A GPA, or Grade point Average, is calculated by summing the grade points earned in a student’s courses and then dividing by the total units. The grade points for an individual course are calculated by multiplying the units for that course by the appropriate factor depending upon the grade received:
A receives 4 grade points
B receives 3 grade points
C receives 2 grade points
D receives 1 grade point
F receives 0 grade point
Your program will have a while loop to calculate multiple GPAs and a while loop to collect individual grades (i.e. a nested while loop).
For your demo, calculate the GPA to 2 decimal places for these two course combinations:
First Case: 5 units of A 4 units of B 3 units of C
Second Case: 6 units of A 6 units of B 4 units of C
This is what I have so far....
todo = int(input("How many GPA's would you like to calculate? "))
while True: x in range (1, todo+1)
n = int(input("How many courses will you input? "))
totpoints = 0
totunits = 0
while True: range(1, n+1)
grade = input("Enter grade for course: " )
if grade == 'A':
grade = int(4)
if grade == 'B':
grade = int(3)
if grade == 'C':
grade = int(2)
if grade == 'D':
grade = int(1)
if grade == 'F':
grade = int(0)
units = int(input("How many units was the course? "))
totunits += units
points = grade*units
totpoints += points
GPA = totpoints / totunits
print("GPA is ", ("%.2f" % GPA))
print("total points = ", totpoints)
print("total units = ", totunits)
My question is how do I exactly incorporate the while function correctly? My code is not running correctly.
Thanks in advance.
First thing you must know about Python is that is all about indentation. So make sure you indent your while blocks correctly. The syntax of the while statements is like:
while <condition>:
do_something
The code inside the while block is executed if the condition is true. After executing the code the condition is checked again. If the condition is still true it will execute the block again, and so on and so forth until the condition is false. Once the condition is false it exits the while block and keeps executing the code after.
One last thing, Python does not have case statements like other programming languages do. But you can use a dictionary, so for example I've defined a dictionary to map the grades to points and remove the if statements from your code:
gradeFactor = {'A':4, 'B': 3, 'C':2, 'D':1, 'F':0}
todo = int(raw_input("How many GPA's would you like to calculate? "))
while todo:
n = int(raw_input("How many courses will you input? "))
totpoints = 0
totunits = 0
while n:
grade = raw_input("Enter grade for course: " )
units = int(raw_input("How many units was the course? "))
totunits += units
points = gradeFactor[grade]*units
totpoints += points
n -= 1
GPA = float(totpoints) / totunits
print("GPA is ", ("%.2f" % GPA))
print("total points = ", totpoints)
print("total units = ", totunits)
todo -= 1

Categories

Resources