Python basic study notes (2): Python installation and simple syntax

Let's start learning Python formally, first start installing Python:

1. Install Python on Windows

Installing Python on Windows   is as simple as installing ordinary software, just click "Next" after downloading the installation package.

1.1. Download the installation package

Python installation package download address: https://www.python.org/downloads/

Open the link, you can see that there are two versions of Python, Python 3.x and Python 2.x, as shown in the following figure:

It is recommended that beginners use Python 3.x directly. As of now (2020-03-28), the latest version of Python is 3.8.x, which is used to demonstrate the installation process of Python under Windows. Click the version number or the "Download" button in the above picture to enter the download page of the corresponding version, and scroll to the end to see the Python installation packages for each platform.

Explanation of prefixes:

  • Windows x86-64The 64-bit Python installer starts with ;
  • Windows x86The 32-bit Python installer starts with .


Description of suffixes:

  • embeddable zip fileThe green free installation version of the presentation .zipformat can be directly embedded (integrated) into other applications;
  • executable installerIndicates .exethe format of the executable program, which is a complete offline installation package, generally select this;
  • web-based installerIndicates that it was installed through the network, that is to say, what is downloaded is an empty shell, and the real Python installation package needs to be downloaded online during the installation process.

Here I choose "Windows x86-64 executable installer", that is, a complete 64-bit offline installation package. Double-click the downloaded python-3.8.1-amd64.exe to start installing Python officially.

1.2. Installation Wizard

As shown below:

Python installation wizard

Please check it as much as possible Add Python 3.8 to PATH, so that the directory where the Python command tool is located can be added to the system Path environment variable, which will be very convenient for developing programs or running Python commands in the future.

Python supports two installation methods, default installation and custom installation:

  • The default installation will check all components and install them on the C drive;
  • Custom installation can manually select the components to be installed and install them to other drive letters.


Here we choose custom installation and install Python to a common directory to avoid too many files on the C drive. Click "Customize installation" to enter the next step and select the Python components to be installed.
 

Select the Python components to install

If there are no special requirements, just keep the default, that is, check all, click "Next" to continue, and select the installation directory.
 

Select the installation directory
Select your usual installation directory, click "Install", and wait for a few minutes to complete the installation.

1.3. Installation complete test

After the installation is complete, open the Windows command line program (command prompt), enter the command in the window python(note that the letters pare lowercase), if the version information of Python appears and the command prompt appears >>>, it means that the installation is successful, as follows As shown in the figure.

run python command
Running the python command starts the python interactive programming environment. We can >>>enter the code later and see the execution result immediately. Please see the following example.


Press Ctrl+Zthe shortcut key or enter the exit() command to exit the interactive programming environment and return to the Windows command line program.

2. Python syntax


2.1.Python comments and garbled characters

2.1.1. Single-line comments

Single-line comments start with #, and everything on the right of # is used as an explanation, not the actual program to be executed, and serves as an auxiliary explanation

# Comment content

#Everything from the pound sign until the end of the line is a comment. When encountered by the Python interpreter #, the entire line following it is ignored.

When explaining the function of multiple lines of code , the comment is generally placed on the previous line of the code, for example:

#使用print输出字符串
print("Hello World!")
print("Python语言中文网")
print("http://c.biancheng.net/python/")
#使用 print输出数字
print(100)
print( 3 + 100 * 2)
print( (3 + 100) * 2 )

When explaining the function of a single line of code , comments are generally placed on the right side of the code, for example:

print("http://c.biancheng.net/python/")  #输出Python教程的地址
print( 36.7 * 14.5 )  #输出乘积
print( 100 % 7 )  #输出余数

2.1.2. Multi-line comments

Multi-line comments can write multi-line functional descriptions, which refer to the content of multiple lines (including one line) in a one-time comment program.

Python uses three consecutive single quotes ''' or three consecutive double quotes """ to comment multi-line content. The specific format is as follows:

'''
使用 3 个单引号分别作为注释的开头和结尾
可以一次性注释多行内容
这里面的内容全部是注释内容
'''

or

"""
使用 3 个双引号分别作为注释的开头和结尾
可以一次性注释多行内容
这里面的内容全部是注释内容
"""

Multi-line comments are usually used to add copyright or functional description information to Python files, modules, classes, or functions.

Precautions

1) Python multi-line comments do not support nesting, so the following writing is wrong:

'''
外层注释
    '''
    内层注释
    '''
