Python from Beginner to Master Chapter 2 (Basic Grammar Elements of Python Language)

1. Basic input and output functions

1. input function

(1) The so-called "input" is to use code to obtain the information entered by the user through the keyboard. In Python, if you want to obtain the information entered by the user on the keyboard, you need to use the input function.

(2) When the program runs to this function, it will wait for the user to input content (whether it is a string, an integer or a floating point number), then obtain it and return it according to the string type . If the user does not enter content for a long time, the program will get stuck at the statement where the function is located.

(3) Usage: <variable>=input(<prompt string>)

(4) Enter the following code in the .py file and run it. Then enter any data in the window, press Enter, and the window will output the data just entered.

# 在窗口输入内容,该内容赋给变量a(窗口会显示提示字符串“请输入:”)
a = input("请输入:")
# 将变量a打印(输出)在窗口
print(a)

2. print function

(1) This function is used to output operation results. It has multiple uses depending on the output content:

①Only used to output a string or a single variable:

        print(<String or variable to be output>)

print("输出的字符串")  # 输出结果为“输出的字符串”
print(10)  # 输出结果为“10”

a = 20
print(a)  # 输出结果为“20”

print([1,2,3,4])  # 输出结果为“[1,2,3,4]”
print(["输出","字符串"])  # 输出结果为“['输出', '字符串']”

②Only used to output one or more variables:

        print(<variable1>,<variable2>,...,<variablen>)

b = 2005.0803
print(b,b,b)

print("输出",b,"字符串")

③ Used to mix output strings and variable values:

        print(<>.format(<variable1>,<variable2>,...,<variablen>))

# 输出字符串模板中采用大括号{}表示一个槽位置,每个槽位置对应format()中的一个变量
a = 2005
b = 803

print("数字{}和数字{}的乘积是{}".format(a,b,a*b))

(2) When the print function outputs text, it will add a newline at the end by default . If you do not want to add this newline at the end, or you want to add other content after outputting the text, you can assign a value to the end parameter of the print function. The usage method is as follows:

        print(<content to be output>,end="<end of added output>")

a = 2005
b = 803

print("数字{}和数字{}的乘积是{}".format(a,b,a*b),end="。")

(3) If you want to mix output strings and variable values, you can also use the formatting operator "%".

①A string containing "%" is called a format string.

② "%" is used with different characters, and different types of data require different formatting characters.

③Example:

# %s是打印字符串的格式化字符
name="小明"
print("我的名字叫 %s,请多多关照!" % name)

# %d是打印整数的格式化字符,“06”表示最少要显示6位数字,少则用0填充
student_no=2212
print("我的学号是 %06d" % student_no)

# %f是打印浮点数的格式化字符,“.02”表示小数点后显示两位数,少则用0填充
price=12.5
weight=21.3
money=266.25
print("苹果单价 %.02f 元/斤,购买 %.02f 斤,需要支付 %.02f 元" % (price, weight, money))

# print("数据比例是 %.02f%%" % scale * 100)是错误的,“*100”将作用于整个字符串,而不是scale
# 要想打印百分号,""内要在打印%的位置前再加一个%
scale=0.1
print("数据比例是 %.02f%%" % (scale * 100))

3. eval function

(1) The role of the eval function: convert the string into a Python expression (that is, remove the outermost quotation marks of the string) , execute the character content after removing the quotation marks according to the Python statement method, and return the value of the expression . This function can be used to dynamically execute Python code to achieve some dynamic functions. Simply put, the results that can only be produced by inputting expressions in the Python terminal can be produced by passing expressions in parameters with the help of this function. .

(2) Treat the string as a valid expression to evaluate and return the calculation result. Enter the following code in the .py file and run it. Then enter any data in the window, press Enter, and the window will Output the data just entered.

input_str = input("请输入一个算术题:")
print(eval(input_str))

(3) Never use eval to directly convert the input result during development . In this way, users can enter terminal commands at will, causing unpredictable consequences.

2. Variables

1. Definition and use of variables

(1) In Python, each variable must be assigned a value before use. The variable will not be created until the variable is assigned a value .

(2) The equal sign "=" is used to assign a value to a variable. The left side of "=" is a variable name, and the right side of "=" is the value stored in the variable.

(3) Unlike C language, Python does not need to declare a type when creating a variable. Python will automatically recognize the data type on the right side of "=".

(4) Example:

①Example 1:

# 定义 qq_number 的变量用来保存 qq 号码
qq_number = "1234567"

# 输出 qq_number 中保存的内容
print(qq_number)

# 定义 qq_password 的变量用来保存 qq 密码
qq_password = "123"

# 输出 qq_password 中保存的内容
print(qq_password)

②Example 2:

# 定义单位重量的价格
price = 8.5

# 定义购买重量
weight = 7.5

# 计算总金额
money = price * weight

# 输出需要支付的总金额
print(money)

③Example 3:

# 定义单位重量的价格
price = 8.5

# 定义购买重量
weight = 7.5

# 计算总金额
money = price * weight
print("返现前需支付:%.2f元" % money)

# 只要有购买行为就返 5 元
money = money - 5
print("返现后需支付:%.2f元" % money)

[1] For this example (Example 3), a total of three variables are defined, namely price, weight, and money.

[2] "money = money - 5" is a variable that has been defined before direct use. The variable name is defined only the first time it appears . If the variable name appears again , the previously defined variable is used directly .

[3] During program development, the values ​​saved in previously defined variables can be modified .

2. Type of variable

(1) Defining variables in Python does not require specifying a type (required in many other high-level languages).

(2) Data types can be divided into numeric and non-numeric types:

①Number type: integer type (int), floating point type (float), Boolean type (bool), complex type (complex).

②Non-numeric types: strings, lists, tuples, and dictionaries.

(3) The type function can output the variable type, as shown in the figure below.

3. Naming of variables

(1) Python uses uppercase letters, lowercase letters, numbers, underscores, Chinese characters and other characters and their combinations for naming, but the first character of the name cannot be a number, there cannot be spaces in the middle of the identifier , and there is no limit on the length. (Identifiers in Python are case-sensitive)

(2) Generally, Chinese and other non-English language characters are not used to name variables.

(3) Variable names cannot have the same name as keywords.

(4) Naming rules can be regarded as a convention, not absolute or mandatory, and the purpose is to increase the recognition and readability of the code. In Python, if a variable name needs to consist of two or more words, it can be named in the following way:

①Use lowercase letters for each word.

② Use underscores to connect words.

③When the variable name consists of two or more words, you can also use camel case naming method to name it.

[1] Little CamelCase nomenclature: The first word starts with a lowercase letter, and the first letter of subsequent words is capitalized.

[2] CamelCase nomenclature: The first letter of each word is capitalized.

(5) When defining variables, in order to ensure the code format, a space should be reserved on the left and right sides of "=".

3. Reserved words (keywords)

Python 3.x version has a total of 35 reserved words. Like other identifiers, Python's reserved words are also case-sensitive. For example, True is a reserved word, but true is not. The latter can be used as an ordinary variable.

and

as

assert

async

await

break

class

continue

def

of the

elif

else

except

talk

finally

for

from

global

if

import

in

is

lambda

None

nonlocal

not

or

pass

raise

return

True

try

while

with

yield

The function of the keyword pass is an empty statement, which is the same as the ";" empty statement in C language.

4. Statement elements of the program

1. Expression

(1) Code fragments that generate or calculate new data values ​​are expressions.

(2) Expressions generally consist of data and operators.

2. Assignment statement

(1) A line of code that assigns a value to a variable is called an assignment statement.

(2) The equal sign "=" is used to assign a value to a variable. The left side of "=" is a variable name, and the right side of "=" is the value stored in the variable. The format is:

        <variable>=<expression>

a = 2005 * 803
print(a)

(3) In Python, you can also assign values ​​to multiple variables at the same time (synchronous assignment statement), the format is:

        <Variable1>,<Variable2>,...,<VariableN>=<Expression1>,<Expression2>,...,<ExpressionN>

a = 1
b = 2

c,d = a,b

print(a,b,c,d)

a,b = b,a  # 使用同步赋值语句还可以直接进行值交换
print(a,b,c,d)

3. Reference (import of module/library)

(1) Python programs often use existing function codes outside the current program. This method is called "reference".

(2) The concept of module:

①Every Python source code file ending with the extension py is a module.

②The module name is also an identifier and needs to comply with the naming rules of identifiers.

③The global variables, functions, and classes defined in the module are all tools provided for direct use by the outside world.

④ A module is like a toolkit. If you want to use the tools in this toolkit, you need to import the module first.

(3) Three ways to import modules:

①import import:

[1] After importing, use the tools (global variables, functions, classes) provided by the module through "module name.".

[2] If the name of the module is too long, you can use as to specify the name of the module to facilitate use in the code.

        import module name 1 as module alias

import hm_01_测试模块1 as DogModule
import hm_02_测试模块2 as CatModule

DogModule.say_hello()
CatModule.say_hello()

dog = DogModule.Dog()
print(dog)

cat = CatModule.Cat()
print(cat)

②from...import import:

[1] If you want to import some tools from a certain module, you can use from...import.

        from module name import tool name

[2] "Import module name" imports all the tools in the module at one time, and this import method requires the module name/alias to access the tools; "from...import" does not require "module name." To access tools, you can directly use the tools provided by the module.

from hm_01_测试模块1 import say_hello

say_hello()

③from...import *Import:

[1] Import all tools from modules.

        from module name import *

