Edhesive 7.5 code practice GPA average Python - python

Currently my code is:
def GPAcalc(grade, weighted):
grade = grade.lower()
dictionary = {"a": 4, "b": 3, "c": 2, "d": 1, "f": 0}
if weighted == 1 and grade in dictionary:
return "Your GPA score is: "+str(dictionary[grade] + 1)
elif weighted == 0 and grade in dictionary:
return "Your GPA score is: "+str(dictionary[grade])
else:
return "Invalid"
def GPAav():
grade = GPAcalc()
for i in range(0,cl):
grad= GPAcalc(grade,dictionary)
total = grade + total
print(total/cl)
cl = int(input("How many Classes are you taking? "))
for i in range(0,cl):
print(GPAcalc(input("Enter your letter Grade: "), int(input("Is it weighted?(1= yes, 0= no) "))))
GPAav()
I have to find the average GPA in decimal form from the rest of the code and output it. How would I go about getting the values from GPAcalc and using it in GPAav so i can average it out?

You have 2 options here. Store the grades in an list as they are entered or do the calculations on the fly. I chose the first option. This allows you to use the data later, if you want to add features the the app. You may also want to store the un-weighted grades in a list of tuples ([('a',True),('b',False)...]), but I just store the weighted grades.
Also, it is probably easier if you verify that the user is inputting the correct values as you read them. Have them keep re-trying until they get it right.
Your calculation functions should not print anything. They should just do the calculations they are required to do and return the result as a number.
grade_map = {"a": 4, "b": 3, "c": 2, "d": 1, "f": 0}
def GPAcalc(grade, weighted):
# Data has already been sanitized, so no error checks needed
return grade_map[grade] + weighted
def GPAav(grades):
return sum(grades) / len(grades)
def input_grades():
# TODO: Make sure user enters a number
cl = int(input("How many classes are you taking? "))
grades = []
for _ in range(cl):
# Loop until valid input
while True:
# Get input and convert to lower case
grade = input("Enter your letter grade: ").lower()
if grade in grade_map:
# Ok data. Exit loop.
break
# This only prints on bad input
print("Invalid input. Enter a,b,c,d or f. Try again...")
# Loop until valid input
while True:
# Read the value as a string first to verify "0" or "1"
weighted = input("Is it weighted?(1= yes, 0= no) ")
if weighted in "01":
# Verified. Now convert to int to avoid an exception
weighted = int(weighted)
break
print("Invalid input. Enter 0 or 1. Try again...")
# Store weighted numeric grade in list
grades.append(GPAcalc(grade, weighted))
return grades
grades = input_grades()
print(f"Your average GPA is {GPAav(grades)}.")
TODO: The repeated code in input_grades() is a red-flag that maybe that code can be moved into a re-usable function.

Related

