Python transform current list into 2d - python

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}

Related

How to check 2 conditions in while loop at the same time

The Question
Write a program that asks the user to enter their name and grades for all the courses they took this
semester. Check that the name is composed of only letters and that each grade entry is composed of
numbers only. When the user has entered all their grades, they may enter -1 to indicate they are done.
Calculate the average grade and display that to the user.
Sample given to me
Enter your name: Sar#
Please enter a valid name.
Enter your name: sara
Enter your grade for course 1: 90
Enter your grade for course 2: 90s
Please enter a valid grade.
Enter your grade for course 2: 80
Enter your grade for course 3: 70
Enter your grade for course 4: 60
Enter your grade for course 5: -1
Sara, your average grade for 4 courses this semester is 75.0. Well done!
My progress
count=0
sum=0
name = input("Enter your name: ")
while name.isalpha()==False:
print("Please enter a valid name.")
name = input("Enter your name: ")
grade = int(input("Enter your grade for course "+ str(count+1)+": "))
grade == 1
while grade!=-1:
grade = str(grade)
while grade.isnumeric()==False:
print("Please enter a valid grade.")
grade = input("Enter your grade for course "+ str(count+1)+": ")
grade =int(grade)
count+=1
sum+=grade
grade = int(input("Enter your grade for course "+ str(count+1)+": "))
avg = sum/count
if avg>60:
print(name.capitalize(),", your average grade for",count,"courses this semester is",avg,". Well done!")
else:
print(name.capitalize(),", your average grade for",count,"courses this semester is",avg,". Please do better.")
I get an int error. though I know why I get the error but have no other way to solve this problem. Please help!
You can use try except
Like this:
count=0
sum=0
name = input("Enter your name: ")
while name.isalpha()==False:
print("Please enter a valid name.")
name = input("Enter your name: ")
grade = 1
while grade!=-1:
try:
grade = int(input("Enter your grade for course "+ str(count+1)+": "))
if grade == -1: break
count+=1
sum+=grade
except:
print("Please enter a valid grade.")
avg = sum/count
if avg>60:
print(name.capitalize(),", your average grade for",count,"courses this semester is",avg,". Well done!")
else:
print(name.capitalize(),", your average grade for",count,"courses this semester is",avg,". Please do better.")
I assume you got an int error after entering a non-numeric value as your grade. You convert the grade to an int when you define it without checking if it's a numeric value or not. This will raise an exception, you can avoid it by using try/except or first checking if grade is numeric.
Your while grade.isnumeric()==False: is failing when user enters nothing. It passes through an empty string and in line
grade = int(input("Enter your grade for course "+ str(count+1)+": "))
it tries to evaluate it as int although it can't since its an empty string.
You have several things wrong with this homework assignment.
Here are some suggestions:
Append to a list grades =[] rather than a running grade that is initialized with a '1'. You don't want the '1' to be part of your average.
Use a try/except clause to validate the user input.
Compute the average on the list after you exit the while loop.

Adding multiple items to dictionary

