Python Forum
exception in side if clause - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: exception in side if clause (/thread-24416.html)



exception in side if clause - sbabu - Feb-13-2020

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:")



RE: exception in side if clause - michael1789 - Feb-13-2020

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


RE: exception in side if clause - buran - Feb-13-2020

(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.


RE: exception in side if clause - sbabu - Feb-14-2020

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


RE: exception in side if clause - ndc85430 - Feb-14-2020

Do you know about loops?


RE: exception in side if clause - sbabu - Feb-15-2020

completed loops exercises. But where to start any hint.
Thanks


RE: exception in side if clause - ndc85430 - Feb-15-2020

What have you thought about?