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

3
  • Does this answer your question? How do I check if a string represents a number (float or int)? Commented Nov 21, 2022 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: Commented Nov 21, 2022 at 20:50
  • What do you mean by "float"? What about 2, or 17/51 or 2pi? Is `Decimal("0.3") considered a float? Commented Nov 21, 2022 at 21:01

3 Answers 3

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 ')
Sign up to request clarification or add additional context in comments.

Comments

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.)

1 Comment

Which is normally spelt isinstance()
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() 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.