我不知道如何让我的代码正常工作

问题描述 投票:0回答:1

我正在练习,尝试定义数学函数和其他东西,但后来我遇到了一堆错误,最终没有出现错误,但结果是错误的。这是撰写本文时的代码:

def factorial(num):
 n = 1
    for i in range(1, num+1):
        n *= i
    return n

def series(start, end, expression):
    m = 0
    for n in range(start, end+1):
        m+=eval(expression)
    return m

ans1 = input("Do you want to use factorial or a series? ")
if ans1 == "Yes":
     ans2 = input("Series or factorial? ")
     if ans2 == "Series":
        start = int(input("Select the starting value of n. "))
        end = int(input("Select the final value of n. "))
        expression = input("Type the expression to be run in terms of n. ")
        series(start, end, expression)
        print("The result is: " + str(m))
     if ans2 == "Factorial":
        factorizing = int(input("Select the number to factorize. "))
        factorial(factorizing)
        print(n)
elif ans1 == "No":
     print("Ok!")

我目前陷入困境,因为它没有将 n 识别为变量,因此无法在 print(n) 中打印。 以前似乎是正确的,但现在却不是了。

python variables math scope
1个回答
0
投票

变量 n 和 m 未在您尝试访问它的范围内定义。您的函数返回一个数字,但您从未将该值分配给变量。这是一个简单的修复:

if ans2 == "Series":
        start = int(input("Select the starting value of n. "))
        end = int(input("Select the final value of n. "))
        expression = input("Type the expression to be run in terms of n. ")
        m = series(start, end, expression)
        print("The result is: " + str(m))
 if ans2 == "Factorial":
        factorizing = int(input("Select the number to factorize. "))
        n = factorial(factorizing)
        print(n)
© www.soinside.com 2019 - 2024. All rights reserved.