[英]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 假设
n
是一个正整数
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
. 但是当我在Python上运行它时,它给了我答案
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. 由于您要查找第一个“ n”个奇数之和,因此建议您使用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
输出为:
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. 您的代码有一些问题。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.