def AddStudent():
#Variable to control the loop
again = 'y'
#While loop that gets user input to be added to dictionary
while again.lower() == 'y':
student_key = input("What's the name of the student? ")
#Ask user for number of grades
n = int(input('How many grades do you wish to input? '))
#Empty list where grades will be saved
grades = []
#for loop to add as many grades as user wishes
for i in range(0 ,n):
grade = int(input(f'Grade {i + 1}: '))
grades.append(grade)
#Call StudentGradeBook and send values as parameters
StudentGradeBook(student_key, grades)
again = input('Do you wish to add another student? (y) ')
def StudentGradeBook(name, grade_value):
#Dictionary of the grades
grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
#Add the key and value to the dict
grade_book[name] = grade_value
print(grade_book)
When I add more than one name and grade list to the dict, it just replaces the third one instead of adding a 4th, 5th, etc.
This is the output:
What's the name of the student? Bill
How many grades do you wish to input? 3
Grade 1: 88
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Bill': [88, 88, 88]}
Do you wish to add another student? (y) y
What's the name of the student? Thomas
How many grades do you wish to input? 3
Grade 1: 87
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Thomas': [87, 88, 88]}
Do you wish to add another student? (y) n
I suggest that you save all the inputs in a list, then you pass the list to StudentGradeBook() :
def AddStudent():
# Variable to control the loop
again = 'y'
# Keep track of your inputs
inputs_list = []
# While loop that gets user input to be added to dictionary
while again.lower() == 'y':
student_key = input("What's the name of the student? ")
# Ask user for number of grades
n = int(input('How many grades do you wish to input? '))
# Empty list where grades will be saved
grades = []
# for loop to add as many grades as user wishes
for i in range(0, n):
grade = int(input(f'Grade {i + 1}: '))
grades.append(grade)
# Save the inputs before calling StudentGradeBook
inputs_list.append([student_key, grades])
again = input('Do you wish to add another student? (y) ')
# Call StudentGradeBook and pass the inputs as a list
StudentGradeBook(inputs_list)
def StudentGradeBook(grades):
grade_book = {'Tom': [90, 85, 82], 'Bob': [92, 79, 85]}
grade_book.update(grades)
print(grade_book)
Your StudentGradebook function is always beginning with:
grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
and since it neither returns the resulting modified dict nor stores it elsewhere, it's always restarting from scratch. If you want to preserve a single student gradebook across calls, I'd recommend making it a class, and reusing an instance of said class to add new student info to, e.g. defining it like so:
class StudentGradeBook:
def __init__(self):
# Initial dictionary on creation
self.grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
def add_grades(self, name, grades):
# Update with additional data
self.grade_book[name] = list(grades) # Shallow copy to avoid being tied to caller list
# Optionally, if new grades for an existing student should be allowed,
# replace the line above with:
self.grade_book.setdefault(name, []).extend(grades)
# which will concatenate on new grades for the name rather than replacing all grades
and using it like so:
def AddStudent(gradebook=None): # Allow passing in an existing gradebook
if gradebook is None:
gradebook = StudentGradebook() # Make a new one if it one wasn't provided
#Variable to control the loop
again = 'y'
#While loop that gets user input to be added to dictionary
while again.lower() == 'y':
student_key = input("What's the name of the student? ")
#Ask user for number of grades
n = int(input('How many grades do you wish to input? '))
#Empty list where grades will be saved
grades = []
#for loop to add as many grades as user wishes
for i in range(0 ,n):
grade = int(input(f'Grade {i + 1}: '))
grades.append(grade)
#Call StudentGradeBook and send values as parameters
gradebook.add_grades(student_key, grades)
print(gradebook.grade_book) # Print the state so far
again = input('Do you wish to add another student? (y) ')
return gradebook # So caller can use it if they didn't already provide one
Every time you call StudentGradeBook you are redefining grade_book from scratch as
grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
Just move it outside of both function body and it will work.
def AddStudent():
...
#Dictionary of the grades
grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
def StudentGradeBook(name, grade_value):
#Add the key and value to the dict
grade_book[name] = grade_value
print(grade_book)
You can also pass grade_book to keyword arguments in function as default value:
def StudentGradeBook(name, grade_value, grade_book={'Tom': [90, 85, 82], 'Bob': [92, 79, 85]}):
Full code:
def AddStudent():
again = 'y'
while again.lower() == 'y':
StudentGradeBook(input("What's the name of the student? "), [int(input(f'Grade {i + 1}: '))
for i in range(int(input('How many grades do you wish to input? ')))])
again = input('Do you wish to add another student? (y) ')
def StudentGradeBook(name, grade_value, grade_book={'Tom': [90, 85, 82], 'Bob': [92, 79, 85]}):
grade_book[name] = grade_value
print(grade_book)
Output:
What's the name of the student? Bill
How many grades do you wish to input? 3
Grade 1: 88
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Bill': [88, 88, 88]}
Do you wish to add another student? (y) y
What's the name of the student? Thomas
How many grades do you wish to input? 3
Grade 1: 87
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Bill': [88, 88, 88], 'Thomas': [87, 88, 88]}
Do you wish to add another student? (y) n

Python judgment that the input value is a null value

I designed a python program
After entering the grades of all students,
Minimum to maximum
I hope to rewrite the program as
When if the input value (score variable) is empty (when nothing is entered)
The program execution ends and the result of print is displayed.
My problem is that I don't know how to write judgment grammar?
When if input input (score variable)
The value is a null value, the program execution ends, and the result of print is displayed.
Program execution effect:
When judging the input (score variable), it is a null value
End the program execution and display the result of print
Please enter the student's grade: 89
Please enter the student's grade: 38
Please enter the student's grade: 49
Please enter the student's grade: 77
Please enter the student's grade: 448
Please enter the student's grade: 38
Please enter the student's grade: 39
Please enter the student's grade:
Grades are sorted from smallest to largest: [448 44, 55, 66, 88, 97, 22]
My code
score=int(input("Please enter the student's score:"))
mes = list()
for i in range(1,8):
score=int(input("Please enter the student's score:"))
mes.sort()
mes.append(score)
print("Grades are sorted from smallest to largest", str(mes))
Hope can ask for help, thank you all
I think this is what your are looking for.
score = 0
grades = []
while score != "":
score = input("Please enter the student's score:")
if score != "":
grades.append(score)
grades = sorted(grades)
print(f"Grades are sorted from smallest to largest: {grades}")

how to list out all the keys and values from users' input in python

