Home > Back-end >  Python - How to check if user input is a Complex type input
Python - How to check if user input is a Complex type input

Time:11-25

i want to print a message depending on the type of the input but every time i input a complex number, FOR EXAMPLE (5j) it's detected as a string input. How do i solve this please? Thanks.

while True:
    a = input("a ? ")
    if (isinstance(a, complex)):
        print("Valid number, please not Complex!")  
    try:
        a = float(a)
    except ValueError:
        print ('please input a int or float')
        if (type(a)==str):
            print("Valid number, please not String!")
        continue
    if 0.5 <= a <= 100:
        break
    elif 0 <= a < 0.5:
        print ('bigger number, please: 0.5-100')
    elif a < 0:
        print ('positive number, please')
    elif a > 100:
        print ('smaller number, please: 0.5-100')

Example of execution:

a ? 5j
please input a int or float
Valid number, please not String!

i tried doing this :

while True:
    try:
        a = input("a ? ")
        if ('j' in a):
            print("Valid number, please not Complex!")
        a = float(a)
    except ValueError:
        print ('please input a int or float')
        if (type(a)==str and 'j' not in a):
            print("Valid number, please not String!")
        continue
    if 0.5 <= a <= 100:
        break
    elif 0 <= a < 0.5:
        print ('bigger number, please: 0.5-100')
    elif a < 0:
        print ('positive number, please')
    elif a > 100:
        print ('smaller number, please: 0.5-100')

but it's not "Perfect"

CodePudding user response:

You can add the first block of code into try block

Like this -

while True:
    try:
        a = input("a ? ")
        if (isinstance(a, complex)):
            print("Valid number, please not Complex!")  
        a = float(a)
    except ValueError:
        print ('please input a int or float')
        if (type(a)==str):
            print("Valid number, please not String!")
        continue
    if 0.5 <= a <= 100:
        break
    elif 0 <= a < 0.5:
        print ('bigger number, please: 0.5-100')
    elif a < 0:
        print ('positive number, please')
    elif a > 100:
        print ('smaller number, please: 0.5-100')

Is this what you meant?

CodePudding user response:

You can use nested try-except and the inbuilt function complex() instead.
So, your code needs to be like this

while True:
    a = input("a? ")
    try:
        a = float(a)
        if 0.5 <= a <= 100:
            break
        elif 0 <= a < 0.5:
            print ('bigger number, please: 0.5-100')
        elif a < 0:
            print ('positive number, please')
        elif a > 100:
            print ('smaller number, please: 0.5-100')
    except ValueError:
        try:
            a = complex(a)
            print("Valid number, please not Complex!")
        except ValueError:
            print ("Valid number, please not String!")
            continue
  • Related