Implement a condition into a array - python

I'm trying to implement another condition into my program but can't seem to figure it out.
Here is the code:
print ("Welcome to the winning card program.")
year_one=[]
year_one.append(eval(input("Enter the salary individual 1 got in year 1: ")))
year_one.append(eval(input("Enter the salary individual 2 got in year 1: ")))
if year_one[0]==year_one[1]:
print("Error. The amount are the same, please reenter information.")
year_two=[]
year_two.append(eval(input("Enter the salary individual 1 got in year 2: ")))
year_two.append(eval(input("Enter the salary individual 2 got in year 2: ")))
if year_two[0]==year_two[1]:
print("Error. The amount are the same, please reenter information.")
year_three=[]
year_three.append(eval(input("Enter the salary individual 1 got in year 3: ")))
year_three.append(eval(input("Enter the salary individual 2 got in year 3: ")))
if year_three[0]==year_three[1]:
print("Error. The amount are the same, please reenter information.")
year_four=[]
year_four.append(eval(input("Enter the salary individual 1 got in year 4: ")))
year_four.append(eval(input("Enter the salary individual 2 got in year 4: ")))
if year_four[0]==year_four[1]:
print("Error. The amount are the same, please reenter information.")
year_five=[]
year_five.append(eval(input("Enter the salary individual 1 got in year 4: ")))
year_five.append(eval(input("Enter the salary individual 2 got in year 4: ")))
if year_five[0]==year_five[1]:
print("Error. The amount are the same, please reenter information.")
individual1_total=year_one[0]+year_two[0]+year_three[0]+year_four[0]+year_five[0]
individual2_total=year_one[1]+year_two[1]+year_three[1]+year_four[1]+year_five[1]
if (individual1_total>individual2_total):
print("Individual one has the highest salary.")
elif (individual2_total>individual1_total):
print("Individual two has the highest salary.")
If the salary for the two individuals for a particular year is exactly the same, you should print an error and make the user enter both the salaries again for that year. (The condition is the salaries should not be the exact same).
I look forward to everyone's feedback.
Thank you in advance.

Ok so building on surge10 here is a more complete replacement of your code. I broke all the pieces down into functions, and made a dictionary as my in in-memory database.
total_years = 5
years = {}
def dict_key(year, userId):
return '{}:{}'.format(year, userId)
def get_user_data(year, userId):
key = dict_key(year, userId)
years[key] = float(input("Enter the salary individual {} got in year {}:".format(userId, year)))
def get_year_salaray(year, userId):
key = dict_key(year, userId)
return years[key]
def any_salaries_match(year, userIds):
for userLeft in userIds:
salary_left = get_year_salaray(year, userLeft)
for userRight in userIds:
if userLeft != userRight:
salary_right = get_year_salaray(year, userRight)
if salary_left == salary_right:
return True
def get_user_totals(userId):
total = 0
for key, value in years.items():
if ':{}'.format(userId) in key:
total += value
return total
for x in range(total_years):
year = x + 1
data_invalid = True
while data_invalid:
userOne = 1
userTwo = 2
get_user_data(year, userOne)
get_user_data(year, userTwo)
if any_salaries_match(year, [userOne, userTwo]):
print("Error. The amount are the same, please reenter information.")
else:
data_invalid = False
userOneTotal = get_user_totals(1)
userTwoTotal = get_user_totals(2)
if (userOneTotal>userTwoTotal):
print("Individual one has the highest salary.")
elif (userTwoTotal>userOneTotal):
print("Individual two has the highest salary.")

Since we were checking for five different years I used a loop for those five years
Later we can get it back into individual years.
print ("Welcome to the winning card program.")
years=[]
for x in range(5):
# range starts at zero so add one all the time
# to start it at one
y = str(x + 1)
errors = True
while errors:
salary_one = input("Enter the salary individual 1 got in year " + y + ": ")
salary_two = input("Enter the salary individual 2 got in year " + y + ": ")
if salary_one == salary_two:
print("Error. The amount are the same, please reenter information.")
errors = True
else:
years.append([salary_one, salary_two])
errors = False
year_one = years[0]
year_two = years[1]
...
print(year_one)
print(year_two)
...

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

Print the arithmetic average, the youngest and oldest age

