Python Forum
How to properly catch this exception
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to properly catch this exception
#1
I wanted to write a little code that takes in a number. If the number is within a specified range, 0.0 to 1.0, no exception is thrown. But if it is outside the range, the program should prompt the user to input another number. I don't seem to be getting the prompting right when the exception happens. Instead of prompting the user for a new number, the code just fails. Please can anyone tell me what is wrong? The code is below.
Score = input('enter number between 0 and 1\n')
try : 
    Score = float(Score)
    if Score >= 0.0 and Score <=1.0 :
        print('correct number')
except:
    print('enter correct number')
Reply
#2
The way you use except is wrong - The except block lets you handle the error. So for example
try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")
Here, the variable x is not defined, and therefore, a Nameerror will come like
Error:
Variable x not defined
like that
here, even if the input is greater than 1, an error will not come.
You will have to use a while loop like
while Score > 1:
    Score = input('enter number between 0 and 1\n')
Then print your rest of the code. The while loop will work as long as your score is greater than 1. When it becomes less than 1, it will automatically break
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#3
Thanks. Am going back to the code to implement your suggestion.
Reply
#4
Couple of suggestions:
1. use while True: and break to exit the loop when valid inpu
2. Don't use all-catching except. Be specific - in this case you want to catch ValueError, so say so
3. What happens if input is number but outside of the desired range? No error is raised, but you can display respective message. If input is number and inside the range - just break out of the loop
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Thanks everyone. I finally did it. So happy.
score = 0
while True : 
    score = input('number btw 0 and 1\n')
    try :
    	score = float(score)
    	if score>=0 and score<=1:
    		break
    except :
    	print('not number')
    
Reply
#6
To improve readability one can also write:

if 0 <= score <= 1:
...and all-catching except is still bad.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
I have not gotten a firm hold on the except yet. Next time I will specify it. Thanks
Reply
#8
This may get you closer
while True : 
    score = input('number btw 0 and 1\n')
    try :
        score = float(score)
        if score<=0 or score>=1:
            raise ValueError
    except ValueError:
        print('not number, at least not in range')
The part we haven't answered is how to raise an error. This is how. With it you will get an error to trigger the except block whether the person enters "5" or "a".
Reply
#9
(May-26-2020, 09:00 PM)jefsummers Wrote: This may get you closer
while True : 
    score = input('number btw 0 and 1\n')
    try :
        score = float(score)
        if score<=0 or score>=1:
            raise ValueError
    except ValueError:
        print('not number, at least not in range')
The part we haven't answered is how to raise an error. This is how. With it you will get an error to trigger the except block whether the person enters "5" or "a".

I think this is elegant. This wraps up everything. Thanks
Reply
#10
It's better to be specific as to what problem is
while True : 
    score = input('Number between 0 and 1\n')
    try :
        score = float(score)
        if 0 <= score <= 1:
            break
        else:
            print('Number must be between 0 and 1, inclusive. Please try again...') 
    except ValueError:
        print('Not a number. Please try again...')

print(f'You entered: {score}')
Now, if you want to go a step further you can put [part of] this code in a function that takes start and or end argument, ask user for input, validates it and returns the number once correct input.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020