Python Forum
My function won't return the sum unless the last paramater is an odd number.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
My function won't return the sum unless the last paramater is an odd number.
#1
Hi guys, I'm trying to return the summation of all even numbers, but the function won't return anything unless the parameter "y" is an odd number.
def sumOfEvens(x,y):
    total = 0

    while x <= y:

        if (x % 2 == 0):
            total = (total + x)
            
        elif (x == y):
            return total

        x = (x + 1)
            

I fixed it by removing the elif statment.
def sumOfEvens(x,y):
    total = 0

    while x <= y:

        if (x % 2 == 0):
            total = (total + x)
            
        x = (x + 1)

    return total
            
Reply
#2
You know, a for loop would be much better in that situation:

def sum_evens(x, y):
    total = 0
    for z in range(x, y + 1):
        if z % 2:
            total += z
    return total
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  nested function return MHGhonaim 2 608 Oct-02-2023, 09:21 AM
Last Post: deanhystad
  return next item each time a function is executed User3000 19 2,276 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  function return boolean based on GPIO pin reading caslor 2 1,170 Feb-04-2023, 12:30 PM
Last Post: caslor
  float("{:.2f}" return long number? korenron 2 1,029 Jul-13-2022, 05:35 AM
Last Post: korenron
  return vs. print in nested function example Mark17 4 1,736 Jan-04-2022, 06:02 PM
Last Post: jefsummers
  How to invoke a function with return statement in list comprehension? maiya 4 2,821 Jul-17-2021, 04:30 PM
Last Post: maiya
  Checking the number of arguments a function takes Chirumer 3 2,152 Jul-06-2021, 04:56 PM
Last Post: Chirumer
  Function - Return multiple values tester_V 10 4,436 Jun-02-2021, 05:34 AM
Last Post: tester_V
  Get return value from a threaded function Reverend_Jim 3 17,030 Mar-12-2021, 03:44 AM
Last Post: Reverend_Jim
  Return not exiting function?? rudihammad 3 5,276 Dec-01-2020, 07:11 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020