


This article will help you understand variables and constants in Python
Jul 25, 2023 pm 02:15 PM1. The difference between variables and constants
Variable: The amount that changes in value during the running of the program.
Constant: A quantity whose value will not change during the running of the program.
Whether it is a variable or a constant, a space will be opened in the memory when it is created to save its value.
2. Variables
1. Variables in Python do not need to declare types
This is based on the dynamic language features of Python. Variables can be used directly without declaring the type in advance. For example, the following four variables a, b, c, and d do not have any type declarations such as int a, str b, list c, int d before use, which is required in C language and JAVA programming language. portable.
For example:
a = 4 b = "haha" c = [] d = 9-5
2. Use the "=" sign to assign a value to the variable
a = 100
The equal sign here should be understood and read as "assignment", not "equal to". "Assignment" is an operation on variables, while "equal to" is a comparison of two variables. The four variables a, b, c, and d above are assigned different values ??through the "=" sign.
3. Each variable must be assigned a value before use, and the variable will not be created until it is assigned a value.
New variables create and open up memory space and save values ??through the action of assignment. If used directly without assignment, the exception referenced before assignment or an unnamed exception will be thrown.
For example:
a # 孤單單一個(gè)a,什么也表示不了,只能報(bào)錯(cuò) a = 1 # 這樣就沒問題了,解釋器知道a是個(gè)新變量了 c.append(1) # c是個(gè)什么鬼? NameError: name 'c' is not defined
Result:
##4. In Python, the variable itself has no concept of data type
The commonly referred to as "variable type" is the type of the object referenced by the variable , or the type of the variable's value.a = 1
a = "haha"
a = [1, 2, 3]
a = { "k1":"v1"}
變量a在創(chuàng)建的時(shí)候,賦予了值為1的整數(shù)類型,然后又被改成字符串“haha”,再又變成一個(gè)列表,最后是個(gè)字典。變量a在動(dòng)態(tài)的改變,它的值分別是不同的數(shù)據(jù)類型,這是動(dòng)態(tài)語言的特點(diǎn)。
5. “=”號(hào)這個(gè)賦值運(yùn)算符是從右往左的計(jì)算順序
a = 1 b = 2 c = a + b # 先計(jì)算a+b的值,再賦給c print(c)
6. Python允許同時(shí)為多個(gè)變量賦值
(例如:a = b = c = 1,最終大家都是1)。也可以同時(shí)為多個(gè)變量賦值,用逗號(hào)分隔,逐一對(duì)應(yīng)。
例如:a, b, c = 1, 2, 3,最后a是1,b是2,c是3。
不要把賦值語句的等號(hào)等同于數(shù)學(xué)的等號(hào)。
x = 1 x = x + 2
如果從數(shù)學(xué)上理解x = x + 2那無論如何是不成立的,在程序中,賦值語句先計(jì)算右側(cè)的表達(dá)式x + 2,得到結(jié)果3,再賦給變量x。由于x之前的值是1,重新賦值后,x的值變成3。
a = 'ABC'時(shí),Python解釋器干了兩件事情:
1. 在內(nèi)存中創(chuàng)建了一個(gè)‘ABC’的字符串對(duì)象;
2. 在內(nèi)存中創(chuàng)建了一個(gè)名為a的變量,并把它指向'ABC'。
也可以把一個(gè)變量a賦值給另一個(gè)變量b,這個(gè)操作實(shí)際上是將變量b指向變量a所指向的數(shù)據(jù),
例如下面的代碼:
a = 'Jack' b = a a = 'Tom' print(b) print(a)
最后變量b的內(nèi)容到底是'Jack'還是'Tom'?如果從數(shù)學(xué)意義上理解,就會(huì)錯(cuò)誤地得出b和a相同是‘Tom’,但實(shí)際上b的值還是'Jack ‘!
請(qǐng)牢記:Python中的一切都是對(duì)象,變量是對(duì)象的引用!
圖:
執(zhí)行a = ‘Jack’,解釋器創(chuàng)建字符串‘Jack’對(duì)象和變量a,并把a(bǔ)指向‘Jack’對(duì)象;
執(zhí)行b = a,解釋器創(chuàng)建變量b,并且將其指向變量a指向的字符串‘Jack’對(duì)象;
執(zhí)行a = ‘Tom’,解釋器創(chuàng)建字符串‘Tom’對(duì)象,并把a(bǔ)改為指向‘Tom’對(duì)象,與b無關(guān)。
三、常量
常量就是不變的變量,比如常用的數(shù)學(xué)常數(shù)圓周率就是一個(gè)常量。在Python中,通常用全部大寫的變量名表示常量:
PI = 3.14159265359
????但事實(shí)上,從Python語法角度看,PI仍然是一個(gè)變量,因?yàn)镻ython根本沒有任何機(jī)制保證PI不會(huì)被改變。你完全可以給PI賦值為10,不會(huì)彈出任何錯(cuò)誤。所以,用全部大寫的變量名表示常量只是一個(gè)習(xí)慣上的用法。
????常量通常放置在代碼的最上部,并作為全局使用。
四、總結(jié)
? ? 本文基于Python基礎(chǔ),主要介紹了Python基礎(chǔ)中變量和常量的區(qū)別,對(duì)于變量的用法做了詳細(xì)的講解,用豐富的案例 ,代碼效果圖的展示幫助大家更好理解 。
The above is the detailed content of This article will help you understand variables and constants in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

