python-3.x - Python:尝试在函数内引用和使用我在脚本顶部声明的变量时出现未解析的引用(变量名)
问题描述
我在 python 脚本的开头声明了这些变量:
hours = 0
mins = 0
secs = 0
然后我创建一个函数,并希望在我的函数中使用这些变量:
def calc_running_total():
hours = hours + int(running_total[0:2])
mins = mins + int(running_total[3:5])
if mins == 60 or mins > 60:
hours += 1
mins = mins - 60
secs = secs + int(running_total[6:8])
if secs == 60 or secs > 60:
mins += 1
secs = secs - 60
但它在赋值运算符 (=) 之后用红色强调了小时、分钟和秒,并表示“未解决的参考:小时”,分钟和秒也是如此。
如何在函数中使用在脚本顶部声明的变量?
谢谢。
编辑:有人告诉我将“全局时间”放在函数定义中。但是对于我刚刚定义的另一个函数,我不必这样做,变量“activity_type”:
def add_to_correct_list():
if activity_type.casefold() == "work":
if day_and_date:
work_list.append((day_and_date))
print(f"\n{day_and_date} added to work_list")
work_list.append(activity_item_name + ": " + running_total)
print("\nItem and time tracking added to Work_List!")
为什么我不需要在这个函数中这样做?
解决方案
# these are considered 'global vars'
hours = 0
mins = 0
secs = 0
def calc_running_total():
global hours # now the method will reference the global vars
global mins
global secs
hours = hours + int(running_total[0:2])
mins = mins + int(running_total[3:5])
if mins == 60 or mins > 60:
hours += 1
mins = mins - 60
secs = secs + int(running_total[6:8])
if secs == 60 or secs > 60:
mins += 1
secs = secs - 60
根据要求的其他示例:
hours = 1
def implicit_global():
print(hours) # 1
hours = 1
def point_to_global():
global hours
print(hours) # 1
print(hours+ 1) # 2
print(hours) # 2
hours = 1
def implicit_global_to_local():
local_hours = hours # copies the global var and sets as a local var
print(local_hours) # 1
print(local_hours + 1) # 2
print(hours) # 1
推荐阅读
- java - Selenium 文件上传错误-> org.openqa.selenium.ElementNotInteractableException:元素不可交互
- css - 定位整个文档中的奇数元素,而不仅仅是兄弟姐妹
- php - 我希望我的日期格式为 09:54:24
- javascript - 错误:在我的 NodeJS 应用程序中找不到模块“../../models/blog”
- c++ - 计算彼此之间数字的平均值 C++
- python - 使用 telnetlib 在 telnet 期间从 tn.write() 获取输出
- react-native - 无法从 api 的响应中设置状态
- javascript - 在 Gatsby Typescript 中使用 SVG 时出错
- python - 创建用于图像更改的 Keras CNN
- javascript - 在历史记录中单击取消后,URL 不会变回。如果页面之前刷新过,则阻止警报框