How to store numeric input in a loop - python

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

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]]

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

Arrays in python, arrays won't line up, ( a beginner to coding)

I am trying to code some arrays in python, but when I run the code below, the "sort" and "people" lists won't line up properly ie. the sort is showing the wrong people. I am quite new to python so please keep code simple thanks.
I know a lot of the code is repeated, but I am working on it. The problem area is mostly the last 3 lines but i have attached the rest, just to be sure.
people = []
score = []
people.append("Doc")
people.append("Sarah")
people.append("Jar-Jar")
Doc1 = int(input("Enter the test score for Doc "))
print("Test score:", Doc1)
Sarah1 = int(input("Enter the test score for Sarah "))
print("Test score:", Sarah1)
Jar1 = int(input("Enter the test score for Jar-Jar "))
print("Test score:", Jar1)
score.append(Doc1)
score.append(Sarah1)
score.append(Jar1)
sort = sorted(score, reverse = True)
print("[",sort[0],", '", people[0],"']")
print("[",sort[1],", '", people[1],"']")
print("[",sort[2],", '", people[2],"']")
Make tuples out of the scores and names so you can keep them together, and put those in a list; then just sort the list.
people = ["Doc", "Sarah", "Jar-Jar"]
scores = [
(int(input(f"Enter the test score for {person} ")), person)
for person in people
]
scores.sort(reverse=True)
for score, person in scores:
print(f"[{score}], '{person}'")
Enter the test score for Doc 1
Enter the test score for Sarah 4
Enter the test score for Jar-Jar 3
[4], 'Sarah'
[3], 'Jar-Jar'
[1], 'Doc'

Remove Bottom 3 scores in file

numberofbands = int(input("How many bands are there in the competition? "))
print("Input each band’s name pressing enter after each one")
file = open("scores.txt","w")
for loop in range(numberofbands):
name = input("\nEnter the name of the band: ")
votes = input("Enter how many votes that band received: ")
file.write(name + "," + votes + "," + "\n")
file.close()
number_of_lines = len(open("scores.txt").readlines( ))
def removebottom3():
#code to remove bottom 3 here
removebottom3()
The first part writes the band's name and score to the file.
I want the code to remove the lowest 3 scoring bands from the file. There will be a function for that.
How can I do this?
Thanks in advance.
You are quite off. Let me help you.
First, consider using Counter, it is meant for this kind of cases.
Second, try dividing the script logic into blocks (divide and conquer!), first get the data, then sort and remove the last 3, and only at the end write the results to a file.
Here is an example of the implementation.
from collections import Counter
numberofbands = int(input("How many bands are there in the competition? "))
print("Input each band’s name pressing enter after each one")
scores = Counter()
for n in range(numberofbands):
name = input("\nEnter the name of the band: ")
vote = input("Enter how many votes that band received: ")
scores.update({name:int(votes)})
#remove the last 3
final = scores.most_common()[:-3]
#write to file
with open('scores.txt', 'w') as f:
for name, vote in final:
f.write(f'{name},{vote}\n')
since you are already reading all the lines from the file,
number_of_lines = len(open("scores.txt").readlines( ))
you can use sorted to sort your lines by score,
lines = open("scores.txt").readlines()
sorted(lines,
key=lambda x : float(x.split(",")[1]),
reverse = True)

How to record inputs when using "For Loop"

I'm trying to ask the user to input how many classes they have (x), ask "What are your grades in those classes?" x amount of times, and record all of the inputted grades to use later.
I tried to assign the question to a variable and ask to print the variable, but I get only the last inputted number. I don't want to print the numbers, I want to store them for later so I can add them together. I was just using the print function to see how my numbers would be stored if assigning the variable actually worked. How would I record all the inputted numbers to later add and calculate GPA?
numofclasses = int(input("How many honors classes do you have?: "))
for i in range(numofclasses):
grades = str(input("Enter the unweighted grade from one class "))
print(grades)
I want to get all the inputted numbers recorded, but by using the print option I only get the last inputted number recorded.
The thing you want to use is a list, which is used to container which holds a sequence of datatypes, like integer, characters, etc,
Think of it this way, if you want to use 3 variables in python what would you generally do
a = 1
b = 2
c = 3
This works fine, but what if the number of variables is 50, or 100, how many variables will you keep defining, hence you would need a container to store these, which is where a list comes in. So we would just do
li = [1,2,3]
And access these variables via indexes, which start from 0
a[0] #1
a[1] #2
a[2] #3
Keeping this in mind, we would do!
numofclasses = int(input("How many honors classes do you have?: "))
#List to save all grades, defined by assigning variable to []
all_grades = []
for i in range(numofclasses):
#Take grades from the user
grades = input("Enter the unweighted grade from one class ")
#Append the grades to the list, using list.append function
all_grades.append(grades)
#Loop through the list to print it
for item in all_grades:
print(item)
#Print all grades in a single line by joining all items of list in a string
s = " ".join(all_grades)
print(s)
And the output will look like
How many honors classes do you have?: 3
Enter the unweighted grade from one class A
Enter the unweighted grade from one class B
Enter the unweighted grade from one class C
#All grades in different lines
A
B
C
#All grades in single line
A B C
It seems to me there are a couple options that may be suitable.
Printing the input each iteration:
numofclasses = int(input("How many honors classes do you have?: "))
for i in range(numofclasses):
grades = str(input("Enter the unweighted grade from one class "))
print(grades) # move print to inside of loop
Storing the values in a list for printing later:
numofclasses = int(input("How many honors classes do you have?: "))
grades = []
for i in range(numofclasses):
grades.append(str(input("Enter the unweighted grade from one class ")))
print(grades) # will look like ["A", "B", "C", "B"]
Here is how yo do it:
class_dict = {}
numOfClasses = input("How many classes do you take? Enter here : ")
for i in range(int(numOfClasses)):
class_dict["class" + str(i +1)] = input("Enter your grade for class " + str(i +1) + ": ")
print(class_dict)
The above should do it.

