python program not giving desired result - python

def main():
names=[0]*10
for index in range(len(names)):
names[index] = input("Enter word " + str(index + 1) + ": ")
bubbleSort(names)
print("Names in Alphabetical order:")
print(names)
def bubbleSort(names):
for maxElement in range(len(names)-1, 0, -1):
for index in range(maxElement):
if names[index] > names[index+1]:
temp = names[index]
names[index] = names[index+1]
names[index+1] = temp
found = False
index=0
while found == False and index < len(names):
Searchword= input('enter a searchword:')
if scores[index] == Searchword :
found = True
else:
index = index + 1
if found:
print("Found")
else:
print("Not Found")
main()
Does everything required accept when a Searchword is entered that cannot be found it does not print 'not found' but only keeps asking for input.

Change if scores[index] == Searchword : to if names[index] == Searchword :
Place Searchword= input('enter a searchword:') outside the while loop
It should look something like this:
def main():
names=[0]*10
for index in range(len(names)):
names[index] = input("Enter word " + str(index + 1) + ": ")
bubbleSort(names)
print("Names in Alphabetical order:")
print(names)
def bubbleSort(names):
for maxElement in range(len(names)-1, 0, -1):
for index in range(maxElement):
if names[index] > names[index+1]:
temp = names[index]
names[index] = names[index+1]
names[index+1] = temp
found = False
index=0
Searchword= input('enter a searchword:')
while found == False and index < len(names):
if names[index] == Searchword :
found = True
else:
index = index + 1
if found:
print("Found")
else:
print("Not Found")
main()

you might need input before the loop, ie:
Searchword= input('enter a searchword:')
while found == False and index < len(names):
if scores[index] == Searchword :
found = True
else:
index = index + 1

Related

Can I fix the index out of range error when I try to get a different word out of the last place of a list with all the same words

For this exercise I can input words until i enter "stop". All the words that I have input will go in to a list. I use a for loop to loop over all the words in the list. If the word isnt the same as the next or previous I "mark" that word.If there are no marked words it wil print out that there are none.If there are 2 or more marked words it will print that it cant be known. This works well until the last word in the list is the "marked" one. I get the error list index out of range. Does anyone see a solution for this? Below I will paste the code.
Thank you!
woorden = []
woord = str(input())
vreemdeEend = 0
vreemdWoord = ""
while woord != "stop":
woorden.append(woord)
woord = str(input())
for index, elem in enumerate(woorden):
if (woorden[index] != woorden[index-1] and woorden[index] != woorden[index+1] and woorden[index-1] != 0):
vreemdeEend += 1
vreemdWoord = woorden[index]
if(vreemdeEend == 1):
print("De vreemde eend in de bijt is " + vreemdWoord)
elif(vreemdeEend >= 2):
print("vreemd eend is onbeduid")
else:
print("er is geen vreemd eend")`
I tried to check if the index is at the last place that it would check the previous 2 words to see if they are the same. But this didnt have any effect
woorden = []
woord = str(input())
vreemdeEend = 0
vreemdWoord = ""
while woord != "stop":
woorden.append(woord)
woord = str(input())
if len(woorden)>0:
woorden.append(woorden[-1] + "DIFRENCE")
for index, elem in enumerate(woorden):
if (woorden[index] != woorden[index-1] and woorden[index] != woorden[index+1] and woorden[index-1] != 0):
vreemdeEend += 1
vreemdWoord = woorden[index]
if(vreemdeEend == 1):
print("De vreemde eend in de bijt is " + vreemdWoord)
elif(vreemdeEend >= 2):
print("vreemd eend is onbeduid")
else:
print("er is geen vreemd eend")`

Python reverse each word in a sentence without inbuilt function python while preserve order

