【问题标题】:Python == Function to Count All Integers Below Defined Variable, Inclusive [duplicate]Python ==计算定义变量以下所有整数的函数,包括[重复]
【发布时间】:2016-08-25 20:25:21
【问题描述】:

对不起,我不得不问这么简单的问题,但我一直在尝试这样做一段时间,但没有运气,尽管四处寻找。 我正在尝试定义一个函数,该函数将获取 X 的用户输入,然后将每个整数从 0 添加到 X,并显示输出。

例如,如果用户输入 5,则结果应该是 1 + 2 + 3 + 4 + 5 的总和。

我不知道如何提示用户输入变量,然后将此变量传递给函数的参数。感谢您的帮助。

def InclusiveRange(end):
        end = int(input("Enter Variable: ")
        while start <= end:
                start += 1
        print("The total of the numbers, from 0 to %d,  is:  %d" % (end, start))

【问题讨论】:

  • 只是关于编码风格的说明:Python 中的约定是使用 CamelCase 作为类名,使用 lower_case_with_underscores 作为函数名。因此,您的函数最好称为“inclusive_range”,或者更好的名称实际上描述了该函数的作用(例如“sum_zero_to_n”)。
  • 你知道这个值有一个封闭形式的解决方案吗? InclusiveRange = lambda end: (end * (end+1))/2

标签: python variables arguments


【解决方案1】:

只需从函数头中删除参数“end”并使用您的函数。

InclusiveRange()

或以其他方式定义代码:

def InclusiveRange(end):        
    while start <= end:
            start += 1
    print("The total of the numbers, from 0 to %d,  is:  %d" % (end, start))
end = int(input("Enter Variable: ")
InclusiveRange(end)

【讨论】:

    【解决方案2】:

    这是itertools 版本:

    >>> from itertools import count, islice
    >>> def sum_to_n(n):
    ...     return sum(islice(count(), 0, n + 1))
    >>>
    >>> sum_to_n(int(input('input integer: ')))
    input integer: 5
    15
    

    【讨论】:

      【解决方案3】:
      • 您应该将用户输入从函数中取出,并在收到用户输入后调用该函数。
      • 您还需要将总和存储在一个单独的变量中才能开始,否则每次迭代只需加 1。 (在这个例子中我把它重命名为index,因为它更能反映它的目的)。

      def InclusiveRange(end):
          index = 0
          sum = 0
          while index <= end:
              sum += start
              index += 1
          print("The total of the numbers, from 0 to %d,  is:  %d" % (end, sum))
      
      end = int(input("Enter Variable: "))
      InclusiveRange(end)
      

      Demo

      【讨论】:

        【解决方案4】:

        不要使用循环,而是使用range 对象,您可以轻松地将其发送到sum()。此外,您从未真正使用传递的end 变量,而是立即将其丢弃并将end 绑定到一个新值。从函数外部传入。

        def inclusive_range(end):
                num = sum(range(end+1))
                print("The total of the numbers, from 0 to {}, is: {}".format(end, num))
        
        inclusive_range(int(input("Enter Variable: ")))
        

        【讨论】:

          【解决方案5】:

          您还可以使用math formula 来计算从 1 到 N 的所有自然数之和。

          def InclusiveRange(end):
              ''' Returns the sum of all natural numbers from 1 to end. '''
              assert end >= 1
              return end * (end + 1) / 2
          
          end = int(input("Enter N: "))
          print(InclusiveRange(end))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-05-20
            • 1970-01-01
            • 2016-03-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-07-13
            • 1970-01-01
            相关资源
            最近更新 更多