6 variable operations and 33 reserved keywords that must be mastered in Python

Learn Python data science, play games, learn Japanese, and engage in programming all in one package.

The content shared this time is the basic operation of Python variables and reserved keywords.

A variable is a memory location with a name and a value (some data). Variables have unique names that distinguish memory locations. They have the same naming conventions as identifier naming conventions.

In Python it is not necessary to declare a variable (specify the data type) before using it. When creating a variable write a valid name for the variable and use the assignment operator to assign a value to it. The data type of a variable is defined internally according to the type of the value it assigns.

However, in the case of complex code, the program needs to change the corresponding value as the code changes.
insert image description here

Python variables

variable assignment

Variables in Python do not need to be declared or defined up front like many other programming languages. To create a variable, assign a value to it and start using it. Use a single equals sign "=" to complete assignments.

Here n is assigned the value 1, then n can be used in statements or expressions and its value will be replaced.

num = 1

print(num)
1

num
1

Changing the value of n and using it again will replace it with the new value.

n = 10

print(n)
10

n
1000

Python also allows chained assignment, where the same value can be assigned to multiple variables at the same time.

a = b = c = 1
print(a, b, c)
1 1 1

variable type

Variables in many programming languages ​​are statically typed, which means that the variable is initially declared to have a specific data type, and any value assigned to it during its lifetime must always have that type.
insert image description here
Variables in Python are not subject to this restriction, a variable can be assigned a value of one type and then reassigned a value of a different type.

var = 1.5
print(var)
1.5

var = "str"
print(var)
string

object reference

Python is a highly object-oriented language, and almost every piece of data in a program is an object of a specific type or class.

# 创建整数对象、赋值、打印
print(100)
100

# 查看数据类型
type(100)
<class 'int'>

Assignment creates an integer object with the value 100 and assigns the variable n to point to that object.
insert image description here

print(n)
100

type(n)
<class 'int'>

Multiple references to a single object : using other variables for assignment, Python does not create another object, just a new symbolic name or reference m which points to the same object n.

m = n

insert image description here
Creating a new integer and assigning 200 forms a new reference to a separate object .
insert image description here
When an object's reference count drops to zero, it is no longer accessible, and its life cycle ends. Python will eventually notice that it is inaccessible and reclaim the allocated memory so that it can be used for other purposes. In computer terminology this process is called garbage collection .

object identity

Every object created in Python has a number that uniquely identifies it, and there can be no identical identifiers with overlapping lifetimes for two objects. Once an object is garbage collected , the identifier can be used again.

The built-in Python function id() returns an integer identifier for an object. Using the id() function, you can verify that both variables indeed point to the same object. Variable objects have different identities once reassigned.

n = 100
m = n
id(n)
2006284448
id(m)
2006284448

m = 200
id(m)
2006287648

variable name

Variable names in Python can be of any length, consisting of upper and lower case letters (AZ, az), numbers (0-9), and underscore characters (_). The limitation is that variable names can contain numbers, but cannot start with a number.

name = "Mr数据杨"
Age = 36
is_teacher = True
print(name, Age, is_teacher )
Mr数据杨 36 True

Variables also have their own naming conventions.

  • Variables can consist of letters, underscores, and numbers.
  • Variables cannot start with a number.
  • A variable cannot have the same name as a keyword.
  • Variables are case sensitive.
# 官方的命名规则
my_name = "Mr数据杨"

# 小驼峰式命名法
myName = "Mr数据杨"

# 大驼峰式命名法
MyName = "Mr数据杨"

age = 1
Age = 2
aGe = 3
AGE = 4
a_g_e = 5
_age = 6
age_ = 7
_AGE_ = 8

print(age, Age, aGe, AGE, a_g_e, _age, age_, _AGE_)
1 2 3 4 5 6 7 8

Python reserved words

Reserved words in Python. Reserved words cannot be used as variables, so you need to be careful when naming variables.

33 reserved words (keywords)

insert image description here

33 keywords that cannot conflict

Let's see what keywords are there.

import keyword
print(",".join(keyword.kwlist))
FalseNoneTrueandasassertbreakclasscontinuedefdelelifelseexceptfinallyforfromglobalifimportinislambdanonlocalnotorpassraisereturntrywhilewithyield

Don't memorize them deliberately, these will have color prompts that are different from ordinary codes.

  • and: used for expression operations, logical and operations
  • as: for type conversion
  • assert: Assertion, used to determine whether the value of a variable or conditional expression is true
  • break: interrupt the execution of the loop statement
  • class: used to define classes
  • continue: continue to execute the next loop
  • def: used to define functions or methods
  • del: delete the value of a variable or sequence
  • elif: conditional statement combined with if else
  • else: conditional statement conditional statement, used in conjunction with if and elif. Can also be used for exceptions and loops
  • except: including the operation code after catching the exception, used in combination with try and finally
  • finally: used for exception statements. After an exception occurs, the code block contained in finally is always executed. Use with try, except
  • from: used to import modules, used in conjunction with import
  • global: define global variables
  • if: conditional statement, used in combination with else, elif
  • import: used to import modules, used in conjunction with from
  • in: Determines whether the variable exists in the sequence
  • is: Determines whether a variable is an instance of a class
  • lambda: define anonymous function
  • not: used for expression operation, logical NOT operation
  • or: used for expression operations, logical or operations
  • pass: placeholder for empty class, function, method
  • print: print statement
  • raise: exception throwing operation
  • return: used to return the calculation result from the function
  • try: contains statements where exceptions may occur, used in conjunction with except, finally
  • while: loop statement
  • with: Simplified Python statement
  • yield: used to return values ​​sequentially from a function

This list can be viewed at any time by typing help (keywords corresponding to keywords) in the Python interpreter. Reserved words are case sensitive and must be used exactly as shown, except False , None and True are case sensitive.

for = 1
SyntaxError: invalid syntax

Check for reserved words

Use the iskeyword() function to check whether the specified string in Python is a reserved word.

import keyword

print(keyword.iskeyword('yield'))
print(keyword.iskeyword('Yield'))

True
False

Use the in operator to check.

import keyword

print("yield" in keyword.kwlist)
print("Yield" in keyword.kwlist)

True
False

Guess you like

Origin blog.csdn.net/qq_20288327/article/details/123653788