Python transform current list into 2d

I have designed a code which functions as I wish to do, by asking the administrator at my private school the number of students, how many grades to input per each student and lastly the course code for the courses that they are taking.
COLS= int(input("number of students to enter: "))
ROWS= int(input("number of grades per student: "))
def main(COLS,ROWS):
number =[]
for c in range(COLS):
student =(input("enter student Name: "))
number.append(student)
for r in range (ROWS):
course=input("Enter course Code: ")
number.append(course)
grades =(input("Enter grade for module: "))
number.append(grades)
print(number)
main(COLS,ROWS)
An example of the output is:
number of students to enter: 3
number of grades per student: 2
enter student Name: LarryH
Enter course Code: Math202
Enter grade for module: 80
Enter course Code: Sci101
Enter grade for module: 90
enter student Name: JeromeK
Enter course Code: TT101
Enter grade for module: 60
Enter course Code: PSY205
Enter grade for module: 50
enter student Name: CheungL
Enter course Code: PS100
Enter grade for module: 80
Enter course Code: Math300
Enter grade for module: 50
['LarryH', 'Math202', '80', 'Sci101', '90', 'JeromeK', 'TT101', '60', 'PSY205', '50', 'CheungL', 'PS100', '80', 'Math300', '50']
Now the code works except for the last line of my output where the list is given with the students and their respective grades and course code.
I am trying to instead of my output producing that 1d list, produce a 2d list, for example:
[
["Andre", "MA22", 79, "MA300", 88, "CM202", 69],
["Larry", "PS44", 67, "MA555", 80, "ACC200", 67],
...
]
Does anyone have any suggestions as to what I may alter in my code to produce a desired output like that above,
Thank you
Within the first loop, you can create a new temporary array to store the data for that particular student, e.g.:
for c in range(COLS):
studentInfo = [] # Info per-student
student =(input("enter student Name: "))
studentInfo.append(student)
for r in range (ROWS):
course=input("Enter course Code: ")
studentInfo.append(course)
# ...
# ...
number.append(studentInfo)
You could also look into storing student info in dictionaries, rather than lists so that the order is not as important. So instead of:
singleStudentInfo = ["Andre", "MA22", 79, "MA300", 88, "CM202", 69]
You would have:
singleStudentInfo = {"name": "Andre", "MA22": 79, "MA300": 88, "CM202": 69}

Error - input expected at most 1 argument, got 3

I've set up the following for loop to accept 5 test scores. I want the loop to prompt the user to enter 5 different scores. Now I could do this by writing the input "Please enter your next test score", but I'd rather have each inputted score prompt for its associated number.
So, for the first input, I'd like it to display "Please enter your score for test 1", and then for the second score, display "Please enter your score for test 2". When I try to run this loop, I get the following error:
Traceback (most recent call last):
File "C:/Python32/Assignment 7.2", line 35, in <module>
main()
File "C:/Python32/Assignment 7.2", line 30, in main
scores = input_scores()
File "C:/Python32/Assignment 7.2", line 5, in input_scores
score = int(input('Please enter your score for test', y,' : '))
TypeError: input expected at most 1 arguments, got 3
Here's the code
def input_scores():
scores = []
y = 1
for num in range(5):
score = int(input('Please enter your score for test', y, ': '))
while score < 0 or score > 100:
print('Error --- all test scores must be between 0 and 100 points')
score = int(input('Please try again: '))
scores.append(score)
y += 1
return scores
A simple (and correct!) way to write what you want:
score = int(input('Please enter your score for test ' + str(y) + ': '))
Because input does only want one argument and you are providing three, expecting it to magically join them together :-)
What you need to do is build your three-part string into that one argument, such as with:
input("Please enter your score for test %d: " % y)
This is how Python does sprintf-type string construction. By way of example,
"%d / %d = %d" % (42, 7, 42/7)
is a way to take those three expressions and turn them into the one string "42 / 7 = 6".
See here for a description of how this works. You can also use the more flexible method shown here, which could be used as follows:
input("Please enter your score for test {0}: ".format(y))

Categories