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?
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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.