Tim
Tim

Reputation: 13

While loop to identify integer in Python

I'm trying to write a program to calculate densities, and I have tried to create a while loop the prevents the user from entering nothing or a non-number for the volume.

But when I run the program the it just loops "You have to type a value" forever. I've tried the same code in a for loop and it does work after inputing 2 numbers.

def GetVolume():
    print("How many cublic cm of water does the item displace")
    Volume = input()
    while Volume == ("") or type(Volume) != int:
        print("You have to type a value")
        Volume = input()
    return float(Volume)

Upvotes: 0

Views: 14538

Answers (3)

idjaw
idjaw

Reputation: 26600

This solution is written assuming you are using Python 3. The problem in your code is that you are assuming that if you type in a number, the input method will return a type int. This is incorrect. You will always get a string back from your input.

Furthermore, if you try to cast int around your input to force an int, your code will raise if you enter a string, with:

ValueError: invalid literal for int() with base 10:

So, what I suggest you do to make your implementation easier is to make use of try/exceptinstead to attempt to convert your value to a float. If it does not work, you prompt the user to keep entering a value until they do. Then you simply break your loop and return your number, type casted to a float.

Furthermore, because of the use of the try/except, you no longer need to put in a conditional check in your while loop. You simply can set your loop to while True and then break once you have satisfied your condition in your code.

Observe the code below re-written with what I mentioned above:

def GetVolume():
    print("How many cublic cm of water does the item displace")
    Volume = input()
    while True:
        try:
            Volume = float(Volume)
            break
        except:
            print("You have to type a value")
            Volume = input()
    return Volume

Upvotes: 2

Jean Guzman
Jean Guzman

Reputation: 2232

You have to modify your while because is validating that is str or different than int. An input will always be an str by default unless you modified the type with int() or float() in your case.

You can use 'try' instead to check for this:

while True:
    x = input("How many cubic cm of water does the item displace")

    try:
        x = float(x)
        break

    except ValueError:
        pass

print('out of loop')

Upvotes: 0

FFF
FFF

Reputation: 791

def GetVolume():
    Volume = input("How many cublic cm of water does the item displace")

    while not Volume.replace('.', '').replace(',', '').isdigit():
        Volume = input("You have to type a value")
    return float(Volume)

x = GetVolume()
print(x)

Upvotes: 0

Related Questions