Not allowed to use "Split(),Reverse(),Join() or regexes" or any other
helping inbuilt python function
input something like this:
" my name is scheven "
output like this:
"ym eman si nevehcs"
you need to consider removing the starting,inbetween,ending spaces aswell in the input
I have tried 2 tries, both failed i will share my try to solve this and maby an idea to improve it
First try:
def reverseString(someString):
#lenOfString = len(someString)-1
emptyList = []
for i in range(len(someString)):
emptyList.append(someString[i])
lenOfString = len(emptyList)-1
counter = 0
while counter < lenOfString:
if emptyList[counter] == " ":
counter+=1
if emptyList[lenOfString] == " ":
lenOfString-=1
else:
swappedChar = emptyList[counter]
emptyList[counter] = emptyList[lenOfString]
emptyList[lenOfString] = swappedChar
counter+=1
lenOfString-=1
str_contactantion = ""
#emptyList = emptyList[::-1]
#count_spaces_after_letter=0
for letter in emptyList:
if letter != " ":
str_contactantion+=letter
#str_contactantion+=" "
str_contactantion+=" "
return str_contactantion
second try:
def reverse(array, i, j):
emptyList = []
if (j == i ):
return ""
for k in range(i,j):
emptyList.append(array[k])
start = 0
end = len(emptyList) -1
if start > end: # ensure i <= j
start, end =end, start
while start < end:
emptyList[start], emptyList[end] = emptyList[end], emptyList[start]
start += 1
end -= 1
strconcat=""
for selement in emptyList:
strconcat+=selement
return strconcat
def reverseStr(someStr):
start=0
end=0
help=0
strconcat = ""
empty_list = []
for i in range(len(someStr)):
if(someStr[i] == " "):
continue
else:
start = i
j = start
while someStr[j] != " ":
j+=1
end = j
#if(reverse(someStr,start,end) != ""):
empty_list.append(reverse(someStr,start,end))
empty_list.append(" ")
for selement in empty_list:
strconcat += selement
i = end + 1
return strconcat
print(reverseStr(" my name is scheven "))
The following works without managing indices:
def reverseString(someString):
result = crnt = ""
for c in someString:
if c != " ":
crnt = c + crnt # build the reversed current token
elif crnt: # you only want to do anything for the first space of many
if result:
result += " " # append a space first
result += crnt # append the current token
crnt = "" # and reset it
if crnt:
result += " " + crnt
return result
reverseString(" my name is scheven ")
# 'ym eman si nevehcs'
Try this:
def reverseString(someString):
result = ""
word = ""
for i in (someString + " "):
if i == " ":
if word:
result = result + (result and " ") + word
word = ""
else:
word = i + word
return result
You can then call it like this:
reverseString(" my name is scheven ")
# Output: 'ym eman si nevehcs'
Try this:
string = " my name is scheven "
def reverseString(someString):
result = ''
curr_word = ''
for i in someString:
if i == ' ':
if curr_word:
if result:
result = f'{result} {curr_word}'
else:
result = f'{result}{curr_word}'
curr_word = ''
else:
curr_word = f'{i}{curr_word}'
return result
print(repr(reverseString(string)))
Output:
'ym eman si nevehcs'
Note: if you're allowed to use list.append method, I'd suggest using a collections.deque as it's more performant than appending to a list. But of course, in the end you'll need to join the list together, and you mentioned that you're not allowed to use str.join, so that certainly poses an issue.

update value in python dictionary by adding a number

I want to make a program that adds a name in the dictionary if it doesn't exist already and count the times it is given as input. My code works, however, it doesn't add 1 when it iterates.
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
for name in namelist:
if word == name:
namelist[word] += 1
# else wasn't properly indented earlier
else:
namelist[word] = 1
print(namen())
print(namelist)
You can use the dict.get method instead to provide a default value to a new entry to the dict:
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
for name in namelist:
if word == name:
namelist[word] = namelist.get(word, 0) + 1
Your check is incorrect, you need if rather than for to see if the key exists, then you can remove the inner if statement
if name in namelist:
namelist[word] += 1
else:
namelist[word] = 1
No one said anything about the has_key method of dictionaries, which is in my opinion the standard way to to this:
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
if namelist.has_key(word):
namelist[word] += 1
else:
namelist[word] = 1
print(namen())
print(namelist)
try this
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
try:
namelist[word] += 1
except:
namelist[word] = 1
print(namen())
print(namelist)

