Home > database >  Functions and infinite loops
Functions and infinite loops

Time:09-15

The code below should create a function to calculate and return the sum of all of the even numbers from 0 to the passed number being 10(inclusive) using a while loop. But instead, it just creates an infinite loop and I don't know why.

def function(lex):
zero = 0 
while zero <= lex:
    while lex % 2 == 0:
        print(lex)
        zero = zero   1
    while lex % 2 =! 0:
        zero = zero   1
return sum

print(function(10))

CodePudding user response:

I think you have to change the second and third while loops and replace them with an if statement that checks whether the number is even or odd.

Maybe this is the code you are looking for:

def function(lex):
  sum = 0
  while 0 <= lex:
    if lex%2 == 0:
      print(lex)
      sum = sum   lex
    lex = lex-1
  return sum

And then you can call the function print(function(10))

  • Related