[Learn python from zero] 28. Local variables and global variables in Python

local variable

  • A local variable is a variable defined inside a function
  • Its scope of action is inside this function, that is, it can only be used in this function, and cannot be used outside the function
  • Because its scope of action is only within its own function, different functions can define local variables with the same name (for example, treat you and me as functions, and understand local variables as mobile phones in everyone's hands, you But there is an iPhone8, of course I can also have an iPhone8, they are not related to each other)
  • The role of local variables, in order to temporarily save data, variables need to be defined in the function for storage
  • When the function is called, the local variable is created, and the variable cannot be used after the function call is completed.

As shown below:

insert image description here

global variable

If a variable can be used not only in one function, but also in other functions, such a variable is a global variable

For example: there are two brothers who each have a mobile phone, and each has its own little secret in the mobile phone, which is not allowed to be used by the other party (it can be understood as a local variable); but the phone at home can be used by both brothers casually ( Can be understood as global variables)

# 定义全局变量
a = 100

def test1():
    print(a)  # 虽然没有定义变量a但是依然可以获取其数据

def test2():
    print(a)  # 虽然没有定义变量a但是依然可以获取其数据

# 调用函数
test1()
test2()

operation result:

Summary 1:

  • Variables defined outside a function are called global variables
  • Global variables can be accessed in all functions

Global variable and local variable names have the same problem

Look at the following code:

insert image description here

Summary 2:

  • When the local variable and the global variable have the same name in the function, the variable name = data inside the function is understood as defining a local variable instead of modifying the value of the global variable

Modify global variables

Can it be modified when used in a function?

code show as below:

# 修改全局变量
a = 100

def change_global_variable():
    global a  # 使用global关键字声明全局变量
    a = 200

change_global_variable()
print(a)  # 输出200

Summary 3:

  • If the name of the global global variable appears in the function, even if the variable name = data that is the same as the global variable name appears in this function, it is understood as modifying the global variable instead of defining a local variable
  • If multiple global variables need to be modified in a function, they can be declared all at once or separately.
# 可以使用一次global对多个全局变量进行声明
global a, b
# 还可以用多次global声明都是可以的
# global a
# global b

View all global and local variables

Python provides two built-in functions globals() and locals() that can be used to view all global and local variables.

def test():
    a = 100
    b = 40
    print(locals())  # {'a': 100, 'b': 40}

test()

x = 'good'
y = True
print(globals())  # {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x101710630>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/jiangwei/Desktop/Test/test.py', '__cached__': None, 'test': <function test at 0x101695268>, 'x': 'good', 'y': True}

function return value

How do we return multiple values ​​in python?

1. Multiple return?

def create_nums():
    print("---1---")
    return 1  # 函数中下面的代码不会被执行,因为return除了能够将数据返回之外,还有一个隐藏的功能:结束函数
    print("---2---")
    return 2
    print("---3---")

result = create_nums()
print(result)  # 输出1

Summary 1:

  • There can be multiple return statements in a function, but as long as one return statement is executed, the function will end, so the subsequent return is useless.

  • If the program is designed as follows, it is possible because different returns are executed in different scenarios

def create_nums(num):
    print("---1---")
    if num == 100:
        print("---2---")
        return num+1  # 函数中下面的代码不会被执行,因为return除了能够将数据返回之外,还有一个隐藏的功能:结束函数
    else:
        print("---3---")
        return num+2
    print("---4---")

result1 = create_nums(100)
print(result1)  # 输出101
result2 = create_nums(200)
print(result2)  # 输出202

2. How a function returns multiple data

def divid(a, b):
    shang = a//b
    yushu = a%b 
    return shang, yushu  #默认是元组

result = divid(5, 2)
print(result)  # 输出(2, 1)

Summary 2:

  • Return can be followed by tuples, lists, dictionaries, etc. As long as it is a type that can store multiple data, multiple data can be returned at one time.
def function():
    # return [1, 2, 3]
    # return (1, 2, 3)
    return {"num1": 1, "num2": 2, "num3": 3}

If there are multiple data after return, the default is a tuple.

Unpack the returned data directly

def get_my_info():
    high = 178
    weight = 100
    age = 18
    return high, weight, age  # 函数返回三个数据,会自动打包为元组

my_high, my_weight, my_age = get_my_info()  # 直接把元组拆分为三个变量来使用,更加方便
print(my_high)
print(my_weight)
print(my_age)

Summarize:

  • Pay attention when unpacking, the number of data to be unpacked must be the same as the number of variables, otherwise the program will be abnormal
  • In addition to unpacking tuples, you can also unpack lists, dictionaries, etc.
In [17]: a, b = (11, 22)
In [18]: a
Out[18]: 11
In [19]: b
Out[19]: 22

In [20]: a, b = [11, 22]
In [21]: a
Out[21]: 11
In [22]: b
Out[22]: 22

In [23]: a, b = {
    
    "m":11, "n":22}  # 取出来的是key,而不是键值对
In [24]: a
Out[24]: 'm'
In [25]: b
Out[25]: 'n'

Advanced case

[Python] Python realizes the word guessing game-challenge your intelligence and luck!

[python] Python tkinter library implements GUI program for weight unit converter

[python] Use Selenium to get (2023 Blog Star) entries

[python] Use Selenium and Chrome WebDriver to obtain article information in [Tencent Cloud Studio Practical Training Camp]

Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition

[Fun with Python series [Xiaobai must see] Python multi-threaded crawler: download pictures of emoticon package websites

[Play with Python series] [Must-see for Xiaobai] Use Python to crawl historical data of Shuangseqiu and analyze it visually

[Play with python series] [Must-see for Xiaobai] Use Python crawler technology to obtain proxy IP and save it to a file

[Must-see for Xiaobai] Python image synthesis example using PIL library to realize the synthesis of multiple images by ranks and columns

[Xiaobai must see] Python crawler actual combat downloads pictures of goddesses in batches and saves them locally

[Xiaobai must see] Python word cloud generator detailed analysis and code implementation

[Xiaobai must see] Python crawls an example of NBA player data

[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python

[Must-see for Xiaobai] Technical realization of using Python to download League of Legends skin pictures in batches

[Xiaobai must see] Python crawler data processing and visualization

[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory

[Must-see for Xiaobai] Use Python to generate a personalized list Word document

[Must-see for Xiaobai] Python crawler combat: get pictures from Onmyoji website and save them automatically

Xiaobai must-see series of library management system - sample code for login and registration functions

100 Cases of Xiaobai's Actual Combat: A Complete and Simple Shuangseqiu Lottery Winning Judgment Program, Suitable for Xiaobai Getting Started

Geospatial data processing and visualization using geopandas and shapely (.shp)

Use selenium to crawl Maoyan movie list data

Detailed explanation of the principle and implementation of image enhancement algorithm Retinex

Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis

Introductory Guide to Crawlers (7): Using Selenium and BeautifulSoup to Crawl Douban Movie Top250 Example Explanation [Reptile Xiaobai must watch]

Getting Started Guide to Crawlers (6): Anti-crawlers and advanced skills: IP proxy, User-Agent disguise, Cookie bypass login verification and verification code identification tools

Introductory Guide to Crawlers (5): Distributed Crawlers and Concurrency Control [Implementation methods to improve crawling efficiency and request rationality control]

Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API

Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies

Getting started with crawlers (2): How to use regular expressions for data extraction and processing

Getting started with reptiles (1): Learn the basics and skills of reptiles

Application of Deep Learning Model in Image Recognition: CIFAR-10 Dataset Practice and Accuracy Analysis

Python object-oriented programming basics and sample code

MySQL database operation guide: learn how to use Python to add, delete, modify and query operations

Python file operation guide: encoding, reading, writing and exception handling

Use Python and Selenium to automate crawling#【Dragon Boat Festival Special Call for Papers】Explore the ultimate technology, and the future will be due to you"Zong" #Contributed articles

Python multi-thread and multi-process tutorial: comprehensive analysis, code cases and optimization skills

Selenium Automation Toolset - Complete Guide and Tutorials

Python web crawler basics advanced to actual combat tutorial

Python introductory tutorial: master the basic knowledge of for loop, while loop, string operation, file reading and writing and exception handling

Pandas data processing and analysis tutorial: from basics to actual combat

Detailed explanation of commonly used data types and related operations in Python

[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model

Introductory Python programming basics and advanced skills, web development, data analysis, and machine learning and artificial intelligence

Graph prediction results with 4 regression methods: Vector Regression, Random Forest Regression, Linear Regression, K-Nearest Neighbors Regression

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/132293363