Python for loop 不会检查每个字符串是否为空



我正在学习Python,并试图构建代码,其中for循环在继续添加所有内容之前检查字符串是空的还是非数字的。我如何阻止它去那里,而指示它通过b到e循环?

您的代码中有几个错误:

  • 您是否意识到a、b、c、d、e不存在于您的函数中?您现在使用的是一个列表,而不是只存在于函数之外的单个变量!将求和的结果累加到一个变量中,并将其打印到循环的外部
  • 要将值与None进行比较,请使用is,而不是==
  • 检查是否存在重复的验证应在循环外进行
  • 在每个条件下,您必须而不是返回!等待循环结束后再返回

if i == None:-如果变量=='',此条件将不起作用

我用if not all(tuple(map(bool, chocolate)))替换了它——它将使列表中的所有空元素都为bool类型。若元素为空,它将为False,否则为True。all()函数检查列表中的所有元素是否为True,它将返回True。

此外,我用这个not all(tuple(map(str.isdigit, chocolate)))替换了这个elif i.isnumeric() == False:,这个代码将用于每个元素方法isdigit,工作方式与前一个类似。

所以我认为你代码的elif len(chocolate) != len(set(chocolate)):部分是很好的

您可以使用sum()函数来代替这个长代码billday = int(a) + int(b) + int(c) + int(d) + int(e)billday = int(a) + int(b) + int(c) + int(d) + int(e)

最后一个我用f字符串替换了else中的代码:f"Your bill for today is {billday}. The total bill for this week is, {5 * billday}."

这是最后一个代码:

b = input("Please input the price of the 2nd chocolate:")
c = input("Please input the price of the 3rd chocolate:")
d = input("Please input the price of the 4th chocolate:")
e = input("Please input the price of the 5th chocolate:")
chocolate = [a, b, c, d, e]

def chocolatebill(chocolate):
if not all(tuple(map(bool, chocolate))) or not all(tuple(map(str.isdigit, chocolate))):
return "You missed a price. Go back and input each price again."
elif len(chocolate) != len(set(chocolate)):
return "Double check your input. The price of each chocolate must be different."
else:
billday = sum(map(int, chocolate))
return f"Your bill for today is {billday}. The total bill for this week is, {5 * billday}." 

print(chocolatebill(chocolate))```

您应该检查输入,然后计算结果。这是代码必须处理的两个独立问题。不要同时执行这些不同的操作。在您的情况下,您尝试在只检查了chocolate的第一个元素后返回总和。当然,如果您的第二个元素已经是例如None,那么这将失败。

您还应该注意变量的命名。在Python中,您在函数外定义的所有内容在函数范围内也是已知的:

x = 1
def f(y):
print(x)  # x is known here, will print 1
print(y)  # will print 2
f(y=2)

因此

chocolate = [...]
def f(chocolate):  # overwrites the `chocolate` variable defined previously
print(chocolate)  # will print 1 instead of the list

f(chocolate=1)

无论如何,为了解决您的示例,您应该使用以下内容:

A = input("Please input the price of the first chocolate:")
...
E = input("Please input the price of the 5th chocolate:")
CHOCOLATE = [A, B, C, D, E]
# naming convention: global variables, i.e. such declared outside a function/class scope
# should be capitalized
def chocolatebill(chocolates):
_validate_input(chocolates)
bill_day = sum(map(int, chocolates))
bill_week = 5 * bill_day
return f"Your bill for today is {bill_day}. The total bill for this week is {bill_week}."
def _validate_input(chocolates):
if len(chocolates) != len(set(chocolates)):  
# this does not need to be checked every time in the for loop
raise Exception("Double check your input. The price of each chocolate must be different.") 
for i in chocolates:
if not i:  # checks if the input is an empty string (evaluates to True if empty)
raise Exception("You missed a price. Go back and input each price again.")
elif not i.isnumeric():  # instead of `... == False`
raise Exception("You missed a price. Go back and input each price again.")         

print(chocolatebill(CHOCOLATE))

这里有几点:

  • 通过input方法的任何输入都不会导致空字符串(''),而不会导致None
  • 提出一个Exception,而不是在验证中返回内容。理想情况下,您甚至想要专用的异常,例如InvalidPriceError
    class InvalidPriceError(Exception):
    pass
    raise InvalidPriceError("You missed a price. Go back and input each price again.")
    
    这使您的代码更有表现力
  • CCD_ 19对任意数量的巧克力价格有效。这里,sum返回类似列表的元素中的元素的总和。map(int, chocolates)在这里将int方法映射到chocolates列表上,即尝试将其应用于每个元素并返回结果列表(确切地说是生成器)
  • 我在CCD_ 24函数之前使用了下划线;私人的";方法也就是说,它应该只在chocolatebill函数的范围内使用。这是一个Python命名。公约

这里还有很多要提到的,但我不想用太多信息来强调你。我认为这已经足够了。

最新更新