Issue
I've written a program which repeatedly reads numbers until the
user enters "done"
. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.
The problem is the code never gets to the except
part of the code (user should get an error for not entering anything or for entering invalid characters (anything not 'done'
or a number).
What am I doing wrong?
numbers=(input("Enter a number or 'done' to quit: "))
count=1
total_num=int(numbers)
while True:
numbers=(input("Enter another number or 'done' to quit: "))
try:
if (numbers.isalpha() and numbers=='done'): #elif numbers.isalpha() and numbers=='done':
break
elif numbers.isdigit():
numbers=int(numbers)
total_num+=int(numbers)
count+=1
except:
print('Valid a number or done to quit:' )
print('sum is', total_num)
print('count is', count)
print('average is', int(total_num/count))
Solution
You've misunderstood the point of the try..except
block. You don't need to check if the input isdigit
, since that precludes any errors from being thrown. Just try to convert the input to int
, and if this fails, you'll fall through to the except
. There, you can check if the input is == "done"
, and break out:
while True:
numbers = input("Enter another number or 'done' to quit: ")
try:
numbers = int(numbers)
total_num += numbers
count += 1
except ValueError:
if numbers == "done": break
print('Valid a number or done to quit:' )
Note that I qualified the except
clause to only catch ValueError
s, since it is a bad practice to catch all errors -- that can hide actual problems with your code, and disable the ability to interrupt the program with Ctrl+C
Answered By - Pranav Hosangadi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.