python - 使用函数返回名称后如何重用名称?
问题描述
我正在上一门基本的计算机编程课程,偶然发现了一个问题,我不知道如何使用前一个函数中的变量。提示是取一个起始值和一个结束值并计算其间的数字。我怎样才能改变这个?
我还没有真正尝试过任何东西。我真的被困住了。
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
我希望输出立即打印总和和产品
解决方案
您不能使用在这些函数之外的其他函数中初始化的变量(称为“范围”)。您必须将起始值作为参数传递,就像您使用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)
并为所有需要该值的函数执行此操作。
你也可以在这里阅读更多关于这件事的信息
推荐阅读
- amazon-web-services - 如何只允许 1 个第三方网站访问我的 S3 对象?
- uwp - 无法使用“无效的包标识/系列名称”错误发布 UWP 包更新
- javascript - 如何在d3中的圆圈之间动态绘制和动画线?
- python - 在具有索引Python数的Excel工作表中搜索特定字符串
- if-statement - x86汇编中条件语句的实现
- ruby-on-rails - 通过一系列控制器传递 Rails 请求?
- python - 将scrapy数据打印到csv
- r - 无法绘制逻辑回归图
- java - 启动应用程序时显示异常 - org.openqa.selenium.WebDriverException:
- php - 如何在 php 中调整 Jquery jtable 列宽?