'''

2) Regardless of whether it is a multi-line comment or a single-line comment, when comment characters appear as part of a string, they can no longer be regarded as comment marks, but should be regarded as part of normal code, for example:

print('''Hello,World!''')
print("""http://c.biancheng.net/cplus/""")
print("#是单行注释的开始")

operation result:

Hello, World!
http://c.biancheng.net/cplus/
# is the beginning of a single-line comment

For the first two lines of code, Python does not treat the three quotation marks here as multi-line comments, but as the beginning and end of the string. For the third line of code, Python does not treat the pound sign as a single-line comment, but as part of the string.

2.1.3. Python garbled problem

Since the Python source code is also a text file, when your source code contains Chinese, you need to specify the UTF-8 encoding when saving the source code. When the Python interpreter reads the source code, in order to make it read in UTF-8 encoding, we usually write these two lines at the beginning of the file:

# -*- coding:utf-8 -*-
 
# coding=utf-8

2.2.Python indentation rules

Unlike other programming languages ​​(such as  Java and C) that use curly braces "{}" to separate code blocks, Python  uses code indentation and colons (:) to distinguish levels between code blocks.
In Python, for class definitions, function definitions, flow control statements, exception handling statements, etc., the colon at the end of the line and the indentation of the next line indicate the beginning of the next code block, while the end of the indentation indicates the end of this code block Finish.
Note that the indentation of the code in Python can be achieved by using the space or Tab key. But no matter whether you type the space manually or use the Tab key, the length of 4 spaces is usually used as an indentation amount (by default, a Tab key represents 4 spaces). For example, in the following Python code (involving knowledge that has not been learned so far, beginners do not need to understand the meaning of the code, they only need to understand the indentation rules of the code block):

height=float(input("输入身高:")) #输入身高
weight=float(input("输入体重:")) #输入体重
bmi=weight/(height*height)       #计算BMI指数
#判断身材是否合理
if bmi<18.5:
    #下面 2 行同属于 if 分支语句中包含的代码,因此属于同一作用域
    print("BMI指数为:"+str(bmi)) #输出BMI指数
    print("体重过轻")
if bmi>=18.5 and bmi<24.9:
    print("BMI指数为:"+str(bmi)) #输出BMI指数
    print("正常范围,注意保持")
if bmi>=24.9 and bmi<29.9:
    print("BMI指数为:"+str(bmi)) #输出BMI指数
    print("体重过重")
if bmi>=29.9:
    print(BMI指数为:"+str(bmi)) #输出BMI指数
    print("肥胖")

Python has very strict requirements on code indentation. The indentation of code blocks at the same level must be the same, otherwise the interpreter will report a SyntaxError exception.

For the Python indentation rules, beginners can understand that Python requires that all lines of code belonging to the same scope must have the same indentation amount, but there is no hard and fast rule on the specific indentation amount.

2.3.Python Coding Specifications

Python adopts PEP 8 as the coding specification, where PEP is the abbreviation of Python Enhancement Proposal (Python Enhancement Proposal), and 8 represents the style guide for Python code. The following is just a list of some coding rules that beginners in PEP 8 should strictly abide by:

2.3.1. import statement

Each import statement imports only one module, try to avoid importing multiple modules at once, for example:

#推荐
import os
import sys
#不推荐
import os,sys

The meaning and usage of import will be introduced later, so there is no need to delve into it here.

2.3.2. Do not add a semicolon at the end of the line, and do not use a semicolon to put two commands on the same line

For example:

#不推荐
height=float(input("输入身高:")) ; weight=fioat(input("输入体重:")) ;

2.3.3. It is recommended that each line should not exceed 80 characters

If it exceeds, it is recommended to use parentheses to implicitly connect multiple lines of content, and it is not recommended to use backslash \ for connection. For example, if a string text cannot be completely displayed in one line, you can use parentheses to display it separately, the code is as follows:

#推荐
s=("C语言中文网是中国领先的C语言程序设计专业网站,"
"提供C语言入门经典教程、C语言编译器、C语言函数手册等。")
#不推荐
s="C语言中文网是中国领先的C语言程序设计专业网站,\
提供C语言入门经典教程、C语言编译器、C语言函数手册等。"

Note that this programming specification applies to absolutely most cases, except for the following 2 cases:

  • The statement to import a module is too long.
  • The URL in the comment.

2.3.4. Using necessary blank lines can increase the readability of the code

Usually there are two blank lines between top-level definitions (such as function or class definitions), and one blank line between method definitions, and one blank line can also be used to separate certain functions. For example, in the code on the right side of Figure 1, the function of the if judgment statement is different from that of the previous code, so a blank line can be used here to separate.

2.3.5. Use spaces for necessary separation

In general, spaces are recommended for separation between operators, between function parameters, and on both sides of commas.

2.4. Variables and types


2.4.1. Definition of variables

In Python, to store a piece of data, you need something called a variable:

For example:

num1=10

num2=8

result=num1+num2

A variable is an amount that has no fixed value, is expressed in non-numeric symbols, and can be changed.

Three elements of a variable: the name of the variable, the type of the variable, and the value of the variable

2.4.2. Types of variables

In order to make full use of memory space and manage memory more efficiently, there are different types of variables, as shown in the figure:

a. Integer

Python can handle integers of any size, including negative integers of course. The representation in the program is exactly the same as that in mathematics, for example: 1, 100, -8, 0, and so on.

Since computers use binary, it is sometimes convenient to represent integers in hexadecimal. Hexadecimal is generally represented by numbers 0 to 9 and letters A to F (or a~f), where: A~F means 10~15.

b. Floating point number

Floating-point numbers are also decimal numbers. The reason why they are called floating-point numbers is that when expressed in scientific notation, the position of the decimal point of a floating-point number is variable. For example, 1.23x109 and 12.3x109 are completely equal. Floating point numbers can be written mathematically, such as 1.23, 3.14, -9.01, and so on.

For very large or small floating-point numbers, you must use scientific notation, replace 10 with e, 1.23x109 is 1.23e9, or 12.3e8, 0.000012 can be written as 1.2e-5, and so on.

Note : Integers and floating-point numbers are stored differently in the computer. Integer operations are always accurate (is division also accurate? Yes!), while floating-point operations may have rounding errors .

c.string

A string is any text enclosed in single quotes ' or double quotes " , such as 'abc', "xyz" and so on. Please note that single quotes ' or double quotes " are just a representation, not part of the string itself , therefore, the string 'abc' has only 3 characters a, b, c. If the single quote ' itself is also a character, it can be enclosed in double quotes  "", for example, the characters contained in "I'm OK" are I, ', m, space, O, K these 6 characters.

What if the string contains both ' and "? You can use the escape character \ to identify it, for example: ' I\'m \"OK\"!" The string content represented by 'I\'m \"OK\"!' is: I'm "OK"!

The escape character \ can escape many characters, such as \n means newline, \t means tab character, and the character \ itself must be escaped, so the character represented by \\ is \, which can be used in the Python interactive command line with print () print the string to see. If there are many characters in the string that need to be escaped, you need to add a lot of \. For simplicity, Python also allows r'' to indicate that the internal string of '' is not escaped by default.

#普通含有转义的字符串
text="1 E:/Code/PycharmProjects/QtDemo/ToolsList\__pycache__\start.cpython-36.pyc \r\n"
print(text)
 
#输出如下:
#E:/Code/PycharmProjects/QtDemo/ToolsList__pycache__\start.cpython-36.pyc 
#<空行>
 
#在python中使用r来处理常量,强制不转义。
text=r"1 E:/Code/PycharmProjects/QtDemo/ToolsList\__pycache__\start.cpython-36.pyc \r\n"
print(text)

#The output is as follows:
#E:/Code/PycharmProjects/QtDemo/ToolsList__pycache__\start.cpython-36.pyc \r\n

If there are many newlines inside the string, it is not easy to read in one line with \n. For simplicity, Python allows the format of '''...''' to represent multi-line content.

print('''line1