[2] This method is not recommended because there is no prompt for duplicate function names, making it difficult to troubleshoot problems.

(4) If two modules have functions with the same name , the function imported from the module later will overwrite the function imported first.

① During development, the import code should be written at the top of the code to make it easier to detect conflicts in time.

② Once a conflict is found, you can use the as keyword to give an alias to one of the tools.

# from hm_01_测试模块1 import say_hello
from hm_02_测试模块2 import say_hello as module2_say_hello
from hm_01_测试模块1 import say_hello

say_hello()
module2_say_hello()

(5) Module search order: Search for the file with the specified module name in the current directory. If there is one, import it directly. If there is no file, search the system directory again.

① When naming the file, do not name it the same as the system module file.

②Every module in Python has a built-in attribute "__file__" to view the full path of the module.

(6) In principle, every file should be importable. An independent Python file is a module.

(7) When importing a file, all codes in the file without any indentation will be executed. In actual development, each module is developed independently, and most of them have dedicated personnel in charge. Developers usually add some test code under the module. The test code is only used within the module and does not need to be executed when it is imported into other files. , the "__name__" attribute is required to implement the test code function.

①The "__name__" attribute can make it so that the code of the test module is only run under test conditions and will not be executed when it is imported .

② "__name__" is a built-in attribute of Python, recording a string: if it is imported from other files, "__name__" is the module name; if it is the currently executing program, "__name__" is "__main__".

③You will see codes in the following format in many Python files:

# 注意:直接执行的代码不是向外界提供的工具!

def say_hello():
    print("你好你好,我是 say hello")

# 如果直接执行模块,__name__ == __main__
if __name__ == "__main__":
    print(__name__)

    # 文件被导入时,能够直接执行的代码不需要被执行!
    print("小明开发的模块")
    say_hello()

(8) Package:

①A package is a special directory containing multiple modules , and there is a special file __init__.py in the directory.

②The naming method of the package name is consistent with the variable name.

③Use "import package name" to import all modules in the package at one time.

④Case exercise:

[1] Create a new hm_message package.

Note: The location of the test file in the picture is wrong. The test file should be in the same (same level) folder as the "hm_message" directory.

[2] In the directory, create two new files send_message and receive_message.

[3] Define a send function in the send_message file.

[4] Define a receive function in the receive_message file.

[5] To use the modules in the package externally, you need to specify the module list provided to the outside world in __init__.py. ("." represents the current directory)

[6] Directly import the hm_message package externally and use the tools in it.

4. Branch statement

(1) The definition of judgment: If the conditions are met, you can do something; if the conditions are not met, do another thing, or do nothing.

(2) Judgment statements are also called "branch statements". It is precisely because of judgments that the program has many branches.

(3) Single branch statement:

        if <condition>:

                <statement block>

①The indentation of the code is one tab key or 4 spaces.

② Any statement that can produce True or False can be used as a judgment condition. When the condition is True (true), the content in the statement block is executed.

③Example:

# 定义年龄变量
age = 18

# 判断是否满18岁
# if 语句以及缩进部分的代码是一个完整的代码块
if age >=18:
    print("已成年!")

# 这条语句无论是否满足成年条件都会执行
print("年龄为%d" % age)

(4) Two-branch statement:

        if <condition>:

                <statement block>

        else:

                <statement block>

# 定义年龄变量
age = 18

# 判断是否满18岁
# if 语句以及缩进部分的代码是一个完整的代码块
if age >=18:
    print("已成年!")
else:
    print("未成年")

# 这条语句无论是否满足成年条件都会执行
print("年龄为%d" % age)

5. Loop statement

(1) Similar to branch statements that control program execution, the function of loop statements is to determine whether a piece of code needs to be executed one or more times based on judgment conditions.

(2) Loop statements include traversal loops and conditional loops.

(3) Conditional loop:

        while(<condition>):

                <Statement block 1>

        <Statement block 2>

① When the condition is True (true), execute statement block 1, and then judge the condition again. When the condition is False (false), exit the loop and execute statement block 2.

②Conditional loops are generally used like this: (the while statement and the indented part are a complete code block)

Initial condition setup - usually a counter for repeated execution

while condition (to determine whether the counter reaches the target number of times):

        What to do when the conditions are met 1

        When the conditions are met, do things 2

        What to do when the conditions are met 3

        ...(omission)...

    

        Process condition (counter + 1)

Note: After the loop ends, the value of the previously defined counter condition still exists.

③Example:

# 1. 定义重复次数计数器
i = 1

# 2. 使用 while 判断条件
while i <= 5:
    # 要重复执行的代码
    print("Hello Python")

    # 处理计数器 i
    i = i + 1

print("循环结束后的 i = %d" % i)

おすすめ

転載: blog.csdn.net/Zevalin/article/details/135367515