简体   繁体   中英

Run while loop one extra time after condition is met

I am making an area calculator to help me understand the basics of Python, but I want to do some type of validation on it - if a length is less than zero, then ask again. I've managed to do this with the 'validation' code inside the function for the shape (eg inside the 'square' function) but when I put the validation code in a separate function - 'negativeLength,' it doesn't work. This is my code in the separate function:

def negativeLength(whichOne):
    while whichOne < 1:
        whichOne = int(input('Please enter a valid length!'))

When I run this by calling 'negativeLength(Length)' it will ask me for the length again (as it should) but when I enter the positive length, the condition is met and so the actual loop does not run.

I have also tried (after following Emulate a do-while loop in Python? )

def negativeLength(whichOne):
    while True:
        whichOne = int(input('Please enter a valid length!'))
        if whichOne < 1:
            break

... but that doesn't work either.

I've put the parameter as 'whichOne' because the circle's 'length' is called Radius, so I'd call it as negativeLength(Radius) instead of negativeLength(Length) for a square.

So is there any way to make the while loop finish after the 'whichOne = int(input...)'?

Edit: I'm using Python 3.3.3

The code you've written works, as far as it goes. However, it won't actually do anything useful, because whichOne is never returned to the caller of the function. Note that

def f(x):
    x = 2

x = 1
f(x)
print(x)

will print 1, not 2. You want to do something like this:

def negative_length(x):
    while x < 0:
        x = int(input('That was negative. Please input a non-negative length:'))
    return x

x = input('Enter a length:')
x = negative_length(x)

I'm going to assume you're using Python 3. If not, you need to use raw_input() rather than input().

The code that I usually use for this would look like:

def negativeLength():
    user_input = raw_input('Please enter a length greater than 1: ')
    if int(user_input) > 1:
        return user_input
    input_chk = False
    while not input_chk:
        user_input = raw_input('Entry not valid.  Please enter a valid length: ')
        if int(user_input) > 1:
            input_chk = True
    return user_input

Which should do what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM