简体   繁体   English

关于Python的一个函数

[英]About a function on Python

I'm a absolute beginner, and when I made a function to count the number of even ints on a given list, it didn't went as expected, and I can't see where I'm doing it wrong. 我是一个绝对的初学者,当我创建一个函数来计算给定列表中的偶数时,它没有按预期进行,我无法看到我做错了。

nums = [2,2,4,4,5,6,7,8,9]

def count_even(nums):
    for number in nums:
        num = 0
        if number % 2 == 0:
            num += number
            return num
        else:
            continue

The output is: 输出是:

count_even(nums)
2

It stops on nums[1] for some obscure reason. 由于一些不明原因,它停在nums [1]上。 Or it just prints the first "2" and adds it, and I don't know how to fix it, yet. 或者它只打印第一个“2”并添加它,我不知道如何解决它。

You have three problems here. 你有三个问题。

  • You're setting num = 0 every time through the loop, instead of just once at the start. 你每次循环都设置num = 0 ,而不是在开始时设置一次。 So you're only going to get the very last count that you do. 所以你只会得到你最后的计数。

  • You're doing num += number , instead of num += 1 , so instead of counting the even numbers, you're adding them. 你正在做num += number而不是num += 1 ,所以不是计算偶数,而是加入它们。

  • You're doing a return num as soon as the first even number is found, instead of only at the end of the function, after the loop. 一旦找到第一个偶数,你就会return num一个return num数,而不是仅仅在循环之后的函数结尾处。 (And that also means that if there are no even numbers, instead of returning 0 , you return None ). (这也意味着如果没有偶数,而不是返回0 ,则返回None )。

While we're at it, you don't need else: continue , because continuing is already what happens by default when you fall off the end of a loop. 虽然我们正在使用它,但您不需要else: continue ,因为继续已经是默认情况下当您从循环结束时发生的事情。


Anyway, this means it's not stopping at nums[1] , it's stopping at nums[0] —but it's adding 2 instead of 1 there, which makes things confusing. 无论如何,这意味着它不是停在nums[1] ,它停在nums[0] - 但是它在那里加2而不是1 ,这让事情变得混乱。 (It's always fun when bugs interact like that. Even more fun when they happen to exactly cancel out for your test case, like if you did nums = [6,2,4,4,5,6,7,8,9] and got back 6 and thought everything was working…) (当错误相互作用时,它总是很有趣。当它们碰巧完全抵消你的测试用例时更有趣,就像你做了nums = [6,2,4,4,5,6,7,8,9]并回到6并认为一切正常......)


So: 所以:

def count_even(nums):
    num = 0
    for number in nums:
        if number % 2 == 0:
            num += 1
    return num

Your function stops on nums[1] because the return keyword exits the function and returns num (which is set to 0 + number ). 你的函数在nums[1]上停止,因为return关键字退出函数并返回num (设置为0 + number )。 If you want to print out the sum of all the even numbers in nums you could move the return statement to the end and take the num = 0 expression out of the for loop (because it will reset to 0 after each iteration), like this: 如果你想打印出nums中所有偶数的总和,你可以将return语句移动到结尾并从for循环中取出num = 0表达式(因为它会在每次迭代后重置为0),就像这样:

def count_even(nums):
    num = 0
    for number in nums:
        if number % 2 == 0:
            num += number
        else:
            continue
    return num

Also, your else statement is redundant here, so you could simply remove it, leaving you with the following: 另外,你的else语句在这里是多余的,所以你可以简单地将其删除,留下以下内容:

def count_even(nums):
    num = 0
    for number in nums:
        if number % 2 == 0:
            num += number
    return num

And you could simplify that further to: 你可以进一步简化:

def count_even(nums):
    evens = [number for number in nums if number % 2 == 0]
    return sum(evens)

Another solution: 另一种方案:

def count_even(nums):
    return len([i for i in nums if i % 2 == 0])

There are a couple of problems in your code: 您的代码中存在一些问题:

  • Your num needs be defined outside the loop, so you can count every even number found. 您的num需要在循环外定义,因此您可以计算找到的每个偶数。 If you define it inside the loop, it resets to 0 every iteration. 如果在循环内定义它,则每次迭代都会重置为0
  • When you find an even number, you increment it towards the counter num . 当你找到一个偶数,你增加它朝着对num You need to instead increment num by 1. 您需要将num递增1。
  • You return immediately when a even number is found, this means the function exits on the first even number. 当找到偶数时,立即return ,这意味着函数退出第一个偶数。 You instead want to return the total num at the end. 你不是要返回的总num底。
  • You have an unnecessary continue in the else block. 你在else块中有一个不必要的continue If a uneven number is found, simply ignore it. 如果找到不均匀的数字,则忽略它。

Which these suggestions, you could implement your code like this: 哪些建议,您可以像这样实现您的代码:

nums = [2,2,4,4,5,6,7,8,9]

def count_even(nums):
    num = 0

    for number in nums:
        if number % 2 == 0:
            num += 1

    return num

print(count_even(nums))
# 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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