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

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.

Related

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

My code starts yielding illogical answers when a I deal with number bigger than 99

I am trying to write a program that determines a person stage of life, whether the person is a baby, kid, teenager, adult or elder. The program starts with a variable that contains an input() function that allows the user to type in an age so the program can start running.
The issue is that when I type ages higher than 99, the program prompts that the person whose age has been typed in is a baby. So basically, according to the program someone who is 123 years old is a baby, which does not make sense.
age=input("enter the person's age: ")
if age<'2':
print('the person is a baby')
elif age=='2' and age<'4':
print('the person is a toddler')
elif age >='4' and age<'13':
print ('the person is a kid')
elif age>='13' and age<'20':
print('the person is a teenager')
elif age>='20' and age<'65':
print('the person is an adult')
elif age>='65':
print('the person is an elder')
I am wondering if I am making a mistake on my code, although it seems to me pretty straight forward. Anyways, I am guessing there is some theoretical knowledge that I am missing, if that is the case I would appreciate if you folks can shed some light on the whole issue.
What you are essentially doing here is comparing strings which does not translate to the behavior you are seeking. You will need to cast the input as int() first.
If you know the input is guaranteed to be formatted correctly, use:
age = int(input("enter the person's age: "))
However, nobody is perfect so it would be best to wrap in a try-except:
age = input("enter the person's age: ")
try:
age = int(age)
except:
# Handle exception
if age < 2:
# Do something
elif ...
# Do more stuff
You are comparing strings no integers thus '100' is less than '99' as the first and second characters are less.
You need to convert your input to an integer and thenuuse that for the comparisons and then you shall be fine.
You should convert age to an integer and then compare. You are comparing strings, and that gives you weird answers.
Reformatted code:
age_str=input("enter the person's age: ")
try:
age = int(age_str)
except:
print("Invalid Entry. Enter age as a number.")
exit(0)
if age < 2:
print('the person is a baby')
elif age == 2 and age < 4:
print('the person is a toddler')
elif age >= 4 and age < 13:
print('the person is a kid')
elif age >= 13 and age < 20:
print('the person is a teenage r')
elif age >= 20 and age < 65:
print('the person is an adult')
elif age >= 65:
print('the person is an elder')
Code also checks for invalid entries above. If anything other than an integer is entered, it throws an error.

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 functions for multiple inputs [Python]

I'm new to python, taking my first class in it right now, only about 4 weeks in.
The assignment is to calculate test average and display the grade for each test inputted.
Part of the assignment is to use a function to calculate the average as well as deciding what letter grade to be assigned to each score.
As I understand it, functions are supposed to help cut down global variables.
My question is this: how do I condense this code?
I don't know how to use a function for deciding letter grade and then displaying that without creating a global variable for each grade that has been inputted.
If you notice any redundancy in my code, I would appreciate a heads up and a little lesson on how to cut that out. I can already smell the mark downs I will get if I turn this in as is...
def main():
grade1=float(input( "Enter score (0-100):"))
while (grade1 <0 or grade1 >100 ):
if grade1 <0 or grade1 >100:
print("Please enter a valid grade")
grade1=float(input( "Enter score (0-100):"))
grade2=float(input( "Enter score (0-100):"))
while (grade2 <0 or grade2 >100 ):
if grade2 <0 or grade2 >100:
print("Please enter a valid grade")
grade2=float(input( "Enter score (0-100):"))
grade3=float(input( "Enter score (0-100):"))
while (grade3 <0 or grade3 >100 ):
if grade3 <0 or grade3 >100:
print("Please enter a valid grade")
grade3=float(input( "Enter score (0-100):"))
grade4=float(input( "Enter score (0-100):"))
while (grade4 <0 or grade4 >100 ):
if grade4 <0 or grade4 >100:
print("Please enter a valid grade")
grade4=float(input( "Enter score (0-100):"))
grade5=float(input( "Enter score (0-100):"))
while (grade5 <0 or grade5 >100 ):
if grade5 <0 or grade5 >100:
print("Please enter a valid grade")
grade5=float(input( "Enter score (0-100):"))
total=grade1+grade2+grade3+grade4+grade5
testAverage=calcAverage(total)
eachGrade1=determineGrade(grade1)
eachGrade2=determineGrade(grade2)
eachGrade3=determineGrade(grade3)
eachGrade4=determineGrade(grade4)
eachGrade5=determineGrade(grade5)
print("\nTest #1 grade:", (eachGrade1))
print("Test #2 grade:", (eachGrade2))
print("Test #3 grade:", (eachGrade3))
print("Test #4 grade:", (eachGrade4))
print("Test #5 grade:", (eachGrade5))
print("\nTest average:", (testAverage),("%"))
def calcAverage(total):
average=total/5
return average
def determineGrade(grade):
if grade >=90:
return "A"
elif grade >=80:
return "B"
elif grade >=70:
return "C"
elif grade >=60:
return "D"
else:
return "F"
I won't refactor your whole code, but here's a few pointers:
First of all, you need a function to get the user input, let's call it get_score. I won't go into the details here because there's an excellent resource on how to write a function for that here: Asking the user for input until they give a valid response. That function should return a float or integer, so don't forget that input (assuming you are using Python 3) returns a string which you have to cast to int or float manually.
To get a list of n scores, I propose the function:
def get_n_scores(n):
return [get_score() for _ in range(n)]
The stuff in the square brackets is a list comprehension and equivalent to:
scores = []
for _ in range(n):
scores.append(get_score())
Use this code instead if you are not comfortable with the comprehension (don't forget to return result).
The variable name _ is commonly used to indicate a temporary value that is not used (other than for iteration).
You can avoid declaring grade1 ... grade5 by calling all_scores = get_n_scores(5), which will return a list with the user input. Remember that indexing is zero-based, so you'll be able to access all_scores[0] ... all_scores[4].
Instead of hardcoding total, you can just apply the built in sum function: total = sum(all_scores), assuming all_scores holds integers or floats.
Finally, you can determine the grade for each score by applying your function determineGrade to every score in all_scores. Again, you can use a comprehension:
all_grades = [determineGrade(score) for score in all_scores]
or the traditional:
all_grades = []
for score in all_scores:
all_grades.append(determineGrade(score))
The other stuff looks okay, except that in order to print the grade you can just loop over all_grades and print the items. It's up to you if you want to write further functions that wrap a couple of the individual function calls we're making.
In general, always avoid repeating yourself, write a function instead.
I'll write is as below:
def get_grade():
while(True):
grade = float(input("Enter score (0-100):"))
if grade >= 0 and grade <= 100:
return grade
print("Please enter a valid grade!")
def get_average(sum_val, counter):
return sum_val/counter
def determine_grade(grade):
if grade >=90:
return "A"
elif grade >=80:
return "B"
elif grade >=70:
return "C"
elif grade >=60:
return "D"
else:
return "F"
test_num = 5
sum_val = 0
result = {}
for i in range(test_num):
grade = get_grade()
result[i] = determine_grade(grade)
sum_val += grade
for key in result:
print ("Test %d Grade is %s" % (key+1, result[key]))
avg = get_average(sum_val, test_num)
print ("Average is %d" % avg)
Works like this:
>>> ================================ RESTART ================================
>>>
Enter score (0-100):89
Enter score (0-100):34
Enter score (0-100):348
Please enter a valid grade!
Enter score (0-100):34
Enter score (0-100):90
Enter score (0-100):85
Test 1 Grade is B
Test 2 Grade is F
Test 3 Grade is F
Test 4 Grade is A
Test 5 Grade is B
Average is 66
>>>

How to Total a while loop?

Purpose is to put diff ages in, if -1 is entered then the program stops, my totaling statement is wrong. Will Someone please help me fix it.
Totalage = 0
age = 0
print "Enter you Family member's ages!"
age = raw_input ("Enter an age ")
while age != -1:
age = input("Enter an age ")
Totalage = Totalage + age
print Totalage
There are two problems with your code
You are skipping your first input, and you are not adding it to your total
You are adding the last terminator input -1 to your Total.
Just Change the order of the statements in your while loop
age = int(raw_input ("Enter an age "))
while age != -1:
Totalage = Totalage + age
age = int(input("Enter an age "))
Also note, raw_input, in general returns a string, which needs to be converted to int before you may want to calculate on it.
Itertools Provide some wonderful tools, and for fun, I tried coding the above while loop with itertools.takewhile
>>> from itertools import count, takewhile
>>> sum(takewhile(lambda x: x != -1,
(int(raw_input("Enter an age ")) for e in count())))
Enter an age 20
Enter an age 30
Enter an age 40
Enter an age 50
Enter an age -1
140
The problem is that your while condition is working properly, but you don't trigger it until your next run through. Therefore if your input is -1, this:
age = input("Enter an age ")
Totalage = Totalage + age
Will decrement the age by -1 and on the next loop through it will exit the loop. In order to adjust, you could do something like this. Note that one adjustment is changing input to raw_input (usually a better practice in Python 2.x, and Python 3.x changes the behavior of input to match it):
Totalage = 0
print "Enter you Family member's ages!"
while True:
age = int(raw_input("Enter an age "))
if age == -1:
break
Totalage += age
print Totalage
while True puts you into a continuous loop, and you break out of it whenever the value -1 is entered. Also, the int here is what you need to do to convert the number to an integer. This will fail if somebody enters an incorrect value (like 'ten', for instance), so if that is a concern you would have to add some additional error handling.
The problem is that you're adding -1 to Totalage before the loop condition is checked. You could rewrite the loop something like this instead:
print "Enter you Family member's ages!"
Totalage = 0
while True:
age = input("Enter an age ")
if age == -1:
break
Totalage += age
print Totalage

Categories