Home > Blockchain >  Printing highest value input
Printing highest value input

Time:04-11

This a simple python score calculation code, I need the code to print the highest score

file = open("score.txt","w")
number = eval(input("Enter the number of the records you need: "))

for i in range (1,number 1):
    name = input("Enter the name: ")
    file.write(name)
    file.write("\n")
    grade = int(input("Enter grade: "))
    file.write(str(grade))
    file.write("\n")
file.close()

file = open("score.txt","r")
file.close()
print()
print("High Score: ", grade)
print("Held By: ", name)
print()
print("Number of Scores: ", number)

I tried this

file = open("score.txt","w")
number = eval(input("Enter the number of the records you need: "))

for i in range (1,number 1):
    name = input("Enter the name: ")
    file.write(name)
    file.write("\n")
    grade = int(input("Enter grade: "))
    file.write(str(grade))
    file.write("\n")
file.close()

file = open("score.txt","r")
file.close()
print()
print("High Score: ", grade)
print("Held By: ", name)
print()
print("Number of Scores: "), max(number)

it does not seem to work and show error 'int' object is not iterable

CodePudding user response:

You could keep track of the names with the highest grade entered while the user enters the records so you don't have to read the whole file again:

def get_int_input(prompt: str) -> int:
    while True:
        try:
            num = int(input(prompt))
            break
        except ValueError:
            print('Error: Enter an integer, try again...')
    return num

def main() -> None:
    num_records = get_int_input('Enter the number of the records you need: ')
    highest_grade = 0
    highest_grade_names = []
    with open('score.txt', 'w') as file:
        for _ in range(num_records):
            name = input('Enter name: ')
            grade = get_int_input('Enter grade: ')
            file.write(f'{name}\n{grade}\n')
            if grade > highest_grade:
                highest_grade = grade
                highest_grade_names = [name]
            elif grade == highest_grade:
                highest_grade_names.append(name)
    print()
    print(f'Number of records entered: {num_records}')
    print(f'Highest grade: {highest_grade}')
    print(f'Held by: {", ".join(highest_grade_names)}')

if __name__ == '__main__':
    main()

Example Usage:

Enter the number of the records you need: 4
Enter name: Apple
Enter grade: 85
Enter name: Banana
Enter grade: 100
Enter name: Carrot
Enter grade: 100
Enter name: Durian
Enter grade: 65

Number of records entered: 4
Highest grade: 100
Held by: Banana, Carrot

What score.txt looks like:

Apple
85
Banana
100
Carrot
100
Durian
65

CodePudding user response:

When I run your code I do not get an error. But your code does not currently give you the highest score. Keeping a similar logic to your code...

with open("score.txt", "w") as f:
    number = int(input("Enter the number of the records you need: "))

    if number == 0:
        exit()

    # get name
    name = input("Enter the name: ")
    f.write(f"{name}\n")
    # get grade
    grade = int(input("Enter grade: "))
    f.write(f"{grade}\n")

    # current max score and corresponding name
    max_score = grade
    max_name = name
    for i in range(number - 1):
        # get name
        name = input("Enter the name: ")
        f.write(f"{name}\n")
        # get grade
        grade = int(input("Enter grade: "))
        f.write(f"{grade}\n")

        # update current max score and corresponding name
        if grade > max_score:
            max_score = grade
            max_name = name

print(f"\n{'High Score':16}: {max_score}")
print(f"{'Held By':16}: {max_name}\n")
print(f"{'Number of Scores':16}: {number}")

Sample Session

Enter the number of the records you need: 2
Enter the name: Bonnie
Enter grade: 90
Enter the name: Clyde
Enter grade: 56

High Score      : 90
Held By         : Bonnie

Number of Scores: 2

"score.txt"

Bonnie
90
Clyde
56

CodePudding user response:

If you want to get the highest score, you can do it without storing the variables in a file like this:

dic = {"Name": [], "Grade": []}

for i in range(int(input("Enter the number of the records you need: "))):
    dic["Name"].append(input("Enter the name: "))
    dic["Grade"].append(int(input("Enter grade: ")))

i = 0
highest = 0
for grade in dic["Grade"]:
    if grade > highest:
        highest = grade 
        index = i
    i  = 1


print("Highscore: {}\nHeld by: {}\nNumber of Scores: {}"
    .format(dic["Name"] [index], 
        dic["Grade"][index], len(dic["Name"])))

But if you want to store the data, just add this:

file = open("file_name.txt", 'w')
file.write(dict)
file.close()

    
  • Related