How to know if a number is an integer or a float? And how to assign a type to a value inserted in the input function

Asked

Viewed 873 times

0

I have the following problem:

Make a program that takes any two numbers (integers or real) and print on the screen the integers that are in the range understood by them.

And I made the following solution:

  n1 = int(input("Digite um valor:"))
  n2 = int(input("Digite um valor:"))

  for i in range(n1,n2):
      f(i == int(i)):
          print(i)

But I have some problems:

  1. How can I make the function input take values of only 2 types? In the whole case or float.
  2. How to validate if a certain number is real or integer? I tried by type but don’t know if there is another way
  3. How to do the range take into account the final number of the interval?

2 answers

4

In fact you do not need to check whether it is whole or float. Just use float(input(...)), which also accepts strings containing integers, so you convert what was typed to a number.

I suggest we capture the ValueError, if a number has not been entered. For ease, create a function that reads the number and already returns the value set to the range:

def ler_numero(mensagem):
    while True:
        try:
            f = float(input(mensagem))
            n = int(f)
            if f == n:
                return n
            else:
                return n + 1
        except ValueError:
            print('Digite um número válido')

This function asks for a number to be entered, and if an error occurs (i.e., a number has not been entered), it asks to be typed again.

If the conversion to float Alright, I return an integer, taking into account if the decimal part is zero (if it is 4.0, for example, then I return 4, and if it is 4.1, 4.2, etc, I return 5). For that I use int(), that rounds the float down (in case of positive numbers - for negative values, see below).

I make these adjustments because a range only accepts whole.

So now just ask to enter the numbers and print the range:

inicio = ler_numero('Digite o valor inicial:')
fim = ler_numero('Digite o valor final:')

for i in range(inicio, fim):
    print(i)

It is unclear whether the final value should be included (if the final value is 4.0, should you print 4 or not? ). The above code does not. If you want to consider yes, you should always add 1 after converting to integer (but only for the final value, since the initial is included).

Another detail is that the code above does not work for negative numbers as int(-3.5) results in -3 and when adding 1, the beginning would be -2 (i.e., the -3 would be left out of the range).

Then just change the function to use math.floor, rounding down (math.floor(-3.5) results in -4, and when adding 1, the beginning is -3, including him in the range):

import math

def ler_numero(mensagem):
    while True:
        try:
            f = float(input(mensagem))
            n = math.floor(f)
            if f == n:
                return n
            else:
                return n + 1
        except ValueError:
            print('Digite um número válido')

And when reading the numbers, you can also include a validation to check if the initial value is less than the final value (otherwise it makes no sense to proceed):

while True:
    inicio = ler_numero('Digite o valor inicial:')
    fim = ler_numero('Digite o valor final:')
    if fim <= inicio:
        print('Valor final deve ser maior que o inicial')
    else:
        break # valores corretos, sai do loop

for i in range(inicio, fim):
    print(i)

-2

Really the way the hkotsubo said it is better, more practical and more pythonic. But just for registration title: Yes, it is possible to check if a number is float and you can do this in different ways. Some of them:

By the method isinstance():

x = 9.2
print(isinstance(x, int))
>>false
print(isinstance(x, float))
>>true

Or even with the function type():

x = 9.2
print(type(x))
>><class 'float'>
  • 2

    But that’s only when you already own the object of these types. The question is to identify the guy coming by input, that always returns a string. There’s a question here at Sopt that deals with it, I’ll see if I find.

  • The title of the question is "How to know if a number is an integer or a float", so I guess my answer is not so far off. Besides I think it might serve what he proposes

  • 1

    But you must not answer the title but the question. isinstance is of no use in this case, because input always returns str then it will never be float nor int; Your answer only serves to further confuse the beginner.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.