This Python program should read a birth year until the number zero is entered.
The program should then print out the average age and how old the youngest and oldest is.
I need help with two things.
Print "Unreasonable age, please try again" when input year is -N, like "-45"
Print the result i.e. the arithmetic average, the youngest and oldest only when I exit the loop.
That means when I enter 0.
Current output:
Please type in birth year, to stop, enter 0: 1948
Average age is 72.0 years old.
The younges is 72 years old, and the oldest is 72 years old.
Please type in birth year, to stop, enter 0: 1845
Unreasonable age, please try again
Average age is 72.0 years old.
The younges is 72 years old, and the oldest is 72 years old.
Please type in birth year, to stop, enter 0: 1995
Average age is 48.5 years old.
The younges is 25 years old, and the oldest is 72 years old.
Please type in birth year, to stop, enter 0: 2005
Average age is 37.333333333333336 years old.
The younges is 15 years old, and the oldest is 72 years old.
Please type in birth year, to stop, enter 0: 0
Average age is 37.333333333333336 years old.
The youngest is 15 years old, and the oldest is 72 years old.
Expected output that I want:
Please type in birth year, to stop, enter 0.
Year: 1998
Year: 1932
Year: 1887
Fail: Unreasonable age, please try again.
Year: 1987
Year: -77
Fail: Unreasonable age, please try again.
Year: 1963
Year: 0
Average age is 49 years old. The youngest is 21 years old, and the oldest is 87 years old.
Example code:
# set number_years to zero ### Initial value (has not started counting yet)
number_year = 0
# set number_years to zero ### Initial value (has not started counting yet)
sum_year = 0
# set sum_year to zero ### No maximum age yet
max_year = 0
# set max_year to zero ### Well increased minimum value (age) to start with
min_year = 110
# set input_year to minus 1 ### Only as start value for the sake of the loop start!
input_year = -1
# White input_year is not 0:
while input_year != 0:
# print info and store input value to input_year, stop if 0 is entered
input_year = int(input("Please type in birth year, to stop, enter 0: "))
# let age be (2020 - input_year)
age = (2020 - input_year)
# To avoid beauty flaws with the printout "Unreasonable year ..."
# when the final zero is entered, we must check that age is not 2020
# which it is deceptive enough because 2020-0=2020
# if age is less than zero or age is greater than 110 and age is not 2020:
if age < 0 or age > 110 and age != 2020:
# Print "Unreasonable age, please try again"
print("Unreasonable age, please try again")
# else
else:
# if input_year is greater than zero:
if input_year > 0:
# increase number_year with 1
number_year += 1
# let sum_year become sum_year + age
sum_year = sum_year + age
# if age is less than min_year:
if age < min_year:
# set min_year to age ### New minimum age found
min_year = age
# if age is bigger than max_year:
if age > max_year:
# set max_year to age ### New maximum age found
max_year = age
## If the entered number was 0, exit the loop
#if input_year == 0:
# break
# Now just print the arithmetic average, the youngest and oldest
# Print "Average age is ", sum_year / number_year, "year."
print("Average age is ", sum_year / number_year, "years old.")
# Print "The younges is ", min_year, " and the oldest is ", max_year
print("The youngest is", min_year, "years old,", " and the oldest is ", max_year, "years old.")
# Done! :-)
The code works by simply unindenting the two last print statements and uncommenting the if …: break:
# Initial value (has not started counting yet)
number_year = 0
# Initial value (has not started counting yet)
sum_year = 0
# No maximum age yet
max_year = 0
# Well increased minimum value (age) to start with
min_year = 110
# Only as start value for the sake of the loop start!
input_year = -1
while input_year != 0:
# print info and store input value to input_year, stop if 0 is entered
input_year = int(input("Please type in birth year, to stop, enter 0: "))
age = 2020 - input_year
# To avoid beauty flaws with the printout "Unreasonable year ..."
# when the final zero is entered, we must check that age is not 2020
# which it is deceptive enough because 2020-0=2020
if age < 0 or age > 110 and age != 2020:
print("Unreasonable age, please try again")
# else
else:
if input_year > 0:
number_year += 1
sum_year += age
if age < min_year:
### New minimum age found
min_year = age
if age > max_year:
### New maximum age found
max_year = age
if input_year == 0:
break
# print the arithmetic average, the youngest and oldest
print("Average age is ", sum_year / number_year, "years old.")
print("The youngest is", min_year, "years old,", " and the oldest is ", max_year, "years old.")
I also removed unnecessary comments. But, your code can be simplified very much by simply using a list:
ages = []
while True: # infinite loop - we will exit by break-ing when age is 0
age = 2020 - int(input("Please enter birth year (0 to exit)"))
if age == 2020: # user entered a 0 - exit loop
break
if age < 0 or age > 110:
print("Unreasonable age, please try again")
continue # directly go to next loop
ages.append(age) # will only get appended if the condition above was false because of the continue
if ages: # ages list is not empty
print("Average age is", sum(ages) / len(ages), "years old")
print("The youngest is", min(ages), "old, and the oldest is", max(ages), "old")
else:
print("No ages entered - cannot print mean, min and max age - exiting")
You could store all the ages in a list and then do the math you need with that.
# initialize your list
ages = []
# run your code here, adding the age value with each valid input
# this can be done right before finishing the loop, after the last if statement
...
while input_year != 0:
...
ages.append(age)
# at the end, do the required calculations
average_age = np.mean(ages)
min_age = np.min(ages)
max_age = np.max(ages)

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

