编写一个从 1 到 n 的程序,对输入的数字进行加法或阶乘

Writing a program from 1 to n that does addition or factorial of number inputted

我的代码在函数定义中不进行数学运算,但我不知道为什么。当我在没有定义的情况下将它分开时它工作正常但是当使用函数定义调用 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)

在您当前的代码中,您只在以下摘录的第一行中分配了一次 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

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

您的代码中只有一个错误。您正在从 '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)