Python how to limit the score (Code doesn't work after adding the if avg== etc

I am trying to find scores from only 7 judges and to have the numbers between 1-10 only, what is the problem with my code I am an newbie trying to self teach myself:)
So what I'm asking is how to limt the input to have to be 7 inputs per name and to limt the user input to 1-10 for numbers.
import statistics#Importing mean
def check_continue(): #defining check_continue (checking if the user wants to enter more name/athletes
response = input('Would you like to enter a another athletes? [y/n] ') #Asking the user if they want another name added to the list
if response == 'n': #if n, ends the loop
return False
elif response == 'y': # if y, continues the loop
return True
else:
print('Please select a correct answer [y/n]') #making sure the awsener is valid
return check_continue() #calling check continue
while(True):
name = input('Please enter a athletes name: ') #asking for an athletes name
if name == (""):
print ("try again")
continue
else:
try:
print("Enter the judges scores with space inbetween each score") #asking for scores
avg = [float(i) for i in input().split( )] #spliting the scores so the user only needs to put a space for each score
except ValueError:
continue
print("Please enter scores only in numbers")
scores = '' .join(avg)
print("please only enter number")
if scores ==("") or scores <=0 or scores >=10:
print("Please enter a score between 1-10")
continue
else:
print("_______________________________________________________________________________")
print("Athlete's name ",name) #Printing athletes name
print("Scores ", avg) #printing athletes scores
avg.remove(max(avg)) #removing the highest score
avg.remove(min(avg)) #removing the lowest score
avgg = statistics.mean(avg) #getting the avg for the final score
print("Final Result: " +
str(round(avgg, 2))) #printing and rounding the fianl socre
if not check_continue():
break
else:
continue
After reading input scores from judges, make sure that len(input.split()) == 7 to match first criteria.
Once you have the list of scores, just have a check that for each score, 1 <= int(score) <= 10.
If necessary, I can provide a working code too.
import statistics # Importing mean
def check_continue(): # defining check_continue (checking if the user wants to enter more name/athletes
# Asking the user if they want another name added to the list
response = input('Would you like to enter a another athletes? [y/n] ')
if response == 'n': # if n, ends the loop
return False
elif response == 'y': # if y, continues the loop
return True
else:
# making sure the awsener is valid
print('Please select a correct answer [y/n]')
return check_continue() # calling check continue
while(True):
# asking for an athletes name
name = input('Please enter a athletes name: ')
if name == (""):
print("try again")
continue
else:
scores = [float(i) for i in input('Enter the judges scores with space inbetween each score').split() if 1 <= float(i) <= 10]
if len(scores) != 7:
print("try again")
continue
print("_______________________________________________________________________________")
print("Athlete's name ", name) # Printing athletes name
print("Scores ", scores) # printing athletes scores
scores.remove(max(scores)) # removing the highest score
scores.remove(min(scores)) # removing the lowest score
# getting the avg for the final score
avg = statistics.mean(scores)
print("Final Result: " + str(round(avg, 2))) # printing and rounding the final score
if not check_continue():
break
This one should work. Let me know if there are any issues.
scores = [float(i) for i in input('Enter the judges scores with space inbetween each score').split() if 1 <= float(i) <= 10]
This line of code only saves values between 1 and 10, thus already checking for those values. Then the number of elements is checked to be 7.
PS: Would also want to point out that in your code, nothing ever executes after the except ValueError: continue. The continue basically skips to the next iteration without running any of the next lines of code.
My two cents. All checks of input you can warp before printing results with if all(): function for length of input scores list and range of nums between 1 and 10 (see code below).
For mean calc you don't need to delete value from list. You can make sorting and then slicing of list.
check_continue() can be simplify. Check entering for y or n value and return True or False by cases in dict. Otherwise loop.
import statistics
def check_continue():
response = input('Would you like to enter a another athletes? [y/n] ').lower() # Format Y and N to y and n
if response in ['y', 'n']: # Check if response is y or n
return {'y': True, 'n': False}[response]
check_continue()
while True:
name = input('Please enter a athletes name: ') #asking for an athletes name
if name: # Check if name not empty
while True: # make a loop with break at only 7 scores enter
scores_input = input("Enter the judges scores with space inbetween each score (only 7 scores)").split(' ')
try:
scores = [float(s) for s in scores_input] # sort list for extract part for avgg calc
except ValueError:
print("Please enter scores only in numbers")
continue
if all([len(scores) == 7, max(scores) <= 10.0, min(scores) >= 1]):
print("_______________________________________________________________________________")
print(f"Athlete's name {name}") #Printing athletes name
print(f"Scores {scores}") #printing athletes scores
avgg = statistics.mean(sorted(scores)[1:-1]) #getting the avg for the final score
print(f'Final result - {avgg :.2f}')
break
else:
print("Please enter 7 numbers for scores between 1-10")
if not check_continue():
break

Trying to sum up total cost from user input in defintion