Python declare winner using dictionary and loop

This is the output of the code I am trying to write. I have seen this done for C++, but not python with a dictionary. The key here is the dictionary is not optional. I need to use it to fulfill the assignment.
ID Candidate Votes Received % of Total Vote
1 Johnson 5000 55.55
2 Miller 4000 44.44
Total 9000
and the winner is Johnson!
I need to use a dictionary and a loop to create this. However, I am stuck on 3 points.
1.The percent- current code returns the percent before it has the whole total ex: first candidate always has 100%.
2. Declare a winner- code finds the max votes and returns the number value but I need it to return the name.
3. How to format the dictionary values so it lines up under the header. I don't think is possible, but it must be a requirement to use a dictionary for a reason. I am thinking I need to make a copy of the dictionary and format that?
Here is what I have so far:
totalVotes=[]
dct = {}
i = 1
while(True):
name = input('Please enter a name: ')
if name == '':
break
votes = input('Please enter vote total for canidate: ')
totalVotes.append(votes)
totalVotesInt= map(int, totalVotes)
total = sum(totalVotesInt)
dct[i] = {name,votes,int(votes)/total*100}
i += 1
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(header)
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+max(totalVotes))
Which returns:
Please enter a name: Smith
Please enter vote total for canidate: 100
Please enter a name: Frieda
Please enter vote total for canidate: 200
Please enter a name: West
Please enter vote total for canidate: 10
Please enter a name:
ID Name Votes % of Total Vote
1 {'Smith', '100', 100.0}
2 {'Frieda', 66.66666666666666, '200'}
3 {3.225806451612903, '10', 'West'}
Total 310
The Winner of the Election is 200
You add the number of each candidates votes at the same time you calculate the percent vote for each candidate. You need to find the total votes first, then divide each candidates votes by the total
You are returning the max of a list of integers. Obviously you aren't going to get a string. You need some way to connect the number votes with the candidate.
Don't bother. You can try to figure out how many tabs you need to get the whole thing lined up, but from experience, it is basically impossible. You could separate them with commas and open it in excel as a csv, or you could just make the user figure out what number goes with what.
The other answer uses data tables, so I will take another, more vanilla and cool approach to getting what you want.
class candidate():
def __init__(self, name, votes):
self.name = name
self.votes = int(votes)
def percentvotes(self, total):
self.percent = self.votes/total
def printself(self, i):
print('{}\t{}\t\t{}\t\t{}'.format(i, self.name, self.votes, self.percent))
def getinput():
inp = input('Please enter your candidates name and votes')
return inp
candidates = []
inp = getinput()
s = 0
while inp != '':
s+=1
candidates.append(candidate(*inp.split(" ")))
inp = getinput()
for c in candidates:
c.percentvotes(s)
candidates.sort(key = lambda x:-x.percent)
print('ID\tname\t\tvotes\t\tpercentage')
for i, c in enumerate(candidates):
c.printself(i+1)
I have added very little changes to your code to make it work:
I have mentioned the changes as comments in the code.
Edit: It's more efficient to use objects for each candidate if you require scaling in the future.
totalVotes=[]
dct = {}
i = 1
while(True):
name = input('Please enter a name: ')
if name == '':
break
votes = input('Please enter vote total for canidate: ')
totalVotes.append(votes)
totalVotesInt= map(int, totalVotes)
total = sum(totalVotesInt)
# I change it to a list so it's much easier to append to it later
dct[i] = list((name,int(votes)))
i += 1
# I calculate the total percent of votes in the end and append to the candidate
maxVal = 0
for i in range(1, len(dct) + 1):
if dct[i][1] > maxVal:
maxInd = i
dct[i].append(int((dct[i][len(dct[i]) - 1]) / total * 100))
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(dct)
print(header)
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+ dct[maxInd][0]))
I believe that this is the solution you are looking for. Just change the input statements in case you are using Python 2.x. Using Dataframe, the output will be exactly how you wanted.
import pandas as pd
import numpy as np
df = pd.DataFrame(columns=["Candidate", "Votes Received","Percentage of total votes"])
names=list()
votes=list()
while True:
name = str(input("Enter Name of Candidate."))
if name=='':
break
else:
vote = int(input("Enter the number of votes obtained."))
names.append(name)
votes.append(vote)
s=sum(votes)
xx=(votes.index(max(votes)))
myArray = np.array(votes)
percent = myArray/s*100
for i in range(len(names)):
df1 = pd.DataFrame(data=[[names[i],votes[i],percent[i]]],columns=["Candidate", "Votes Received","Percentage of total votes"])
df = pd.concat([df,df1], axis=0)
df.index = range(len(df.index))
print (df)
print ("Total votes = ",s)
print ("The man who won is ",names[xx])

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!

Categories

Resources