I get stuck on the homework for the following question:
Create a program that paris a student's name to his class guide. The user should be able to enter as many students as needed and then get a printout of all the students' names and grades. The output should look like this:
Please give me the name of the student (q to quit):[INPUT]
Please give me their grade (q to quit): [INPUT]
[And so on...]
Please give me the name of the student (q to quit): > q
Okay, printing grades!
Student Grade
Student1 A
Student2 D
Student3 B
Student4 A
Here is what I have done so far:
def my_dict():
while True:
name=input("Please give me the name of the student (q to quit):")
grade=input("Please give me their grade:")
my_dict[name]=grade
if name=='q':
break
print("Ok, printing grades!")
print("Student\t\tGrade")
for name, grade in my_dict.items():
print("name: {}, grade: {}'.format(name, grade))
I know it is not right but I don't know how to pair the name and grade and how to print out all the keys and values from user input. Please let me know if you are willing to help out! Much appreciate
There are several issues here, one is a syntax error as #khelwood noted in the comments, the other one is that my_dict is both a function and (apparently) a non-defined dictionary.
I also break before adding to the dictionary, otherwise you'll end up with 'q' as a name in the dictionary (and the user having to input a grade of student "q").
You can define a local dictionary in the function and then return it, for example:
def get_dict_from_user():
user_input = {}
while True:
name = input("Please give me the name of the student (q to quit):")
if name == 'q':
break
# It is not clear if 'grade' means a letter grade (A-F) or a numerical grade (0-100).
# If you want numerical grade it may be better to do convert to int so you can do
# calculations, such as finding the average
grade = input("Please give me their grade:")
user_input[name] = grade
return user_input
grades_dict = get_dict_from_user()
print("Ok, printing grades!")
print("Student\t\tGrade")
for name, grade in grades_dict.items():
print('name: {}, grade: {}'.format(name, grade))

Create a two dimensional list of ids and corresponding values from user input

I need a two dimensional list to store information about students and their grades.
When I run my program I just get one list of the numbers but I need separate lists for each student. Can anyone help me?
This is what I've done so far:
COLS= int(input("number of students to enter "))
ROWS= int(input("number of grades per student "))
def main():
number =[]
for c in range(COLS):
student =(input("enter student ID number "))
number.append(student)
for r in range (ROWS):
grades =(input("Enter grade for module: "))
number.append(grades)
print(number)
my result is
number of students to enter 2
number of grades per student 4
enter student ID number 1234
Enter grade for module: 55
Enter grade for module: 66
Enter grade for module: 43
Enter grade for module: 33
enter student ID number 2345
Enter grade for module: 34
Enter grade for module: 56
Enter grade for module: 78
Enter grade for module: 99
['1234', '55', '66', '43', '33', '2345', '34', '56', '78', '99']
>>>
You need to create a new list for each row:
for c in range(COLS):
grades = []
student =(input("enter student ID number "))
number.append(student)
number.append(grades)
for r in range (ROWS):
grade =(input("Enter grade for module: "))
grades.append(grade)
I would use a dictionary indexed by student id:
COLS= int(input("number of students to enter "))
ROWS= int(input("number of grades per student "))
def main():
student_grades = {}
for c in range(COLS):
student =(input("enter student ID number "))
grades = []
for r in range (ROWS):
grade =(input("Enter grade for module: "))
grades.append(grade)
student_grades[student] = grades
As per my comment, an example of doing this with list & dict comprehensions:
cols = int(input("Number of students: "))
rows = int(input("Number of grades per student: "))
grades = {input("Enter student ID number: "):
[input("Enter grade for module: ") for _ in range(rows)]
for _ in range(cols)}
Note this is a dictionary as in Kyle Strand's answer, rather than a list. This suits the data better, and will make working with it later easier.
As another note, a better interface could be achieved by repeating this until the user decides not to enter more students, rather than asking up-front how many students will be entered:
rows = int(input("Number of grades per student: "))
def get_students():
while True:
value = input("Enter student ID number, or nothing to finish: ")
if not vale:
return
else:
yield value
grades = {student: [input("Enter grade for module: ") for _ in range(rows)]
for student in get_students()}
Here this is achieved with a generator, which yields new student numbers obtained from the user until the user enters nothing.
Just build a list before you insert it into the number list:
for c in range(COLS):
student =(input("enter student ID number "))
temp_arr = [student] # make a temporary array for the student id and their grades
for r in range (ROWS):
grades =(input("Enter grade for module: "))
temp.append(grades) # append to the temp array here
# after you are done getting the grades
# insert the entire temp array into the number array
number.append(temp)
Also, this data would probably be stored in a better fashion if you made a class Student, which could have an id and a list of grades.
I think it would better to use a dictionary of lists instead of a two dimensional list -- a list of lists -- because it makes access to data for both input and access later easier and readable. For those same reasons I also changed its name from number in your code to grades in the code below to better reflect what is being put into it.
COLS = int(input("number of students: "))
ROWS = int(input("number of grades per student: "))
grades = {}
def main():
for c in range(COLS):
student = int(input("enter student ID: "))
grades[student] = [] # initialize to empty row of grades
for r in range(ROWS):
grade = int(input("Enter grade for module: "))
grades[student].append(grade)
for student in grades.keys():
print 'student:{}, grades:{}'.format(student, grades[student])
Output after inputting your sample data:
student:2345, grades:[34, 56, 78, 99]
student:1234, grades:[55, 66, 43, 33]

Categories