Python Series Learning Chapter 2 - Basic Grammatical Elements of Python Language


hello, here is Token_w's article, mainly explaining the basic learning of python, I hope it will be helpful to everyone

The Python program says it can memorize it backwards. As a human being, do you want to try to write the reserved words silently?

knowledge points

  • Basic grammatical elements of a program: program format framework, indentation, comments, variables, naming, reserved words, data types, assignment statements, references
  • Basic input and output functions: input(), eval(), print()
  • source code writing style

knowledge map

insert image description here

1. The format framework of the program

1.1 Indentation

  • The Python language uses strict "indentation" to indicate the format framework of the program. Indentation refers to the blank space before the beginning of each line of code, which is used to indicate the inclusion and hierarchical relationship between codes.
  • 1 indent = 4 spaces
  • Indentation is the only means of indicating the framework of the program in the Python language
  • When expressing the meaning of programs such as branches, loops, functions, classes, etc., after the complete statement where reserved words such as if, while, for, def, class, etc. are located, use an English colon (:) after the end and indent after that, indicating that the subsequent code and the adjacent Ownership of unindented statements.
    insert image description here

1.2 Notes

  • Comments are auxiliary text in the code, which will be omitted by the compiler or interpreter, and will not be executed by the computer. It is generally used for programmers to explain the code. The Python language uses # to indicate the beginning of a line of comments, and multi-line comments need to use # at the beginning of each line.
    1.#The first line of the comment
    2.#The second line of the comment
    3.#The third line of the comment
  • Non-comment statements in a Python program will be executed sequentially, and comment statements will be filtered out by the interpreter and not executed. Comments are generally used to indicate the author and copyright information in the code, or to explain the principle and purpose of the code, or to assist program debugging by commenting a single line of code.

2. The name of the syntax element

2.1 Variables

  • A variable is a syntactic element that holds and represents data values ​​and is very common in programs. As the name implies, the value of a variable can be changed and can be modified by assignment (expressed using the equal sign =), for example:
a = 99
a = a + 1
print(a)
# 100

2.2 Naming

  • The Python language allows the use of uppercase letters, lowercase letters, numbers, underscores (_) and Chinese characters and other characters and combinations thereof to name variables, but the first character of the name cannot be a number, there can be no spaces in the middle, and there is no limit to the length
  • Note: Identifiers are case sensitive, python and Python are two different names

2.3 Reserved words

  • Reserved words, also known as keywords, refer to identifiers that are internally defined and reserved for use in a programming language.
  • Programmers writing programs cannot define identifiers that are the same as reserved words.
  • Each programming language has a set of reserved words, which are generally used to form the overall framework of the program, express key values, and have structural and complex semantics.
  • To master a programming language, you must first memorize its corresponding reserved words.

Python 3.x reserved word list (33):
insert image description here

# 输出python关键字列表
import keyword
print(keyword.kwlist)
len(keyword.kwlist)

3. Data type

3.1 Overview of data types

  • The Python language supports a variety of data types, the simplest ones include numeric types and string types, and the slightly more complex ones include tuple types, collection types, list types, dictionary types, etc.

3.2 Numeric types

  • The data type that represents a number or value is called a number type. The Python language provides three types of numbers: integers, floating-point numbers, and complex numbers, which correspond to integers, real numbers, and complex numbers in mathematics.
  • An integer value can be represented in different bases such as decimal, hexadecimal, octal and binary.
    Decimal: 1010

Hexadecimal: 0x3F2

Octal: 0o1762

Binary: 0b001111110010

  • A floating-point number can be represented in normal form with a decimal point, or in scientific notation. For example: floating point number 123.456, the two representations are as follows:
    general form: 123.456

Scientific notation: 1.23456e2

  • The complex number type is consistent with the complex number in mathematics, expressed in the form of a+bj, and has real and imaginary parts.

3.3 Strings

  • In the Python language, a string is one or more characters enclosed by two double quotes " " or single quotes ' '.
  • Two serial number systems for Python strings
    insert image description here
  • If the length of the string is L, the forward increment requires the leftmost character sequence number to be 0, and the rightmost character sequence number is L-1; Decrease from the left, the leftmost character number is -L.
print("对酒当歌,人生几何?"[1])
# '酒'
print("对酒当歌,人生几何?"[-1])
# '?'
  • A substring of a string can be obtained in the format [N: M], and this operation is vividly called slicing. [N: M] Get the consecutive substrings from N to M (but not including M) in the string.
print("对酒当歌,人生几何?"[2:4])
# '当歌'
print("对酒当歌,人生几何?"[5:-2])
# '人生几'
  • The length of the string can be obtained through the len() function provided by Python by default. The length of a Chinese character and a Western character are both recorded as 1.
print(len("对酒当歌,人生几何?"))
# 10
print(len("Hello World"))

4. The statement elements of the program

4.1 Expressions

  • A piece of code that produces or computes a new data value is called an expression. An expression is similar to a calculation formula in mathematics. It is aimed at expressing a single function. After the operation, an operation result is generated. The type of the operation result is determined by the operator or operators.
  • Expressions are generally composed of data and operators, which are an important part of Python statements.

