PupilNames=[""]*5
TestMarks=[0]*5
min =TestMarks[0]
max=TestMarks[0]
min=1
for index in range(5):
PupilNames[index]=str(input("Please enter the pupil's name: "))
TestMarks[index]=int(input("Please enter the test mark: "))
if TestMarks[index] >max:
max=TestMarks[index]
else:
min=TestMarks[index]
print(PupilNames[index],"got the highest mark which was",max)
print(PupilNames[index],"got the lowest mark which was",min)
If i input letters ae for their names and numbers 1-5 for the value, it prints that e got the highest value as well as the lowest, however the numbers are correct, 5 is highest and 1 is lowest
First you should keep max_index
and min_index
as well because you compare the values but forget about their index. Second, the min
logic should be revised: if a value is not greater than the max
, is it necessarily a minimum? No. It worked for your inputs 1..5 but it won't in general. Lastly, we should avoid min
and max
as variable names as they override respective built-in functions.
So
PupilNames = [""]*5
TestMarks = [0]*5
# Renamed these variables
min_mark = float("inf") # This should be something huge to begin with
max_mark = float("-inf") # This should be something tiny to begin with
# Below are new
min_index = 0
max_index = 0
for index in range(5):
# No need to cast to str, it's already so
PupilNames[index] = input("Please enter the pupil's name: ")
TestMarks[index] = int(input("Please enter the test mark: "))
if TestMarks[index] > max_mark:
max_mark = TestMarks[index]
max_index = index
# Note the change here
elif TestMarks[index] < min_mark:
min_mark = TestMarks[index]
min_index = index
print(PupilNames[max_index], "got the highest mark which was", max_mark)
print(PupilNames[min_index], "got the lowest mark which was", min_mark)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.