Hello, I'm a student learning Python.
I am writing a program that calculates the average by receiving a score from the user.
If you add a positive number as user_input, you add it to the list, and if you add a negative number, you get the sum and the average based on the list.
To calculate while there is no content in the list, use exception Zero Division Error:
to receive the input value again.
If you enter non-numeric characters in user_input, you are trying to receive the input value again using exceptionValueError:
.
Below is what we were working on.
def calculate_average(listsum, count):
average = sum(listsum) / count
return average
score = list()
try:
user_input = int(input(') score. Enter a negative number to obtain the mean: ')))
except ValueError:
print('Not a valid number. Please re-enter it.')
user_input = int(input(') score. Enter a negative number to obtain the mean: ')))
except ZeroDivisionError:
print('You did not enter a score to obtain the mean. Please re-enter it.')
user_input = int(input(') score. Enter a negative number to obtain the mean: ')))
finally:
while user_input >= 0:
score.append(user_input)
user_input = int(input(') score. Enter a negative number to obtain the mean: ')))
if user_input < 0:
average = calculate_average(score, len(score))
print('sum:', '%'.1f' % sum(score))
print('Average:', '%'.1f' % average)
The cord seems to be unnecessarily messy..
Once I just enter a positive number and then a negative number, the sum and the average I want are normally output.
However, whenever I try to make an exception, it keeps not working.
I think the order or usage of the placement is wrong
Can I ask for advice from masters? Thank you.
And one of the contents that was modified was
def decision():
try:
score_input = int(input(') score. Enter a negative number to obtain the mean: ')))
except ValueError:
print('Not a valid number. Please re-enter it.')
decision()
There was also a way to create and use functions like this, but I think it's a little too much for my head right now. Please do it again ㅠ<
python3.4 try exception
In Python try catch, final is the part that goes unconditionally regardless of whether a value error or division by zero is caught, that is, if a value other than a number, 0 goes in, the error comes out normally, and then the error goes in the final.
917 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
620 Uncaught (inpromise) Error on Electron: An object could not be cloned
574 Who developed the "avformat-59.dll" that comes with FFmpeg?
© 2024 OneMinuteCode. All rights reserved.