Home > Backend Development > Python Tutorial > Python变量作用范围实例分析

Python变量作用范围实例分析

WBOY
Release: 2016-06-10 15:09:51
Original
1402 people have browsed it

本文实例讲述了Python变量作用范围。分享给大家供大家参考。具体如下:

#coding=utf-8
#变量作用范围
global z #使用全局变量
z=1 #给全局变量赋值
x=99 #x全局变量声明时初始化 
def foo(y): #y和z在函数中被赋值:局部的
  #局部区域
  z=x+y #x没被赋值,所以它是全局的
  return z
def bar(y):
  global z
  z=x+y
  return z
print foo(1) #结果=100
print z #结果=1 
print bar(1) #结果=100
print z #结果=100

Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template