Home > Software engineering >  How to store numeric input in a loop
How to store numeric input in a loop

Time:12-09

I want to make two lists, the first containing three names and the second containing three lists of scores:

name_list = [[name1][name2][name3]] 
score_list = [[22,33,35][32,22,34][32,44,50]]

My current code is this:

name = []
name.append(input('input students name: '))
    
score = []
for i in range(3):
    score.append(int(input('input students scores: ')))

I want to save three names and three lists of scores, but it only saves the last input name and values.

Here is the program I am trying to make: enter image description here

CodePudding user response:

If you want 3 names and 3 sets of scores, you need another for loop:

names = []
scores = []
for _ in range(3):
    names.append(input('input students name: '))
    scores.append([])
    for _ in range(3):
        scores[-1].append(int(input('input students score: ')))

print(f"names: {names}")
print(f"scores: {scores}")
input students name: name1
input students score: 22
input students score: 33
input students score: 35
input students name: name2
input students score: 32
input students score: 22
input students score: 34
input students name: name3
input students score: 32
input students score: 44
input students score: 50
names: ['name1', 'name2', 'name3']
scores: [[22, 33, 35], [32, 22, 34], [32, 44, 50]]

CodePudding user response:

Do you mean that every time you run the script, it asks for the score value again? I.e., it doesn't save between sessions?

If so, you could save each var's value inside a text file that's stored in your script's folder.

One way you could go about this is:

def get_vars():
  try:
    fil = open("var-storage.txt", "r") # open file
    fil_content = str(fil.read()) # get the content and save as var
    # you could add some string splitting right here to get the
    # individual vars from the text file, rather than the entire
    # file
    fil.close() # close file
    return fil_content
  except:
    return "There was an error and the variable read couldn't be completed."


def store_vars(var1, var2):
  try:
        with open('var-storage.txt', 'w') as f:
          f.write(f"{var1}, {var2}")
        return True
  except:
        return "There was an error and the variable write couldn't be completed."

# ofc, you would run write THEN read, but you get the idea
  • Related