简体   繁体   中英

How do I write an iterative function that computes the sum of the first n odd numbers it returns 1 + 3 + … + (2n - 1), using a for loop?

Assuming that n is a positive integer

this is my code:

def sum_odd_n(n):
    x =1
    for x in range(n):
        if x%2==1:
            continue
        return x + 2

but when I run it on Python it gives me the answer 2 . Could you help me by telling me what's wrong and what I should do to solve this?

Since you want to find the sum of first 'n' odd numbers, I suggest you to use range function with step=2. I'll elaborate:

def sum_n(n):
    addition=0
    for x in range(1,2*n,2):
        addition+=x
    return addition
s=sum_n(5)
print(s)

This gives output as: 25

Here, in range function, 1st attribute provides starting point, 2nd attribute provides the end point, and 3rd attribute gives the Difference between each number in the sequence. I hope this helps.

There are a few problems with your code.

  • The first is that you have a return statement inside the for loop.
  • Secondly, you just visit the first n integers and check which of them are odd. You won't visit all the first n odd integers.

A list comprehension solution solution is as follows.

 def sum_odd_n(n): # sum up the first n odd numbers return sum([2*i + 1 for i in range(n)]) 

Check this program it will work:

a=int(input("how many first odd number sum you want"))

x=1

i=0

def OddSum():

      global i
      global x
      while i<=a:
            x+=2
            i+=1
      print(x)
OddSum()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM