需要帮助使用Python编程新手,我有点困惑,这更像是一个非常困惑的问题
编写一个程序,让用户输入一个整数N,然后打印前N个奇数整数的和。例如,如果用户输入4,则应打印前4个奇数的总和为16。(因为1+3+5+7=16)请注意,用户输入的数字显示为输出的一部分。[10分] 下面的代码是我所有的问题需要帮助使用Python编程新手,我有点困惑,这更像是一个非常困惑的问题,python,Python,编写一个程序,让用户输入一个整数N,然后打印前N个奇数整数的和。例如,如果用户输入4,则应打印前4个奇数的总和为16。(因为1+3+5+7=16)请注意,用户输入的数字显示为输出的一部分。[10分] 下面的代码是我所有的问题 n = int(input('Enter the Number of Odd Integers:')) firstNum = 1 for i in range(n-2): temp = firstNum secondNum = temp + 2 f
n = int(input('Enter the Number of Odd Integers:'))
firstNum = 1
for i in range(n-2):
temp = firstNum
secondNum = temp + 2
firstNum = secondNum
print('The Sum:', (secondNum))
我知道你应该以奇数之和为结尾
所以第一个空格是输入,第二个是总和,但我不知道如何将它们放在这样的句子回答中。你想使用
进行循环:
num = int(raw_input('How high do you want the diamond to be? ')) #To get input
for i in range(1, num+1): #For loop to loop through numbers
print ' '*(num-i)+'* '*i #Print the indent first, and then the stars for the diamond
for i in range(1, num+1): #Second for loop for other half of diamond
print ' '*(i)+'* '*(num-i) #Print the indent first, and then the stars for the diamond
其运行方式如下:
bash-3.2$ python diamond.py
How high do you want the diamond to be? 5
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
bash-3.2$ python diamond.py
How high do you want the diamond to be? 21
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
bash-3.2$ python diamond.py
How high do you want the diamond to be? 7
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
bash-3.2$
对于第一个问题,您不是将奇数相加,而是简单地增加secondNum的值。相反,您希望将它们全部添加到一起
可爱的版本
>>> def f():
n = int(input('Enter N: '))
print(sum(range(1,2*n,2)))
>>> f()
Enter N: 4
16
>>> f()
Enter N: 3
9
在你提问之前,可以试着发布你的代码。你能修改这个问题吗?。代码不清楚!!是的,刚刚修改过,谢谢!我修正了这个问题,所以它只显示了一个我现在没有的,任何帮助都将不胜感激。非常感谢你帮我这么做,唯一的事情是它还要求我做一个反向三角形,在第一个的另一边向下,所以它是钻石,k所有的工作,我很抱歉问你这个问题,但是你一直都很好!即使你不做第二部分,我也很高兴你今晚抽出时间来帮我做这件事@帕特里克,修正了:)你能接受这个答案吗?谢谢非常感谢!!!!!!你是最棒的!!!!!!非常感谢您的帮助,问题的另一个问题是在最后一句中输入和求和,比如“前4个奇数的和是16”