4.2 Assignment statement

  • In the Python language, = means "assignment", that is, after calculating the value on the right side of the equal sign, the result value is assigned to the variable on the left. A statement containing an equal sign (=) is called an "assignment statement" <variable> =
    <expression>

  • Synchronous assignment statement: assign values ​​to multiple variables at the same time
    <variable 1>, ..., <variable N> = <expression 1>, ..., <expression N>

  • Example: Swap the variables x and y

  • With a single assignment, 3 lines of statements are required:

  • That is, cache the original value of x through a temporary variable t, then assign the value of y to x, and then assign the original value of x to y through t.

  • With a synchronous assignment statement, only one line of code is required:
    insert image description here

4.3 References

  • Python programs often use existing function codes outside the current program. This process is called "referencing". The Python language uses the import reserved word to refer to a function library other than the current program, and the usage method is as follows:
    import <function library name>

  • After referencing the function library, use <function library name>.<function name>() to call specific functions.

# 调用turtle库进行绘图操作
import turtle
print(turtle.fd(-200)    #fd()是turtle库中函数)
print(turtle.right(90)   #right()是turtle库中函数)
print(turtle.circle(200) #circle()是turtle库中函数

4.4 Other statements

  • In addition to assignment statements, Python programs also include some other statement types, such as branch statements and loop statements. More branching and looping content will be introduced later. Here we only briefly introduce the basic usage of these two types of statements.

4.5 Branch Statements

  • A branch statement is a statement that controls the running of a program, and its function is to select a program execution path according to a judgment condition. Branch statements include: single branch, two branches and multiple branches.

  • The single branch statement is the simplest branch statement, used as follows:
    if <condition>:

    <statement block>

# 判断输入整数是否在[0,100]之间
num = eval(input("请输入一个整数:"))
if 0 <= num <= 100: # 判断[0,100]
    print("输入整数在0到100之间(含)")

4.6 Loop Statements

  • The loop statement is an important statement to control the running of the program. It is similar to the branch statement to control the execution of the program. Its function is to determine whether a section of the program is executed once or more times according to the judgment conditions. Loop statements include traversal loops and conditional loops.
    while (<condition>):

    <statement block 1>

    <statement block 2>

# 输出10到100步长为3的全部整数
n = 10
while n < 100:
    print(n, end=" ")
    n = n + 3

5. Basic input and output functions

5.1 input() function

  • Before getting user input, the input() function can contain some prompt text
    <variable> = input(<prompt text>)
a = input("请输入一个小数: ")
# 请输入一个小数: 123.456
print(a) # 此时a是字符串"123.456"
# 123.456

5.2 eval() function

  • The **eval(<string>)** function is a very important function in the Python language. It can parse and execute strings in the form of Python expressions, and return the result output
a = eval("1.2 + 3.4")
print(a)
# 4.6
  • The eval() function is often used together with the input() function to obtain the number entered by the user, as follows:
    <variable> = eval(input(<prompt text>))
value = eval(input("请输入要计算的数值: ")) 
# 请输入要计算的数值: 1024.256 
print(value*2)
# 2047.512

5.3 print() function

  • The print() function is used to output the operation results. There are three usages according to the output content.
  • The first one, only for outputting strings, is used as follows:
print(<待输出字符串>)

print(print("你好,来自江南的你"))
# 你好,来自江南的你
  • The second one is only used to output one or more variables, the usage is as follows:
    print(<variable 1>, <variable 2>,…, <variable n>)
value = 123.456
print(value, value, value)
# 123.456 123.456 123.456
  • The third one is used to mix output strings and variable values. The usage is as follows:
    print(<output string template>.format(<variable 1>, <variable 2>,…, <variable n>))
a, b = 123.456, 1024
print("数字{}和数字{}的乘积是{}".format(a, b, a*b))
# 数字123.456和数字1024的乘积是126417.944
  • Assign a value to the end parameter of the print() function
    print(<content to be output>, end="<end of added output>")
a = 24
print(a, end=".")
# 24.
print(a, end="%")
# 24%

6. Example Analysis: Backwards

6.1 Example analysis

  • Computer programs are masters of mechanical memory. Next, we will write a program to obtain user input and output the input content in reverse order. The input and output examples of this program are as follows:
  • Enter: To be or not to be, that's a question. -Shakespeare
  • Output: Abishsha - .noitseuq a s'taht ,eb ot tonro eb oT
  • An implementation is given below, using the positive increment sequence number, using the len() function to set i as the index sequence number of the last character, and then output to the first character one by one.
s = input("请输入一段文本:")
i = len(s) - 1
while i >= 0 :
    print(s[i], end="")
    i = i - 1
  • Give another implementation, use the reverse descending sequence number, first set i to -1, directly index the last character, and then output to the first character one by one.
s = input("请输入一段文本:")
i = -1
while i >= -1 * len(s):
    print(s[i], end="")
    i = i - 1

Summarize

This time, I explained in detail some basic concepts that beginners need to know about Python, introduced the basic syntax elements of Python, explained the format framework of programs, the names of syntax elements, data types, statement elements of programs, basic input and output functions, etc. It gives the thinking and suggestions on the writing style of Python source programs, and helps readers initially establish the basic concepts of writing beautiful programs. Finally, the example of "backwards like a flow" is explained, and the basic grammatical elements of Python are understood and practiced by completing the function of outputting a piece of input text in reverse order.

Guess you like

Origin blog.csdn.net/weixin_61587867/article/details/131897484