Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi!
I'm learning Python and I'm stuck already :)

If user inputs for example 8 it should say that number is integer, otherwise, if user inputs 5.62 it will display, that number is float.

Thank you!

What I have tried:

For example, I have tried the following code:
Python
num_a = float(input("Enter first number: "))
if num_a % 10 == 0:
      print(f"Number {num_a} is integer")
else:
      print(f"Number {num_a} is float")
Posted
Updated 9-Dec-20 1:02am

Your code is testing whether the entered number is divisible by 10.

To test whether a number is an integer, try comparing it to its truncated version:
Python
if num_a == math.trunc(num_a):
You'll need to make sure you have import math at the top of your code.

Otherwise, if you have to stick with the modulo operator, test whether the number is divisible by 1 instead of 10:
Python
if num_a % 1 == 0:
 
Share this answer
 
v2
Comments
Zaur Bahramov 9-Dec-20 6:58am    
am yet in the first lesson, and i can't use anything except what we have passed. I thought there's some other way. But we have passed type().
But if I use type() it doesn't identify a number, it says it is a string:
num = input("Input a number: ")
print(type(num))

Output: <class 'str'="">
Richard Deeming 9-Dec-20 7:01am    
If you have to use the modulo operator, then test whether the number is divisible by 1, not 10:
if num_a % 1 == 0:
Zaur Bahramov 9-Dec-20 7:08am    
Great! This is exactly what I needed! Thank you very much!
A simple method would be to read it in as a string and then test if the string contains a decimal indicator. You can then convert it to float or int as appropriate.

Python
number = input("Enter a number: ")
if '.' in number:
    print("Number is a float")
else:
    print("Number is an integer")
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900