如何使这个忽略偶数? [英] How do I make this ignore even numbers?

查看:77
本文介绍了如何使这个忽略偶数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

底部的通话功能中存在24会导致错误。





The presence of 24 in the call function at the bottom causes an error.


def sum_odd_ints(list):
    add = 0
    for n in range(len(list)):
        if type(n) == int and int(n % 2 == 1):
            add += list[n]
    print(add)
    return add



sum_odd_ints(['cat', 3, 3.0, 7, 24, 'dog'])

推荐答案

你可以试试

Could you try
if type(n) == int and int(n % 2) == 1:
   add += int(n)



代替?



n 不是数组中的索引,它是从数组枚举中提取的值。这会产生巨大的差异。



你也可以改变测试奇怪的方式:


instead ?

n is not an index in your array, it is the value extracted from the enumeration of the array. That makes a huge difference.

You can also change the way you test the oddity:

if type(n) == int and int (n & 1) == 1:
   add += int(n)



第一行有一个错位的括号。 [/ Edit]


There was a misplaced parenthesis on the first line. [/Edit]


您需要使用调试器运行程序并在程序中检查 n 崩溃。

由于编译器可能会出现问题。

You need to run your program with a debugger and inspect n when the program crash.
your may have a problem because of compiler.
if type(n) == int and int(n % 2) == 1:
   add += int(n)



某些编译器不优化如果表达式,即使第一部分错误,也要评估第二部分。


Some compiler don't optimize the if expression, which make than even if the first part is wrong, the second part be evaluated.

if type(n) == int:
    if int(n % 2) == 1:
       add += int(n)



这种方式确保仅在第一部分为整数时才评估第二部分。


This way you ensure that second part is evaluated only when first part is integer.


这篇关于如何使这个忽略偶数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