Python Forum
exception in side if clause
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
exception in side if clause
#1
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:")
Reply
#2
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
Reply
#3
(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.
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
#4
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
Reply
#5
Do you know about loops?
Reply
#6
completed loops exercises. But where to start any hint.
Thanks
Reply
#7
What have you thought about?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Seven Segment Display - QUERY on Multi-line side-by-side printing output ajayachander 3 4,824 Mar-13-2020, 07:02 AM
Last Post: ajayachander
  Blank spaces in right side fernando_santiago18 1 1,599 Sep-07-2019, 12:33 PM
Last Post: ThomasL

Forum Jump:

User Panel Messages

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