Python-变量范围 [英] Python- Variable Scope

查看:43
本文介绍了Python-变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def 接口():Number = input("请输入数字:")界面()打印(数字)

这是我的代码的一小段简化片段,它产生:

<前>回溯(最近一次调用最后一次):文件C:/Users/Jack/Documents/Python/NumberToText.py",第 78 行,在打印(数字)NameError: 名称 'Number' 未定义

我理解这是因为变量是在函数中定义的.

我该怎么做才能解决这个问题?

解决方案

这取决于你想做什么.

可能让 Interface 函数返回 Number 是最简单的解决方案

def interface():number = input("请输入数字:")退货号码打印(接口())

请参阅此 SO QA,了解 Python 中的范围规则主题

注意:如您所见,我已按照 PEP-8 指南

def Interface():
     Number = input("Enter number: ")

Interface()
print(Number)

This is a small simplified snippet of my code which produces:

Traceback (most recent call last):
  File "C:/Users/Jack/Documents/Python/NumberToText.py", line 78, in 
    print(Number)
NameError: name 'Number' is not defined

I underdstand this is because the variable is defined in a function.

What can I do to fix this?

解决方案

It depends on what you want to do.

Probably making the Interface function return Number would be the easiest solution

def interface():
     number = input("Enter number: ")
     return number

print(interface())

Please see this SO QA on the topic of scope rules in python

Note: as you can see, I have converted the names of the function and the variable to lowercase, following the PEP-8 guideline

这篇关于Python-变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