编写从1到n的程序,该程序执行输入的数字的加法或因子

时间:2018-02-20 04:25:18

标签: python factorial

我的代码在函数定义中没有进行数学计算,但我不知道为什么。当我在没有定义的情况下分开时它可以正常工作但是在使用函数定义调用if时它会产生0或1的结果

#Write a program that asks the user for a number n and gives them the possibility to choose
# between computing the sum and computing the product of 1,…,n.
def summation(n):
    adding = 0
    while n != 0:
        adding += n
        n -= 1
    print(adding)

def factorial(n):
    product = 1
    while n != 0:
        product *= n
        n -= 1
    print(product)

n =0
num = int(input("Enter a number: "))
choice = int(input("Would you like Sum(1) or Product(2)"))

if choice == 1:
     summation(n)

if choice == 2:
    factorial(n)

2 个答案:

答案 0 :(得分:1)

在当前代码中,您只在以下摘录的第一行中分配n:

n = 0
num = int(input("Enter a number: "))
choice = int(input("Would you like Sum(1) or Product(2)"))

if choice == 1:
     summation(n)

因此,您总是计算求和(0)。最有可能的是,您希望最后一行读取

if choice == 1:
     summation(num)  # num instead of n

此外,请考虑从求和和阶乘函数中返回值,然后打印它们。这样,您可以将这些函数用于其他目的,例如在更复杂的计算中,并测试它们。

答案 1 :(得分:1)

您的代码中只有一个错误。您正在从“num”变量&中取出用户的号码。将'n'传递给求和&阶乘函数,其值为'0'。

现在您可以运行此代码了。

def summation(n):
    adding = 0
    while n != 0:
        adding += n
        n -= 1
    print(adding)

def factorial(n):
    product = 1
    while n != 0:
        product *= n
        n -= 1
    print(product)

n =0
num = int(input("Enter a number: "))
choice = int(input("Would you like Sum(1) or Product(2)"))

if choice == 1:
     summation(num)

if choice == 2:
    factorial(num)