2

The purpose of my code is for the output to give the number and the type of the input. For instance:

If the input is: 10

The output should be: 10 is an integer

If the input is: 10.0

The output should be: 10.0 is a float

If the input is: Ten

The output should be: Ten is a string

I am quite a beginner with programming so I don't know any "advanced" functions yet. I shouldn't have to use it either because this is a starting school assignment. Normally I should be able to solve this with if, elif and else statements and maybe some int (), float () and type () functions.

x = input("Enter a number: ")

if type(int(x)) == int:
    print( x, " is an integer")
elif type(float(x)) == float:
    print( x, "is a float")
else:
    print(x, "is a string")

However, I keep getting stuck because the input is always given as a string. So I think I should convert this to an integer / float only if I put this in an if, elif, else statements, then logically an error will come up. Does anyone know how I can fix this?

2

3 Answers 3

2

REMEMBER: Easy to ask forgiveness than to ask for permission (EAFP)

You can use try/except:

x = input("Enter a number: ")
try:
    _ = float(x)
    try:
        _ = int(x)
        print(f'{x} is integer')
    except ValueError:
        print(f'{x} is float')
except ValueError:
    print(f'{x} is string')

SAMPLE RUN:

x = input("Enter a number: ")
Enter a number: >? 10
10 is ineger

x = input("Enter a number: ")
Enter a number: >? 10.0
10.0 is float

x = input("Enter a number: ")
Enter a number: >? Ten
Ten is string
Sign up to request clarification or add additional context in comments.

Comments

0

Since it'll always be a string, what you can do is check the format of the string:

Case 1: All characters are numeric (it's int)

Case 2: All numeric characters but have exactly one '.' in between (it's a float)

Everything else: it's a string

Comments

-1

You can use:

def get_type(x):
    ' Detects type '
    if x.isnumeric():
        return int      # only digits
    elif x.replace('.', '', 1).isnumeric():
        return float    # single decimal
    else:
        return None

# Using get_type in OP code
x = input("Enter a number: ")

x_type = get_type(x)
if x_type == int:
    print( x, " is an integer")
elif x_type == float:
    print( x, "is a float")
else:
    print(x, "is a string")

Example Runs

Enter a number: 10
10  is an integer

Enter a number: 10.
10. is a float

Enter a number: 10.5.3
10.5.3 is a string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.