I am trying to find the odd numbers in a range of numbers, and adding them all up.
- I set my variable which is the range of numbers (5)
- I then made a function which had the for statement, looking for the numbers in range from 1 to 1 num(this is for including the number) and the comma after that to skip every other number.
- Then I printed the total sum, and outside of the function I called the function.
num = 5
def sumOfOdds():
sum = 0
for i in range(1, 1 num, 1):
sum = sum i
print(sum)
sumOfOdds()
I tried to read other ways to fix this, but was unable to find a solution.
CodePudding user response:
The third parameter in the range is the incremental value of the iterator which means that you want it to be 2, not 1, as you want to skip every other number. (By default its value is 1).
def sumOfOdds():
sum = 0
for i in range(1, 1 num, 2): # Here we set it to 2
sum = sum i
print(sum)
For more info on range()
visit https://docs.python.org/3/library/stdtypes.html#range
CodePudding user response:
This is an easy fix. the third argument in range should be 2, not 1.
num = 12
def sumOfOdds():
sum = 0
for i in range(1, 1 num, 2):
sum = sum i
print(sum)
sumOfOdds()
CodePudding user response:
To add to the provided response, I would add that there's a more pythonic way to write it using the reduce
function:
def sumOfOdds():
return reduce(lambda x, y: x y, range(1, 1 num, 2))
Also, let's say you'd like to pass the list to iterate as a parameter, you can use the following writing in Python
def sumOfOdds(values):
return reduce(lambda x, y: x y, values[::2])
sumOfOdds(range(1, 1 num))
Where in python [x:y:i]
means: start at iterable index of x, end at iterable index of y-1, skip every i values. So [::2]
means start at the beggining, end at the end, and skip every 2 values.