首页 > 解决方案 > 使用函数返回名称后如何重用名称?

问题描述

我正在上一门基本的计算机编程课程,偶然发现了一个问题,我不知道如何使用前一个函数中的变量。提示是取一个起始值和一个结束值并计算其间的数字。我怎样才能改变这个?

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

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

我希望输出立即打印总和和产品

标签: pythonfunction

解决方案


您不能使用在这些函数之外的其他函数中初始化的变量(称为“范围”)。您必须将起始值作为参数传递,就像您使用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)

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

你也可以在这里阅读更多关于这件事的信息


推荐阅读