Python. How to sum up all even integers in a list?

前端 未结 4 2114
一向
一向 2021-01-07 04:45

I\'m completely new to the subject and I want to ask how to sum up all even integers in a list (without using functions (I haven\'t studied them yet))? For example:

4条回答
  •  被撕碎了的回忆
    2021-01-07 05:01

    You need to store the result in a variable and add the even numbers to the variable, like so:

    >>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
    >>> result = 0  # Initialize your results variable.
    >>> for i in myList:  # Loop through each element of the list.
    ...   if not i % 2:  # Test for even numbers.
    ...     result += i
    ... 
    >>> print(result)
    60
    >>> 
    

提交回复
热议问题