I am trying to build a menu for user . User must order min 3 items and after that needs to decide if want to keep ordering after or end it. I created while loop for that and now it's my question
How can I sum up all prices for each choice?
I include user answer in definition otherwise my loop is not working as I wish... I need to sum up each choice of different prices that need to match positions from list I've created.
I tried if statement inside def, outside. Like if input answer will be = 1, then price will be 1,20 etc and tried to sum it up, would not work.
Many thanks for any help !
prices = [1.20,1.30,2.00,1.60,2.00,2.50,4.00,4.80,3.80,3.25,3.40,2.70,2.50,3.15,4.40]
food_menu = ["sandwich","pizza","lemon cake","chips","salad","panini","yoghurt","pasta","bagel,"cheese wrap","cherry muffin","egg","blt","marmite sarnine","watermelon pieces"]
def order1():
input("Please choose which treat you wish to order by typing its position number [1-15] and confirm with ENTER : ")
input("Next item to order: ")
def order2():
input("Another item number to order: ")
if decision == "y":
print ("Awesome! Let's get started!")
order1()
i=1
x=""
while i>0:
if decision == "y":
order2()
x = input("Keep adding more food for bigger discount?\ny - for yes\ns - for stop:\nYour answer: ")
if (x == "s"):
break
elif decision == "n":
print ("Please come back tomorrow or try again. Today you need to get minimum 3 items today!\U0001F641")
print ("Bye bye!")
i=0
exit()
else:
print ("Wrong answer, please try again from the start.. \U0001F641 ")
i=0
exit()
After that I should sum up all the prices for each item that customer wants to order.
I'd suggest you have one main loop, then 2 parts in it
handle choice of user for the product
handle choice for continuing or not
Also a dict is the best structure to store both menu and prices, and it provides easy acess and very test inclusion
food_menu = {'sandwich': 1.2, 'pizza': 1.3, 'lemon cake': 2.0, 'chips': 1.6, 'salad': 2.0, 'panini': 2.5,
'yoghurt': 4.0, 'pasta': 4.8, 'bagel': 3.8, 'cheese wrap': 3.25, 'cherry muffin': 3.4, 'egg': 2.7,
'blt': 2.5, 'marmite sarnine': 3.15, 'watermelon pieces': 4.4}
decision = ""
count = 0
total = 0
print("Menu with prices:")
print(*food_menu.items(), sep="\n")
while True:
item = input("Please choose which treat you wish to order by typing its position number [1-15] "
"and confirm with ENTER : ")
if item in food_menu:
total += food_menu[item]
count += 1
else:
print("Wrong input")
decision = input("Keep adding more food for bigger discount? (y - for yes / s - for stop) : ")
if decision == "s":
if count < 3:
print("Please come back tomorrow or try again. Today you need to get minimum 3 items today!")
else:
print("Total price is:", total)
break

How to create a list for each inputted item in dictionary - Python?

I am making a student grading dictionary where the grades for each student should be stored in the dictionary created earlier under the student ID, along side the name of the student. ex. {'1234': {'Name': 'Josh', 'Scores': [88,99,77]}} I am relatively new to coding so dont know how much of my code to share, and it is probably much longer than it needs to be right now.
myDict = {}
total_scores=[]
all_names=[]
total_student_id=[]
for key in total_student_id:
for value in all_names:
myDict[key] = value
all_names.remove(value)
break
for key in all_names:
for value in total_scores:
myDict[key] = value2
total_scores.remove(value2)
break
new_student=True
more_grades = False
while new_student:
name = input("What is their name?")
all_names.append(name)
student_id = input("What is their student id?")
total_student_id.append(student_id)
repeat1 = input("Are there any more students? yes or no: ")
if repeat1 == "no":
new_student = False
more_grades = True
else:
new_student = True
while more_grades == True:
assignments = int(input("How many assignments were given: "))
assign_number = 0
while assign_number < assignments:
score = int(input("enter one of your assignment scores: "))
total_scores.append(score)
assign_number = assign_number+1
more_grades = False
continue
for key, value in myDict.items():
print(key, ' : ', value, value2)
Currently, this code is set up to take the input for each student, and their id. It also asks for the number of assignments given along with the grades for each assignment, however it does not ask for the grades of each specific student. I want to switch this code to ask each student individually for their grades, and add it to the dictionary, to get an output similar to the one i mentioned above.
Edit: I am also having the problem of it not printing out any results at the end. Originally, it was printing out the student id and name, but once I started implementing the assignments/scores, the code would end once I added the final score.
Current Output:
What is their name?Andrew
What is their student id?101
Are there any more students? yes or no: yes
What is their name?Dani
What is their student id?102
Are there any more students? yes or no: yes
What is their name?George
What is their student id?103
Are there any more students? yes or no: no
How many assignments were given: 3
enter one of your assignment scores: 22
enter one of your assignment scores: 88
enter one of your assignment scores: 55
Expected Output:
Please enter the student's name: Andrew
Please enter the student's ID: 101
Enter another student? (y)es (n)o: y
Please enter the student's name: Dani
Please enter the student's ID: 102
Enter another student? (y)es (n)o: n
How many assignments were given? 3
Please enter the scores for Andrew
Enter score (0-100) for assignment 1: 90
Enter score (0-100) for assignment 2: 88
Enter score (0-100) for assignment 3: 95
Please enter the scores for Dani
Enter score (0-100) for assignment 1: 56
Enter score (0-100) for assignment 2: 70
Enter score (0-100) for assignment 3: 85
Final grade report:
Andrew's average score was 91.0
Dani's average score was 70.3
Assignment averages:
The average for assignment 1 was 73.0
The average for assignment 2 was 79.0
The average for assignment 3 was 90.0
So I went through your image and I just ended up writing the code.
def main():
students_left_to_log = int(input("How many students would you like to log?\n"))
student_collection = {}
while students_left_to_log > 0:
student_id = input("Student Id: \n")
name = input("Student Name: \n")
assignment_left_to_log = int(input("How many assignments were given?\n"))
assignment_counter = 1
student_data = {'Name': name, 'Scores': []}
while assignment_left_to_log > 0:
# maybe use a try except block here avoid errors
score = int(input(f"Enter their score on assignment {assignment_counter}: \n"))
if score > 100 or score < 0:
print("The scores must be between 0 and 100.")
continue
student_data['Scores'].append(score)
# reduce the number of assignments left to log
assignment_left_to_log -= 1
assignment_counter += 1
# reduce the number of students left
students_left_to_log -= 1
student_collection[student_id] = student_data
print(f"Successfully logged student: {student_id}\n\n")
for student_id, student_data in student_collection.items():
avg_score = round(sum(student_data['Scores']) / len(student_data['Scores']), 1)
print(f"Student {student_data['Name']} avg assignment score: {avg_score}")
if __name__ == '__main__':
main()
Some concepts you'd wana go through:
Error Handling in python (The try except blocks)
String interpolation python (The nifty f"" syntax)
round() built-in method
Maybe some JSON fundamentals (since it's very similar to python dict) read here

What is wrong in the code?

I am very newbie to programming and stack overflow. I choose python as my first language. Today as I was writing some code to refresh and to improve my skills I wrote a little program. But with complete errors.
Here is the Program
a = [1 , 2, 3]
def list_append():
numbers = int(raw_input("Enter the number please"))
a.append(numbers)
print a
def average(list):
for marks in list:
print marks
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
def loop():
add_numbers = raw_input("Do you want to add another number")
if add_numbers == ("y"):
return list_append()
else:
return average()
while True:
loop()
print average(a)
Basically the function of this program is to ask user for the input of the number. Then append to the list and then show the average which is an easy one.
But I want the program to stop after the first input and ask user if they want to give another input ?
Can't understand where is the problem. ** I am not asking for the direct solution. I would rather want an explanation than the solution itself.**
Following is missing in your code:
Need to break any loop, your while loop in going into infinite loop.
while True:
loop()
2. Handle exception during type casting.
numbers = int(raw_input("Enter the number please"))
Create user enter number list in loop function and pass to list_append function to add numbers.
Also return from the loop function to pass argument into average function.
code:
def list_append(numbers):
while 1:
try:
no = int(raw_input("Enter the number please:"))
numbers.append(no)
break
except ValueError:
print "Enter only number."
return list(numbers)
def average(number_list):
avg = float(sum(number_list))/ len(number_list)
return avg
def loop():
numbers = []
while 1:
add_numbers = raw_input("you want to add number in list(Y):")
if add_numbers.lower()== ("y"):
numbers = list_append(numbers)
else:
return list(numbers)
numbers = loop()
avg = average(numbers)
print "User enter numbers:", numbers
print "average value of all enter numbers:", avg
output:
vivek#vivek:~/Desktop/stackoverflow$ python 17.py
you want to add number in list(Y):y
Enter the number please:10
you want to add number in list(Y):y
Enter the number please:e
Enter only number.
Enter the number please:20
you want to add number in list(Y):Y
Enter the number please:30
you want to add number in list(Y):n
User enter numbers: [10, 20, 30]
average value of all enters numbers: 20.0
vivek#vivek:~/Desktop/stackoverflow$
do not use variable names which are already define by python
e.g. list
>>> list
<type 'list'>
>>> list([1,2,3])
[1, 2, 3]
>>> list = [2]
>>> list([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>>
a = []
def average(list):
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
while True:
numbers = raw_input("Enter the number please or 'q' to quit : ")
if numbers == "q":
average(a)
break
else:
a.append(int(numbers))
Hope this helps

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