返回带有函数的名称后,我该如何重用?

时间:2019-10-15 15:39:34

标签: python function

我正在上一门基础的计算机编程课程,偶然发现了一个我不知道如何使用先前函数中的变量的问题。提示是取一个起始值和一个终止值,并计算两者之间的数字。我该如何更改?

我还没有尝试过任何东西。我真的被卡住了。

def getStartNum():
    startValue = int(input("Enter starting number: "))
    while(startValue<0):
        print("Invalid input.")
        startValue = int(input("Enter starting number: "))
    return startValue
def getStopNum():
    stop = int(input("Enter the ending number: "))
    while(stop <= startValue):
        print("Ending number must be greater than the starting value.")
        stop = int(input("Enter the ending number: "))
    return stop
def sumOfNums(startValue, stop):
    total = 0
    for i in range(startValue, stop+1, 1):
        total+=i
    return total
def productOfNums(startValue, stop):
    product = 1
    for j in range(startValue, stop+1, 1):
        product*=i
    return product
st = getStartNum()
sp = getStopNum()
ns = sumOfNums(st, sp)
p = productOfNums(st, sp)
print("The sum of the sequence is:", ns)
print("The product of the sequence is:", p)
cont = input("Do you want to continue? y/n: ")

错误消息:

    while(stop <= startValue):
NameError: name 'startValue' is not defined

我希望输出立即打印总和和积

1 个答案:

答案 0 :(得分:4)

您不能使用在其他函数(这些函数称为“作用域”)之外初始化的变量。您必须像使用sumOfNums(startValue, stop)

一样将起始值作为参数传递
def getStopNum(startValue):
    stop = int(input("Enter the ending number: "))
    while(stop <= startValue):
        print("Ending number must be greater than the starting value.")
        stop = int(input("Enter the ending number: "))
    return stop
st = getStartNum()
sp = getStopNum(st)

对需要该值的所有函数执行此操作。

您还可以了解有关here

的更多信息