Python list is not callable error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Code (lots of it, sorry):
#nea practice
def re_election():
print("A re-election is needed")
choice = int(input("Which test vote file would you like to use: "))
correct_choices = [1, 2]
while choice not in correct_choices:
choice = int(input("Error, try again: "))
if choice == 1:
filename = "Test1_Votes.txt"
elif choice == 2:
filename = "Test2_Votes.txt"
with open(filename, 'r'):
f = open(filename)
lines = f.readlines()
linecount = 0
candidates = ['a', 'b', 'c', 'd', 'e']
for line in lines:
linecount +=1
valid_votes = linecount
num_seats = 2
quota = int((valid_votes/(num_seats + 1))+ 1)
print("\n")
print("Quota is: " + str(quota))
all_lines = []
a_scores = []
b_scores = []
c_scores = []
d_scores = []
e_scores = []
for line in lines:
line = line.rstrip("\n") # strip new line character
lst = [int(x) for x in line.split(',')] # split line and cast to int
all_lines.append(lst)
a_scores.append(lst[0])
b_scores.append(lst[1])
c_scores.append(lst[2])
d_scores.append(lst[3])
e_scores.append(lst[4])
print(all_lines)
#fp
a_fp_votes = a_scores.count(1)
b_fp_votes = b_scores.count(1)
c_fp_votes = c_scores.count(1)
d_fp_votes = d_scores.count(1)
e_fp_votes = e_scores.count(1)
all_fp_votes = [a_fp_votes, b_fp_votes, c_fp_votes, d_fp_votes, e_fp_votes]
print(all_fp_votes)
candidates_fp_votes = dict(zip(candidates, all_fp_votes))
#sp
a_sp_votes = a_scores.count(2)
b_sp_votes = b_scores.count(2)
c_sp_votes = c_scores.count(2)
d_sp_votes = d_scores.count(2)
e_sp_votes = e_scores.count(2)
all_sp_votes = [a_sp_votes, b_sp_votes, c_sp_votes, d_sp_votes, e_sp_votes]
candidates_sp_votes = dict(zip(candidates, all_sp_votes))
#tp
a_tp_votes = a_scores.count(3)
b_tp_votes = b_scores.count(3)
c_tp_votes = c_scores.count(3)
d_tp_votes = d_scores.count(3)
e_tp_votes = e_scores.count(3)
all_tp_votes = [a_tp_votes, b_tp_votes, c_tp_votes, d_tp_votes, e_tp_votes]
candidates_tp_votes = dict(zip(candidates, all_tp_votes))
all_new_fp_votes = all_fp_votes
candidates_new_fp_votes = candidates_fp_votes
if (sum([x >= quota for x in [a_fp_votes, b_fp_votes, c_fp_votes, d_fp_votes, e_fp_votes]])) >= 2:
print("Quota Achieved")
quota_achieved = True
else:
print("Quota Not Achieved")
quota_achieved = False
if quota_achieved == True:
"""
Tiebreaker system
"""
final_vals = [a for a, b in candidates_fp_votes.items() if
list(candidates_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
print(i)
print(final_vals)
if not final_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = max(candidates_fp_votes, key=candidates_fp_votes.get)
winners.append(winner)
del candidates_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
f.close()
exit()
else:
print("Implementing step 1")
candidates_fp_votes[final_vals[0]] = candidates_fp_votes[final_vals[0]] + candidates_sp_votes[
final_vals[0]]
candidates_fp_votes[final_vals[1]] = candidates_fp_votes[final_vals[1]] + candidates_sp_votes[
final_vals[1]]
step1_vals = [a for a, b in candidates_fp_votes.items() if
list(candidates_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in step1_vals:
print(i)
if not step1_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = max(candidates_fp_votes, key=candidates_fp_votes.get)
winners.append(winner)
del candidates_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
f.close()
exit()
else:
print("Implementing step 2b")
candidates_fp_votes[step1_vals[0]] = candidates_fp_votes[step1_vals[0]] + \
candidates_tp_votes[final_vals[0]]
candidates_fp_votes[step1_vals[1]] = candidates_fp_votes[step1_vals[1]] + \
candidates_tp_votes[final_vals[1]]
step2b_vals = [a for a, b in candidates_fp_votes.items() if
list(candidates_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in step2b_vals:
print(i)
print(step2b_vals)
if not step2b_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = min(candidates_fp_votes, key=candidates_fp_votes.get)
winners.append(winner)
del candidates_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
f.close()
exit()
else:
print("There is a tie breaker which cannot be resolved between " + step2b_vals[0] + " and " +
step2b_vals[1])
f.close()
exit()
"""
STV
"""
eliminated = 0
while quota_achieved == False:
new_candidates = ['a', 'b', 'c', 'd', 'e']
eliminated_candidate = min(candidates_new_fp_votes, key=candidates_new_fp_votes.get)
print(eliminated_candidate + " has been eliminated ")
eliminated +=1
candidate_positions_in_list = [0, 1, 2, 3, 4]
candidate_and_positions = dict(zip(candidates, candidate_positions_in_list))
eliminated_candidate_position_in_list = (candidate_and_positions.get(eliminated_candidate))
for i, row in enumerate(all_lines):
#traversing each column
for j, c in enumerate(row):
#in each column in the row check for '1', if found replace by '0'
if j == eliminated_candidate_position_in_list and c== 1:
row[j] = 0
#in the same row check for '2', if found replace my 1
if 2 in row:
ind = row.index(2)
row[ind] = 1
print(all_lines)
a_new_scores = []
b_new_scores = []
c_new_scores = []
d_new_scores = []
e_new_scores = []
for list in all_lines:
a_new_scores.append(list[0])
b_new_scores.append(list[1])
c_new_scores.append(list[2])
d_new_scores.append(list[3])
e_new_scores.append(list[4])
a_new_fp_votes = a_new_scores.count(1)
b_new_fp_votes = b_new_scores.count(1)
c_new_fp_votes = c_new_scores.count(1)
d_new_fp_votes = d_new_scores.count(1)
e_new_fp_votes = e_new_scores.count(1)
all_new_fp_votes = [a_new_fp_votes, b_new_fp_votes, c_new_fp_votes, d_new_fp_votes, e_new_fp_votes]
candidates_new_fp_votes = dict(zip(new_candidates, all_new_fp_votes))
all_candidates_fp_votes = candidates_new_fp_votes
# sp
a_new_sp_votes = a_new_scores.count(2)
b_new_sp_votes = b_new_scores.count(2)
c_new_sp_votes = c_new_scores.count(2)
d_new_sp_votes = d_new_scores.count(2)
e_new_sp_votes = e_new_scores.count(2)
all_new_sp_votes = [a_new_sp_votes, b_new_sp_votes, c_new_sp_votes, d_new_sp_votes, e_new_sp_votes]
candidates_new_sp_votes = dict(zip(new_candidates, all_new_sp_votes))
# tp
a_new_tp_votes = a_new_scores.count(3)
b_new_tp_votes = b_new_scores.count(3)
c_new_tp_votes = c_new_scores.count(3)
d_new_tp_votes = d_new_scores.count(3)
e_new_tp_votes = e_new_scores.count(3)
all_new_tp_votes = [a_new_tp_votes, b_new_tp_votes, c_new_tp_votes, d_new_tp_votes, e_new_tp_votes]
candidates_new_tp_votes = dict(zip(new_candidates, all_new_tp_votes))
if eliminated_candidate == 'a':
candidates.remove('a')
try:
all_new_fp_votes.remove(a_new_fp_votes)
except ValueError:
pass
elif eliminated_candidate == 'b':
candidates.remove('b')
try:
all_new_fp_votes.remove(b_new_fp_votes)
except ValueError:
pass
elif eliminated_candidate == 'c':
candidates.remove('c')
try:
all_new_fp_votes.remove(c_new_fp_votes)
except ValueError:
pass
elif eliminated_candidate == 'd':
candidates.remove('d')
try:
all_new_fp_votes.remove(d_new_fp_votes)
except ValueError:
pass
elif eliminated_candidate == 'e':
candidates.remove('e')
all_new_fp_votes.remove(e_new_fp_votes)
del candidates_new_fp_votes
candidates_new_fp_votes = dict(zip(new_candidates, all_new_fp_votes))
if (sum([x >= quota for x in [a_new_fp_votes, b_new_fp_votes, c_new_fp_votes,
d_new_fp_votes, e_new_fp_votes]])) >= 2:
print("Quota Achieved")
quota_achieved = True
"""
Tiebreaker system
"""
print(all_candidates_fp_votes)
final_vals = [a for a, b in candidates_new_fp_votes.items() if list(candidates_new_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
print(i)
print(final_vals)
if not final_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = max(candidates_new_fp_votes, key=candidates_new_fp_votes.get)
winners.append(winner)
del candidates_new_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
f.close()
exit()
else:
print("Implementing step 1")
candidates_new_fp_votes[final_vals[0]] = candidates_new_fp_votes[final_vals[0]] + candidates_new_sp_votes[
final_vals[0]]
candidates_new_fp_votes[final_vals[1]] = candidates_new_fp_votes[final_vals[1]] + candidates_new_sp_votes[
final_vals[1]]
step1_vals = [a for a, b in candidates_new_fp_votes.items() if
list(candidates_new_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in step1_vals:
print(i)
if not step1_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = max(candidates_new_fp_votes, key=candidates_new_fp_votes.get)
winners.append(winner)
del candidates_new_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
f.close()
exit()
else:
print("Implementing step 2b")
candidates_new_fp_votes[step1_vals[0]] = candidates_new_fp_votes[step1_vals[0]] + \
candidates_new_tp_votes[final_vals[0]]
candidates_new_fp_votes[step1_vals[1]] = candidates_new_fp_votes[step1_vals[1]] + \
candidates_new_tp_votes[final_vals[1]]
step2b_vals = [a for a, b in candidates_new_fp_votes.items() if
list(candidates_new_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in step2b_vals:
print(i)
print(step2b_vals)
if not step2b_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = min(candidates_new_fp_votes, key=candidates_new_fp_votes.get)
winners.append(winner)
del candidates_new_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
else:
print("There is a tie breaker which cannot be resolved between " + step2b_vals[0] + " and " +
step2b_vals[1])
f.close()
exit()
else:
if eliminated == 2:
re_election()
else:
quota_achieved = False
print("Quota Not Achieved")
pass
pass
Txt file sample:
1,2,3,0,0
0,0,3,2,1
1,0,0,3,2
1,0,0,2,3
Sorry for having to make you read all that code.
I have had to include all of my code because this is a problem with the entire code and there is no way in which I can make this simpler for you.
In line 293 of the code, I have tried a list out of the values of candidates_new_fp_votes but it is not making the list. The list which is always purple in my IDE is no longer purple. It is not my IDE's fault as I have tried the same in the default python IDE and have also put my code into another python file and the same still happens. I think that something in my code is causing this to happen but I do not know.
When I run the code and select 2 (txt file sample above). It throws the error:
final_vals = [a for a, b in candidates_new_fp_votes.items() if list(candidates_new_fp_votes.values()).count(b) > 1]
TypeError: 'list' object is not callable
I'm assuming this is from candidates_new_fp_votes.values not being able to become a list.
I have tried to google this error for 2 hours straight with the results being of no hope to me.
Any help?
Thanks in advance.
Do not override any builtin function/method/statement in python.
You have overrode list() in:
for list in all_lines:
a_new_scores.append(list[0])
b_new_scores.append(list[1])
c_new_scores.append(list[2])
d_new_scores.append(list[3])
e_new_scores.append(list[4])
You get an exception because after you overrode list() by list variable. It [variable] is not callable:
TypeError: 'list' object is not callable
I have overrode list() in:
for list in all_lines:
a_new_scores.append(list[0])
b_new_scores.append(list[1])
c_new_scores.append(list[2])
d_new_scores.append(list[3])
e_new_scores.append(list[4])
I got an exception because I overrode list() by list variable. It is not callable:
TypeError: 'list' object is not callable
Instead I should have put:
for lst in all_lines:
a_new_scores.append(lst[0])
b_new_scores.append(lst[1])
c_new_scores.append(lst[2])
d_new_scores.append(lst[3])
e_new_scores.append(lst[4])
As this does not override the list().

Division by zero error when adding rogue value without any data

Hi having trouble trying to fix an error that occurs when I put just a '#' or rogue value in case someone doesn't want to add any data. I don't know how to fix it and I'm hoping to just end the code just like I would with data.
#Gets Data Input
def getData():
fullList = []
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
while inputText != "#":
nameList = []
nameList2 = []
nameList = inputText.split()
nameList2.extend((nameList[0],nameList[1]))
nameList2.append((float(nameList[2]) + float(nameList [3]))/2)
fullList.append(nameList2)
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
print("\n")
return fullList
#Calculates Group Average
def calc1(fullList):
total = 0
for x in fullList:
total = total + x[2]
groupAverage = total/(len(fullList))
return(groupAverage)
#Finds Highest Average
def calc2(fullList):
HighestAverage = 0
nameHighAverage = ""
for x in fullList:
if x[2] > HighestAverage:
HighestAverage = x[2]
nameHighAverage = x[0] + " " + x[1]
return (HighestAverage, nameHighAverage)
#Returns Marks above average
def results1(groupAverage,r1FullList):
r1FullList.sort()
print("List of students with their final mark above the group average")
print("--------------------------------------------------------------")
print("{:<20} {:<12}".format("Name","Mark"))
for x in r1FullList:
if x[2] > groupAverage:
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f}".format(name,x[2]))
def calc3(x):
if x[2] >= 80:
return 'A'
elif x[2] >= 65:
return 'B'
elif x[2] >= 50:
return 'C'
elif x[2] < 50:
return 'D'
else:
return 'ERROR'
def results2(fullList):
print("List of Studens with their Final Marks and Grades")
print("-------------------------------------------------")
print("{:<20} {:<12} {:<12}".format("Name","Mark","Grade"))
for x in fullList:
grade = calc3(x)
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f} {:<12}".format(name,x[2],grade))
#Checks for boundary and invalid data
def checkInput(question):
while True:
textInput = input(question)
if textInput == "#":
return textInput
splitList = textInput.split()
if len(splitList) !=4:
print("Invalid Format, Please Try Again")
continue
try:
a = float(splitList[2])
a = float(splitList[3])
if float(splitList[2]) < 0 or float(splitList[2]) > 100:
print("Invalid Format, Please Try Again")
continue
if float(splitList[3]) < 0 or float(splitList[3]) > 100:
print("Invalid Format, Please Try Again")
continue
return(textInput)
except ValueError:
print("Invalid Input, Please Try Again")
continue
#Main Program
#Input Data
fullList = getData()
#Process Data
groupAverage = calc1(fullList)
HighestAverage, nameHighAverage = calc2(fullList)
#Display Results
print("The group average was %.2f" % groupAverage)
print("The student with the highest mark was: %s %0.2f" %(nameHighAverage,HighestAverage))
results1(groupAverage,fullList)
print("\n")
results2(fullList)
Your program works OK for me, unless you enter a # as the first entry, in which case fullList is [] and has length 0. Hence, DivisionByZero at this line: groupAverage = total/(len(fullList)).
You could modify your code to check for this and exit:
import sys
fullList = getData()
if not fullList:
print('No Data!')
sys.exit()

Categories