Python judgment that the input value is a null value - python

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}")

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.

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

using %s, %d to assign pass/fail to grade determination based on user input score (python)

desired outcome:
Enter a test score (-99 to exit): 55
Enter a test score (-99 to exit): 77
Enter a test score (-99 to exit): 88
Enter a test score (-99 to exit): 24
Enter a test score (-99 to exit): 45
Enter a test score (-99 to exit): -99
55 77 88 24 45
P P P F F
Process finished with exit code 0
The code so far: (works except for Pass fail assignment)
Python Program to ask user to input scores that are added to a list called scores. Then prints under that score P for Pass F for fail.
scores = [] #list is initialized
while True:
score = int(input("Enter a test score (-99 to exit): "))
if score == -99:
break
scores.append(score)
def print_scores(): #accepts the list and prints each score separated by a space
for item in scores:
print(item, end = " ") # or 'print item,'
print_scores() # print output
def set_grades(): #function determines whether pass or fail
for grade in scores:
if score >= 50:
print("P")
else:
print("F")
print(set_grades)
You're thinking along the right lines, but you need to run through your program from the top and make sure that you're getting your reasoning right.
Firstly, you've written the program to print out all the scores before you get to checking if they're passes, so you'll get a list of numbers and then a list of P/F. These need to happen together to display properly.
Also, make sure that you keep track of what variable is what; in your last function, you attempt to use 'score', which doesn't exist anymore.
Finally, I'm not sure what exactly you're asking with %d or %s, but you may be looking for named arguments with format(), which are shown below.
scores = [] #list is initialized
while True:
score = int(input("Enter a test score (-99 to exit): "))
if score == -99:
break
scores.append(score)
for item in scores:
if item >= 50:
mark = 'P'
else:
mark = 'F'
print('{0} {1}'.format(item, mark))
I believe this is what you're looking for.

User input repeatedly error

I am trying to create a simple program that initializes a list for the grades to be entered by the user and adds grades to the grade list. Also I want my user to be able to repeatedly prompt grades to the list until the user enters a blank grade. My problem is my code does not stop when a blank input is placed by the user.
Here is my initial code:
grade_list=[]
valid_input=True
while valid_input:
grade= input ("Enter your grade:")
grade_list.append(grade)
else:
valid_input= false
print(grade_list)
grade_list = []
while True:
grade = input('Enter your grade: ')
if not grade:
break
grade_list.append(grade)
print(grade_list)
Two problems:
(1) You never change the value of valid_input: you cannot get to the "else" branch.
(2) You don't do anything in the "true" branch to check the input.
You can get rid of the variable and simplify the loop: just grab the first input before the loop, and then control the loop by directly checking the input. This is the "old-school" way to run a top-checking loop.
grade_list = []
grade = input ("Enter your grade:")
while grade:
grade = input ("Enter your grade:")
grade_list.append(grade)

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}

Categories