Skip to content
Advertisement

Why i am unable to use (or) operator on the code given below in python 3.7 [duplicate]

try:
    x = int(input("Enter Your Number first = ")) or  float(input("Enter Your Number first = "))
    y = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))

except:
    print("Error,Invalid Input")

I know I am wrong, I was just wondering why I am unable to use it. As I am not getting any errors. When I try to put float value inside the input it returns me to my second case, which is Error, Invalid Input. I am using (or) operator so that I can validate integer and float values in one place. (or) the operator should execute the code when one of the conditions is true right? But why cannot we use Or operator with an integer? The code will work if you remove int from the code.

Advertisement

Answer

While you can use the or operator to select the the first truthy value between to values (or the latter, if the first one is falsy), it doesn’t work in this case because trying to convert into int a string which represents a float value doesn’t return a falsy value, it raises an Exception, which is why you go into your except clause

A logically sound way to write your code would be

 x = input("Enter Your Number first = ")
 try:
     num = int(x)
 except:
     num = float(x)

Not the best way to do it, but it works

Another example:

x = 10/0 or 3 #ZeroDivisionError
x = 0/10 or 3 # x is 3 because 0 is a falsy value

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement