1
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)

如果我输入字母 ae 作为他们的名字和数字 1-5 作为值,它会打印出 e 得到最高值和最低值,但是数字是正确的,5 是最高的,1 是最低的

4

1 回答 1

0

首先,您应该保留max_indexmin_index,因为您比较了值但忘记了它们的索引。其次,min应该修改逻辑:如果一个值不大于max,它一定是最小值吗?不。它适用于您的输入 1..5,但通常不会。最后,我们应该避免使用minmax作为变量名,因为它们会覆盖各自的内置函数。

所以

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)
于 2020-05-28T11:03:39.447 回答