不正确的循环和返回变量

时间:2016-06-11 14:32:00

标签: python

我的代码是检查输入(数量)是否为数字。如果它是第一次的数字,它返回数字罚款。但是,如果你要输入一个字母,然后当函数循环输入一个数字时,' 0' 0返回而不是您输入的数字。

def quantityFunction():
    valid = False
    while True:
            quantity = input("Please enter the amount of this item you would like to purchase: ")
            for i in quantity:
                try:
                    int(i)
                    return int(quantity)
                except ValueError:
                    print("We didn't recognise that number. Please try again.")
                    quantityFunction()
                    return False

我是否错误地循环了该功能?

1 个答案:

答案 0 :(得分:3)

实际上你的功能不正确,你正在使用# -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup url="http://autoplius.lt/redaguoti/naudoti-automobiliai/" page = requests.get(url) soup = BeautifulSoup(page.content, "html.parser") car_makes_select = soup.find("select", {"id": "make_id"}) car_makes = car_makes_select.select("option") for item in car_makes: itemMain = item itemMain = itemMain.get('value') payload = { 'make_id': itemMain } form = requests.post(url, params=payload) soup11 = BeautifulSoup(form.text, "html.parser") model_select = soup11.find("select", {"id": "model_id"}) print model_select 循环和while,这在这种情况下是不必要的。

虽然,您可以尝试以下代码,这是基于您的功能的一点修改,但仅使用recursion function循环。

while

但是,如果您希望使用def quantityFunction(): valid = False while not valid: quantity = input("Please enter the amount of this item you would like to purchase: ") for i in quantity: try: int(i) return int(quantity) except ValueError: print("We didn't recognise that number. Please try again.") valid = False break ,实际上您可以更轻松地完成此操作:

while loop

如果您真的想使用def quantityFunction(): while True: quantity = input("Please enter the amount of this item you would like to purchase: ") if quantity.isdigit(): return int(quantity) else: print("We didn't recognise that number. Please try again.") ,请尝试以下操作:

recursive function

请注意如果您希望在输入数字时最终返回该值,则需要在def quantityFunction1(): quantity = input("Please enter the amount of this item you would like to purchase: ") if quantity.isdigit(): return int(quantity) else: print("We didn't recognise that number. Please try again.") return quantityFunction() 中使用return quantityFunction()。否则最终将不会返回任何内容。这也解释了为什么你在第一次返回时输入数字而不是之后输入数字的问题。