Checking for an exception and other values in an if statement - python

Let's say I want to check the avarage of 2 test scores. I don't want the user to input any letters or a value less than 0.
What comes to my mind is this code:
while True:
try:
score1 = float(input('Enter the your 1st score: '))
score2 = float(input('Enter the your 2nd score: '))
except:
print('Invalid value, try again...')
continue
if (score1 < 0 or score2 < 0):
print('Invalid value, try again...')
continue
print(f'Your average is {(score1 + score2) / 2}')
break
Is there a way to check for an exception and if a score is less than 0 in the same if statement?

This is not very efficient; but you can do this after loading score2 in the try:
score2 = float(input('Enter the your 2nd score: '))
assert score1 >= 0 and score2 >= 0
except:
...
and get rid of the if statement.

In Python, the way to check for an exception is by using a try:except: block, not by using an 'if' statement.
So the answer to this question:
"Is there a way of checking for an exception with an 'if' statement?" is "no."
Your question was a little different. You asked whether you could (1) check for an exception and (2) evaluate another expression "in the same 'if' statement." Since you can't even do the first thing in an 'if' statement, you clearly can't do both.

Related

How do I limit inputs to only be Specific multiples in Python?

Currently doing a college assignment where we need to input and add 3 different scores.
The Scores must be not be less than 0 or greater than 10, and they can only be in multiples of 0.5. It's the latter part I'm having trouble with.
How do I tell the program to give an error if the input isn't a multiple of 0.5?
score1 = float(input("Please input the first score: ")
if score1 <0 or score1 >10:
score1 = float(input("Error! Scores can only be between 0 and 10.\n Please input Score 1 again: "))
elif score1
One way to do this is to use a while loop:
score1 = float(input("Please input the first score: ")
# while loop will keep asking for correct input if the input does not satisfy the requirements
while score1 <0 or score1 >10 or not (score1%0.5)== 0.0:
score1 = float(input("Error! Scores can only be between 0 and 10 and in multiples of 0.5.\n Please input Score 1 again: ")
print(score1, "passes all the tests")
or alternatively, you could raise an error statement if you'd like:
score1 = float(input("score: "))
if score1<0 or score1>10 or not (score1%0.5)==0.0:
raise BaseException("Error! the input score1 must be between 1 and 10 and a multiple of 0.5")
print(score1, "passes all the tests")
Nested if statement comes into play here. First it will check the condn is score>0 and score<10 then the next if statement of checking multiple statement comes to play. Use loop for taking input back to back until condn not met.
score = float(input("Enter score"))
if score>0 and score<10:
if (score*10)%5 == 0:
print(" Score is a Multiple of 0.5")
else:
print("Score is Not multiple of 0.5")
else:
print("Error! Scores can only be between 0 and 10")
`

Keep asking for numbers and find the average when user enters -1

number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)

What is causing the syntax error in this loop?

I am trying to create a loop if a negative number is entered to prompt the user to re-enter a valid rating, but I keep receiving a syntax error can someone help point out which part does not look right. I am new to this so it's going over my head. Thanks in advance.
def detailLoop():
global numOfStars
if (rating >4):
print ("Out of range. ")
rating = float(input("Enter a star rating or a negative number to quit: ")
elif (numOfStars >= lowestRating) and (numOfStars <= maxRating):
rating=rating+numOfStars
count=count+1
# If Negative Value Is Entered
else: (numOfStars<0):
print("End of Program")
return
Ignoring your indentation, your problem is probably with your else statement. You don't have to specify a condition after the else statement. So it should either be
else:
print("End of Program")
or
elif numOfStars < 0:
print("End of Program")
and as #Klaus has pointed out you're also missing a ) at the end of your input line
rating = float(input("Enter a star rating or a negative number to quit: "))

Invalid Syntax Error - Average Calculator "IF" and "WHILE"

I have no idea what I'm doing wrong, but this is driving me up a wall. Why am I getting a Syntax error? I have to code an average calculator using a while statement, where "0" defines that the program needs to perform the calculation.
Here's the sample output my professor defined:
SAMPLE RUN
Enter test score 80
Enter test score 70
Enter test score 90
Enter test score 88
Enter test score 0
The average is 82.000%
The if statement in the image (please post the actual code in your question) is invalid. It needs a colon, i.e. if test == '0':. It also needs a body.
The sample output suggests that 0 is to terminate the loop. Check for that first, before you modify division_integer otherwise the average will be affected. Then, when you get a 0 break out of the while loop with break, i.e.
while True:
test = int(input('Enter test score:'))
if test == 0:
break
addition_integer += test
division_integer += 1
Note that you are converting the input into an integer, but your test was for the string "0". You need to test for the integer 0 as I show above.
Another point, you should use a try/except block when converting the input into an integer so that you can catch invalid input:
while True:
try:
test = int(input('Enter test score:'))
except ValueError:
print('Invalid number entered, try again.')
continue
# etc.
I've fixed your code for you. For future questions, please post your code directly in your question and indent it all by 4 spaces to properly format it.
addition_integer = 0
divison_integer = 0
while True:
test = int(input("Enter test score: "))
if test == 0:
break
else:
addition_integer += test
divison_integer += 1
print("The average is {}%".format(addition_integer/divison_integer))
Here's an explanation of what I did to fix this:
You were looping while True, which is correct, however you had no way to break out of the while loop. Your line saying if test == '0' would never resolve to true because you're taking the input as an int from the user, not to mention it was out of place and didn't have proper syntax.. What I am doing in the code above is continuing to loop until the input from the user is equal to 0 (an integer, not a string). If the user inputs 0, then we simply break out of the loop and print the average. Until then, we continue to add the input to addition_integer and increment division_integer by 1.
All in all, you were pretty close to the solution, you just needed a few syntax changes and to be steered in the right direction as to how you can break out of an infinite loop.
Finally, here is a test using the numbers that you've provided in your question:
Enter test score: 80
Enter test score: 70
Enter test score: 90
Enter test score: 88
Enter test score: 0
The average is 82%
Alternative answer
Use a list, sum and divide. Same concept, compare test inside the while loop in order to break out of it. Also check if you get valid input that can be made an integer with a try/except.
Additionally, beware of the division by zero
values = []
while True:
try:
test = int(input('Enter test score:'))
if test == 0:
break
values.append(test)
except:
break
total = len(values)
avg = 0 if total == 0 else 1.0 * sum(values) / total
print("The average is", avg)

Cant get str to work in if-loop Python 3

I wrote a grade calculator where you put a float in and get a grade based on what you scored. The problem I have is that I belive I need a float(input... But that becomes an error if you write letters in the box...
def scoreGrade():
"""
Determine the grade from a score
"""
gradeA = "A"
gradeB = "B"
gradeC = "C"
gradeD = "D"
gradeF = "F"
score = float(input("Please write the score you got on the test, 0-10: "))
if score >= 9:
print("You did really good, your grade is:", gradeA, ". Congratulations")
elif score >= 7:
print("Your results are good. They earn you a:", gradeB, ". Better luck next time")
elif score >= 5:
print("Not too bad. You got a:", gradeC)
elif score >= 4:
print("That was close...:", gradeD)
elif score < 4:
print("You need to step up and take the test again:", gradeF)
else:
print("Grow up and write your score between 0 and 10")
Is there a way to get rid of the float and print the last statement if you write something else that the score from 0-10?
Something like this:
score = None
while score is None:
try:
score = float(input("Please write the score you got on the test, 0-10: "))
except ValueError:
continue
Keep on asking until the float cast works without raising the ValueError exception.
You could do
try:
score = float(input("Please write the score you got on the test, 0-10: "))
except ValueError:
print("Grow up and write your score between 0 and 10")
scoreGrade()
I would suggest to use EAFP approach and separate handling good and bad inputs.
score_as_string = input("Please write the score you got on the test, 0-10: ")
try:
score_as_number = float(score_as_string)
except ValueError:
# handle error
else:
print_grade(score_as_number)
def print_grade(score):
"""
Determine the grade from a score
"""
gradeA = "A"
gradeB = "B"
gradeC = "C"
gradeD = "D"
gradeF = "F"
if score >= 9:
print("You did really good, your grade is:", gradeA, ". Congratulations")
elif score >= 7:
print("Your results are good. They earn you a:", gradeB, ". Better luck next time")
elif score >= 5:
print("Not too bad. You got a:", gradeC)
elif score >= 4:
print("That was close...:", gradeD)
elif score < 4:
print("You need to step up and take the test again:", gradeF)
else:
print("Grow up and write your score between 0 and 10")
Note that typically you want to return from functions, not print inside them. Using function output as part of print statement is detail, and function does not have to know that.

Categories