Elementary school students learn Python program syntax element analysis in three minutes~Summary notes

Python program syntax element analysis

Foreword: I am in my sophomore year this year and I am trying to learn python. I write a blog in order to better summarize the knowledge. Each time I write a blog, it may take a few hours or more time to summarize the knowledge. If you think the article is helpful to you, You can like and comment on Erlian at the end of the article, and follow my blog to let more people see my article. This article is original by the author. If you need to reprint it, you must get the author's consent.

1.1 Example 1: Temperature conversion

#TempConvert.py
TempStr = input("请输入带有符号的温度值: ")
if TempStr[-1] in ['F','f']:
    C = (eval(TempStr[0:-1])-32)/ 1.8
    print("转换后的温度是{:.2f}C".format(C))
elif TempStr[-1] in ['C','C']:
    F = 1.8*eval(TempStr[0:-1]) + 32
    print("转换后的温度是{:.2f}F".format(F))
else:
    print("输入格式错误")~

1.2 The format framework of the program

The Python language is used “缩进”to indicate the format framework of the program, 缩进which refers to the blank area before the beginning of each line of code, to express the 包含和层次relationship between the codes . Indentation can be Tabachieved by using keys or multiple spaces. It is recommended to use 4 spaces to write the code.

if TempStr[-1] in ['F','f']:
    C = (eval(TempStr[0:-1])-32)/ 1.8~   #4个空格方式

1.3 Notes

注释It can be divided into single-line comments and multi-line comments. Single-line comments start with #, and multi-line comments start and end with "'(3 single quotation marks). For example:

print("谢谢你这么帅,还关注朕")   #这就是单行注释,注释代码内容不运行
print("谢谢你这么美,还关注朕")   
''' 
这就是多行注释,
此行也是注释
'''

Single-line comments are generally sufficient.

1.4 Naming and reserved words

The Python language uses uppercase and lowercase letters, numbers, underline _ and Chinese characters and their combinations to name variables, but the first letter of the name cannot be a number, no spaces can appear in the middle, and the length is unlimited.

python_is_good
_it_is_a_python

33 reserved words that need to be mastered:

Python3's 33 reserved words list
False def if raise None
of import return True elif
in try and else is
while as except lambda with
assert finally nonlocal yield break
for not class from or
continue global pass

It is particularly emphasized here that the 33 reserved words must be written silently!

1.5 String

The character string includes two serial number systems: forward increasing serial number and reverse decreasing serial number. The first row of the following table is reverse, and the third row is forward. When increasing in positive direction, the leftmost character serial number is 0, and the rightmost character The serial number of the character string is L-1. When decreasing backward, the serial number of the rightmost string is -1, and the serial number of the leftmost string is -L. These two methods of indexing characters can be used at the same time. As in the above example of temperature conversion, the third line TempStr[-1]represents the last character string of the TempStr variable.
Pyhton strings can also provide interval access methods, using the [N:M] format to represent strings from N to M (not including M) in the string, and you can mix forward increasing serial numbers and reverse decreasing serial numbers.

-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
H e 1 1 The W The r 1 d
0 1 2 3 4 5 6 7 8 9 10
>>>TempStr = "110C"
>>>print(TempStr[0:-1])
110

TempStr[0:-1]Represents the substring from the 0th character string to the last character (but not including the last character) of the TempStr variable. So the output above is110

1.6 Assignment Statement

There shouldn't be much to say about this. Just like high school, "=" means "assignment", which is simply understood as assigning the value from the right to the left.

TempStr = input("请输入带有符号的温度值: ")

1.7input() function

Use an input() function to get user input from the console. No matter what the user enters in the console, the input() function returns the result as a string.

>>>input("请输入:")
请输入:hello python
'hello python'  #返回值是hello python

1.8 branch statement

way of expression:

  1. if <condition 1>:
  2. elif <condition 2>
  3. else: <statement block N>
if TempStr[-1] in ['F','f']:
elif TempStr[-1] in ['C','c']:
else:

The first line judges whether the last character of TempStr (TempStr[-1]) is in the set of'F' or'f'. If it is, it returns True, otherwise it returns False. Elif is the same as judging if, else The statement has no judgment condition, which means that the statement executed when all the if and elif conditions are not satisfied, that is 'F'、'f'、'C'、'c', the statement is not satisfied , and the user outputs an error.

1.9eval() function

This is relatively simple, just cite two Liezi to understand

>>>x = 1
>>>eval("x + 1")
2
>>>TempStr = "520C"
>>>eval(TempStr[0:-1])
520    #-1是不包含最后一个字符串,返回值520

2.0print() function

The print(<with output string>) output function outputs character information, and it can also output variables in character form. When outputting pure character information, you can directly pass the content to be output to the print() function, as in line 3. When outputting variable values, a formatted output method is required, and the variables to be output are sorted into the desired output format through the format() method, such as the first and second lines.

print("转换后的温度是{:.2f}C".format(C))
print("转换后的温度是{:.2f}F".format(F))
print("输入格式错误")

Insert picture description here
However, what does the above code specifically mean? Originally Xiaobai, the author still talked a lot about it. Xiaobai's mentality is on the verge of collapse. Don't worry, listen to my detailed explanation. First of all, the content in curly brackets {:.2f} indicates the output format of variable C. Simply put, the output value is taken 两位小数点. Just remember it first. The specific reason for using two decimal places will be discussed in the later article. Then why there is format( ), the simple understanding is that the content of the brackets requires units F或者C.

>>>C = 520.1314
>>>print("转换后的温度是{:.2f}C",format(C))
转换后的温度是520.13C  

He said he would be a scumbag for a lifetime, and hey, nothing, the meeting ended.
Insert picture description here

2.1 Loop statement

Loop statement is an important statement that controls the operation of the program. It is similar to the branch statement that controls the execution of the program. Its function is to determine whether a program is executed once or multiple times according to the judgment condition.
Expression:
while (<condition>):
<sentence block 1>

<.sentence block N>

#e1 TempConvert.py
TempStr = input("请输入带有符号的温度值: ")
while TempStr[-1] not in ['N','n']:
if TempStr[-1] in ['F','f']:
    C = (eval(TempStr[0:-1])-32)/ 1.8
    print("转换后的温度是{:.2f}C".format(C))
elif TempStr[-1] in ['C','C']:
    F = 1.8*eval(TempStr[0:-1]) + 32
    print("转换后的温度是{:.2f}F".format(F))
else:
    print("输入格式错误")~

The code has one more line than the temperature conversion

while TempStr[-1] not in ['N','n']:

This line of code determines whether the last character entered by the user (TempStr[-1]) is'N' or'n'. If it is, return False, if not, return True, and continue to execute the following code.
Insert picture description here

2.2 Function

The temperature conversion instance is composed of a sequence expression, and the program is executed from beginning to end in a sequential manner. In actual programming, the specific function code is generally written in a function, which is easy to read and reuse, and the program is better modularized. The function can be understood as a set of packages that express specific function expressions. It is also similar to mathematical functions, which can receive variables and Output the result.

2.3 End

Well, this chapter of this issue is over. If you like this article, you can like, comment, and follow Sanlian at the end of the article, Lao Tie 666! This article is the author's original and the result of the author's labor. Reprinting must be approved by the author. Thank you again for your support and watching, and welcome everyone to communicate and learn python together.
~
~
~
Every time the summary is better than the last time~

Guess you like

Origin blog.csdn.net/A6_107/article/details/106666091