Python Forum

Full Version: exception in side if clause
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am trying to raise an exception if the no is not in tuple. Where do I include the exception. Tried different ways. Getting indentation error if I put it before else. Now it does not go to the exception at all.

t = (2,3,4)

Ask = int(input("Enter a no:  "))

try:
    if Ask in t:
       print("Valid No")
   
    else:
        print("Not valid")
        print("Enter Again:")
except ValueError as e:
    print(e)
#else:
#    print("Enter Again:")
Well, right off the bat, t is not a tuple, it's a list.

As to why you don't get an error, between if and else, you have everything covered. It's in there or it's not.

This page might be of help to you:
https://www.w3schools.com/python/python_try_except.asp
(Feb-13-2020, 06:07 AM)michael1789 Wrote: [ -> ]Well, right off the bat, t is not a tuple, it's a list.
Actually, it is indeed tuple
>>> t = (1, 2, 3)
>>> type(t)
<class 'tuple'>
As to OP question - you want to raise exception if Ask is not in tuple t, but what you are doing is actually try to catch a ValueError (that in fact will never come out of the code that is inside the try block).
ValueError may come from trying to convert user input to int.
try:
#    def entr(n = int(input("Enter a no:  "))):
    Ask = int(input("Enter a no:  "))

    t = (2,3,4)
    if Ask in t:
        print("Valid No")
   
    else:
        print("Not valid")
        print("Enter Again:")
        raise ValueError
#        Ask = int(input("Enter a no:  "))
except Exception as e:
    print("The no is not in Tuple",e,Ask)
I am successful in checking whether the no entered is in the tuple. If not it raise exception. Up to that point OK.
Now I want to prompt the user to enter another no. How do I run line 6 and ask the user to enter again.

Thanks
Do you know about loops?
completed loops exercises. But where to start any hint.
Thanks
What have you thought about?