1

when i am trying to execute the code, the first if condition is work but the elif condition isn't. After the conditional statements, the except condition is working with no problem.

data = input("Type the number: ")
try:
    integer = int(data)
    decimal = float(data)
    if type(integer) == type(int()):
        for x in range(1,11,1):
            print("{} X {} = {}".format(integer,x,(integer*x)))
    elif type(decimal) == type(float()):  
        for x in range(1,11,1):
            print("{} X {} = {}".format(decimal,x,(decimal*x)))
except (TypeError,ValueError):
    print("Please type a number")
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

2 Answers2

0

By reading your code, I believe you're trying to tell if the data the user entered is an integer or not. To do so, refer to this link:

data = input("Type the number: ")
try:
    decimal = float(data) # if data is not the representation of a float, this will raise an error
    if decimal.is_integer():
        integer = int(decimal)
        for x in range(1,11,1):
            print("{} X {} = {}".format(integer,x,(integer*x)))
    else:
        for x in range(1,11,1):
            print("{} X {} = {}".format(decimal,x,(decimal*x)))
except (TypeError,ValueError):
    print("Please type a number")

Another note about your code: int(<anything>) will either throw an error, or return an int. So your first condition is always True

0

You don't need to convert the input to int and float, just to one of them. Since data is str you can use isdigit to check if all the chars are digits and therefor it is int, or not. You also shouldn't compare types with ==, use isinstance

data = input("Type the number: ")

try:
    if data.isdigit():
        number = int(data)
    else:
        number = float(data)

    if isinstance(number, int):
        for x in range(1, 11, 1):
            print("{} X {} = {}".format(number, x, (number * x)))
    elif isinstance(number, float):
        for x in range(1, 11, 1):
            print("{} X {} = {}".format(number, x, (number * x)))
except (TypeError, ValueError):
    print("Please type a number")

If you don't do anything withe the information what is the type, use one loop without check

data = input("Type the number: ")

try:
    if data.isdigit():
        number = int(data)
    else:
        number = float(data)
    for x in range(1, 11, 1):
        print("{} X {} = {}".format(number, x, (number * x)))
except (TypeError, ValueError):
    print("Please type a number")

You can also convert the input straight to float, but the results will look like 246.0 for ints.

Guy
  • 46,488
  • 10
  • 44
  • 88