vendredi 7 mai 2021

How to print the input as an integer, float or string in Python?

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?

Aucun commentaire:

Enregistrer un commentaire