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.
Solution 1:
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: >? 1010is ineger
x = input("Enter a number: ")
Enter a number: >? 10.010.0isfloat
x = input("Enter a number: ")
Enter a number: >? Ten
Ten is string
Solution 2:
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
Solution 3:
You can use:
defget_type(x):
' Detects type 'if x.isnumeric():
returnint# only digitselif x.replace('.', '', 1).isnumeric():
returnfloat# single decimalelse:
returnNone# 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: 1010is an integer
Enter a number: 10.10.is a float
Enter a number: 10.5.310.5.3is a string
Post a Comment for "How To Print The Input As An Integer, Float Or String In Python"