簡體   English   中英

滿足條件后,額外運行一次while while循環

[英]Run while loop one extra time after condition is met

我正在制作一個面積計算器以幫助我理解Python的基礎,但是我想對其進行某種類型的驗證-如果長度小於零,則再次詢問。 我已經設法通過形狀函數內部的“驗證”代碼(例如,在“正方形”函數內部)執行此操作,但是當我將驗證代碼放在單獨的函數“ negativeLength”中時,它不起作用。 這是我在單獨函數中的代碼:

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

當我通過調用'negativeLength(Length)'來運行它時,它將再次詢問我長度(應該如此),但是當我輸入正長度時,條件就被滿足了,因此實際循環不會運行。

我也嘗試過( 在Python中模擬do-while循環之后?

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

...但是那也不起作用。

我將參數設置為“ whichOne”,因為圓的“長度”稱為“半徑”,因此對於一個正方形,我將其稱為negativeLength(Radius)而不是negativeLength(Length)。

那么,有什么方法可以使“ whileOne = int(input ...)”之后的while循環結束?

編輯:我正在使用Python 3.3.3

就您所編寫的代碼而言,它是可行的。 但是,它實際上不會做任何有用的事情,因為whichOne永遠不會返回給函數的調用者。 注意

def f(x):
    x = 2

x = 1
f(x)
print(x)

將打印1,而不是2。您想要執行以下操作:

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)

我假設您使用的是Python3。否則,您需要使用raw_input()而不是input()。

我通常為此使用的代碼如下所示:

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

哪個應該做你想做的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM