python - 为什么我的代码只在运行第一个函数时才起作用,而第二个函数给我一个赋值前引用的变量?
问题描述
我已经尝试更改问题的变量 thinkig 的名称,但这并没有解决它。我正在尝试计算输入到 get_numbers 函数中的数字的加法持久性和乘法持久性以及加法和乘法根。对于additive_calculator 和multiplicative_calculator 函数,无论我调用第一个函数,但第二个函数在打印语句中给我一个错误,说根的值,我在这种情况下称为total 和total2,在赋值之前给了我一个引用错误。我不知道如何解决此错误。`在此处输入代码
from functools import reduce
def get_numbers():
num = (int(input("Please enter an integer(negative integer to quit):")))
nums = [int(a) for a in str(num)]
return(nums)
nums = get_numbers()
print(nums)
def additive_calculator(nums):
print("Additive loop")
counter = 0
while len(nums) > 1:
for num in nums:
len(nums)
total = 0
total = sum(nums)
list.clear(nums)
nums = [int(a) for a in str(total)]
print("sum:", total)
print(len(nums))
counter = counter + 1
print("Additive persistence", counter,",", "Additive Root:", total)
print("DONE")
def multiplicative_calculator(nums):
print("multiplicative loop")
counter = 0
while len(nums) > 1:
for num in nums:
len(nums)
total2 = 0
total2 = reduce(lambda x, y: x*y,(nums))
list.clear(nums)
nums = [int(a) for a in str(total2)]
print("sum:", total2)
print(len(nums))
counter = counter + 1
print("multiplicative persistence", counter,",", "multiplicative Root:", total2)
print("DONE")
multiplicative_calculator(nums)
additive_calculator(nums)
解决方案
如果您在函数中的任何位置分配给变量,则该变量被视为局部变量(除非声明为全局变量或非局部变量)。函数运行时您是否实际执行分配并不重要;在分配给它的函数中有一些语句就足够了。
例如,在下面的函数中,a
仅当参数b
为 true 时才分配给变量,但a
如果不分配给它(whenb
为 false),它仍然是局部变量。
def f(b):
if b:
a = "foo"
return a
f(True) # -> "foo"
f(False) # error
循环也是如此。如果您分配给循环体中的变量或循环中的for
变量,则即使您不执行循环体,该变量也是局部变量。如果你执行body,变量被赋值,读取它是安全的,但是如果你不执行body,变量没有被初始化,读取它是错误的。
def f(x):
for a in x:
pass
return a
f([1, 2, 3]) # -> 3
f([]) # error
在您的代码中,如果nums
为空,total2
则永远不会分配给。它仍然是一个局部变量,因为在代码中对其进行了赋值——语句永远不会执行并不重要——但是如果你没有赋值,读取变量是错误的。
total2
修复很简单:无论是否进入循环体,都要确保初始化。
def multiplicative_calculator(nums):
print("multiplicative loop")
counter = 0
total2 = 0 # move initialisation of total2 here
while len(nums) > 1:
# same code as before...
# when you get here, total2 is initialised whether you
# entered the loop or not.
print("multiplicative persistence", counter,
",", "multiplicative Root:", total2)
推荐阅读
- ios - 显示 iOS 15 问题的小部件图像。黑色矩形出现/消失在图像上
- ruby-on-rails - 如何在 Rails ActiveRecord 中一次执行多个 JOINS
- node.js - 将 CoseSign1 转换为 JSON
- javascript - 知道为什么 Typescript 在 Material UI Alert severity 属性中会以这种方式运行吗?
- javascript - Sequelize 是否提供有条件地选择属性的方法?
- javascript - 登录页面未将用户值发送到 Firebase 并转到主页
- github-actions - 错误:过程已完成,错误代码 1 – 自托管运行器上的 GitHub 操作
- python - 将 matplotlib 图转换为 json 对象
- css - 如何在网格显示中为每一行添加支撑线
- visual-studio-code - 文本结束后将 VSCode 装饰器应用于空白空间