# PURPOSE: to calculate the sum of the first (n) odd counting numbers
#
# INPUT(S): the number (n) which will be the last number added to the sum
#
# OUTPUT(S): the sum of the first (n) counting numbers
#
# EXAMPLES: input: 23 ; output: 144
#           input: 15 ; output: 64
#
################################################################################
import math

def sums(n):
    total = 0
    for i in range(0, n + 1, 1):
        total += i
    return total



def main():
    n = input('Enter a number: ')
    s = sums(n)
    print 'The sum of the numbers is', s
    while n <= 0:
        print "Please Enter a positive number."
        break



main()

the code in this program is actually to calculate just the sum of (n) counting numbers. what i'm trying to do is listed in the purpose and i know that the "sum= 1 +3+5 +7+...+2n -1" but i've tried numerous ways to figure out how to correctly modify the above code to print the right calculations of the sum. any type of help is welcome, thanks!

Recommended Answers

All 3 Replies

#!/usr/bin/python
def sums(n):
    total = 0
    next_odd=1
    while next_odd <= n:
        total += next_odd
        next_odd+=2
    return total
 
 
 
def main():
    n = input('Enter a number: ')
    s = sums(n)
    print 'The sum of the numbers is', s
    while n <= 0:
        print "Please Enter a positive number."
        break
 
 
 
main()

Just change your range(start, stop, step) parameters ...

n = 15
total = 0

# start at 1 in steps of 2 to get odd numbers
for i in range(1, n + 1, 2):
    total += i
    print i, total  # test

"""my result -->
1 1
3 4
5 9
7 16
9 25
11 36
13 49
15 64
"""

sum is actually a built-in function so you can easily change it a single line: sum(range(1, n+1, 2))

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.