To test the API, you need to use Python's Requests library. The steps are to install the library, send requests, verify responses, set timeouts and retry. First, install the library through pipinstallrequests; then use requests.get() or requests.post() and other methods to send GET or POST requests; then check response.status_code and response.json() to ensure that the return result is in compliance with expectations; finally, add timeout parameters to set the timeout time, and combine the retrying library to achieve automatic retry to enhance stability.

In Python, variables defined inside a function are local variables and are only valid within the function; externally defined are global variables that can be read anywhere. 1. Local variables are destroyed as the function is executed; 2. The function can access global variables but cannot be modified directly, so the global keyword is required; 3. If you want to modify outer function variables in nested functions, you need to use the nonlocal keyword; 4. Variables with the same name do not affect each other in different scopes; 5. Global must be declared when modifying global variables, otherwise UnboundLocalError error will be raised. Understanding these rules helps avoid bugs and write more reliable functions.

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.

How to efficiently handle large JSON files in Python? 1. Use the ijson library to stream and avoid memory overflow through item-by-item parsing; 2. If it is in JSONLines format, you can read it line by line and process it with json.loads(); 3. Or split the large file into small pieces and then process it separately. These methods effectively solve the memory limitation problem and are suitable for different scenarios.

In Python, the method of traversing tuples with for loops includes directly iterating over elements, getting indexes and elements at the same time, and processing nested tuples. 1. Use the for loop directly to access each element in sequence without managing the index; 2. Use enumerate() to get the index and value at the same time. The default index is 0, and the start parameter can also be specified; 3. Nested tuples can be unpacked in the loop, but it is necessary to ensure that the subtuple structure is consistent, otherwise an unpacking error will be raised; in addition, the tuple is immutable and the content cannot be modified in the loop. Unwanted values can be ignored by \_. It is recommended to check whether the tuple is empty before traversing to avoid errors.

Python default parameters are evaluated and fixed values ??when the function is defined, which can cause unexpected problems. Using variable objects such as lists as default parameters will retain modifications, and it is recommended to use None instead; the default parameter scope is the environment variable when defined, and subsequent variable changes will not affect their value; avoid relying on default parameters to save state, and class encapsulation state should be used to ensure function consistency.

Pure functions in Python refer to functions that always return the same output with no side effects given the same input. Its characteristics include: 1. Determinism, that is, the same input always produces the same output; 2. No side effects, that is, no external variables, no input data, and no interaction with the outside world. For example, defadd(a,b):returna b is a pure function because no matter how many times add(2,3) is called, it always returns 5 without changing other content in the program. In contrast, functions that modify global variables or change input parameters are non-pure functions. The advantages of pure functions are: easier to test, more suitable for concurrent execution, cache results to improve performance, and can be well matched with functional programming tools such as map() and filter().