line2

line3'')

d. Boolean value

The expression of Boolean value and Boolean algebra is exactly the same. A Boolean value has only two values ​​of True and False, either True or False. can be calculated by Boolean operations

Boolean values ​​can use and, or, and not operations.

The and operation is an AND operation, only if all are True, the result of the and operation is True

e. Null value

A null value is a special value in Python, represented by None . None cannot be understood as 0, because 0 is meaningful, and None is a special null value. In addition, Python also provides a variety of data types such as lists and dictionaries, and also allows the creation of custom data types, which we will continue to talk about later.

How to know the type of a variable?

In python, as long as a variable is defined and it has data, its type has been determined. We developers do not need to take the initiative to explain its type, the system will automatically identify it, and you can use type (the name of the variable) to see the type of the variable.

2.4.3. Common data type conversion

function

illustrate

int(x [,base ])

convert x to an integer

long(x [,base ])

Convert x to a long integer

float(x )

Convert x to a float

complex(real [,imag ])

create a plural

str(x )

convert the object x to a string

repr(x )

Convert the object x to an expression string

eval(str )

Evaluates a valid Python expression in a string and returns an object

tuple(s )

convert the sequence s to a tuple

list(s )

convert the sequence s to a list

chr(x )

Convert an integer to a character

unichr(x )

Convert an integer to a Unicode character

ord(x )

converts a character to its integer value

hex(x )

Convert an integer to a hexadecimal string

oct(x )

converts an integer to an octal string

2.5. Identifiers and keywords

2.5.1 Identifiers

Some symbols and names customized by developers in the program, identifiers are defined by themselves, such as variable names, function names, etc.

a. Rules for identifiers : identifiers are composed of letters, underscores, and numbers, and numbers cannot begin with a number. Cannot have special symbols: \ , / , ; , #

Identifiers in python are case sensitive:

Python≠python

b. Naming rules :

  • See the name and know the meaning

Give a meaningful name, and try to know what it means at a glance (to improve code readability) For example:

The name is defined as name

Students are defined as student

  • CamelCase
  1. Lower camel case: The first word begins with a lowercase letter; the second word begins with a capital letter, for example: myName, aDog  
  2. Upper camel case: The first letter of each word is capitalized, for example: FirstName, LastName
  3. Underscore nomenclature: Another popular nomenclature is to use an underscore "_" to connect all words, such as send_buf

2.5.2. Keywords

Python has some identifiers with special functions, which are called keywords

The keyword is already used by python, so developers are not allowed to define identifiers with the same name as the keyword

You can use the following command to view the keywords of python in the current system:

import keyword

keyword.kwlist

 Output result:

Guess you like

Origin blog.csdn.net/u012998680/article/details/105162112