0

I currently have this how can I get it so it checks for a float and uses a while loop

def get_float():
    number = input('Input a decimal number ')
    while number != float:
        print('bad input ')
        number = input('Input a decimal number ')
    else:
        return number
        
get_float()
        

right now even if I enter a decimal number it says bad input and asks for another input

Z-0
  • 1
  • 2
  • Does this answer your question? [How do I check if a string represents a number (float or int)?](https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-represents-a-number-float-or-int) – Marcello Zago Nov 21 '22 at 20:42
  • Just to clarify for you why the code isn't working. When you use the `input` function, regardless if one enters a number or a decimal Python treats it as a string. You'd also want to check the type of the number in the while statment by using `while type(number) != float:` – CodeKorn Nov 21 '22 at 20:50
  • What do you mean by "float"? What about 2, or 17/51 or 2pi? Is `Decimal("0.3") considered a float? – 2e0byo Nov 21 '22 at 21:01

3 Answers3

3

Sometimes it's better to ask for forgiveness than permission.

def get_float():
    while True:
        number = input('Input a number ')
        try:
            return float(number)
        except ValueError:
            print('\n bad input\n ')
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
0
number = input('Input a decimal number ')
while number != float:

This is wrong for a few reasons.

First, input() returns a string, so number is a string. It is not a floating point value.

Second, even if number were a proper floating point value, it is not equal to float, because float is a type object.

It seems like you really meant if type(number) != float. (But again, that would always be false here, because number is a string.)

John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

figured it out:

def get_float():
    while True:
        number = input('Input a decimal number ')
        try:
            if "." in number:
                floatnumber = float(number)
                print(floatnumber)
                break
            else:
                print("invalid number")
        except ValueError as err:
            print(err)
                
        
get_float() 

Z-0
  • 1
  • 2