需要帮助新的编程使用Python和我有点困惑,它更像是一个真正的困惑

2024-05-03 00:56:16 发布

您现在位置: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
    firstNum = secondNum

print('The Sum:', (secondNum))

我知道你应该以奇数之和结束。你知道吗

所以第一个空白是输入,第二个空白是总和,但我不知道怎么把它们放在这样的句子里。你知道吗


Tags: the代码用户程序numberinput数字整数
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

要使用for循环:

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$ 

相关问题 更多 >