Day 049 - Project 49 : Loading a High Score Table

Hello All,
this my solution which is different to the solution as well :slight_smile:

python
list = []
maxscore = 0
maxname=""

f = open("high.score", "r")
print("")
print("HIGH SCORE TABLE")
print("")
for line in f:
  name, score_str = line.split()
  score = int(score_str)  
  list.append((name, score))
  if maxscore < score:
    maxscore = score
    maxname = name
  
f.close()

print(maxname, maxscore)
1 Like

Question: Declaring max = 0 and typecasting within ‘if’ statement renders ‘max’ as string. Whereas, separately typecasting variable ‘data’ renders ‘max’ as integer. Why this is happening? The solution given also typecasts within ‘if’ statement, but it throws no error.

Tutorial number: Day 49

Repl link: main.py - Day49_100Days - Replit

My code:

print("🌟Current Leader🌟\n\nAnalyzing high scores......\n")

max = 0
maxName = None

f = open("high.score", "r")
while True:
    contents = f.readline().strip()
    if contents == "":
       break
    uname, data = contents.split()
    # no error in following case:
    data = int(data)    
    if data > max:
        max = data
        maxName = uname

    # throws error if typecasted within 'if' statement:
    # [Error message: TypeError: '>' not supported between instances of 'int' and 'str']

    # if int(data) > max:
    #     max = data
    #     maxName = uname
    
f.close()

print(f"Current leader is {maxName} with score {max}")

Solution given:

import os, time

f = open("high.score", "r")
scores = f.read().split("\n")
f.close()

highscore = 0
name = None

for rows in scores:
  data = rows.split()
  if data != []:
    if int(data[1]) > highscore:
      highscore = int(data[1])
      name = data[0]

print("The winner is", name, "with", highscore)

This is because you later set max to a string.

max = 0
maxName = None

f = open("high.score", "r")
while True:
    contents = f.readline().strip()
    if contents == "":
       break
    uname, data = contents.split()
    # no error in following case:
    # data = int(data)    
    # if data > max:
    #     max = data
    #     maxName = uname

    # throws error if typecasted within 'if' statement:
    # [Error message: TypeError: '>' not supported between instances of 'int' and 'str']
    if int(data) > max:
        max = data  # <--- here, data is a string
        maxName = uname

Also, it is usually bad practice to “shadow”/overwrite builtin functions like max. What if you need to use that function later?

2 Likes

Thanks man for the clarification. I was scratching my head over this. I’m grateful for your kind help.