[Selected] Python introductory tutorial, learn Python programming in 30 minutes! (This article covers all the knowledge points for getting started with Python, collect it first and then watch it)

Preface

This is a basic Python tutorial for beginners. As long as you read it carefully, you can quickly learn Python in 30 minutes.

The knowledge points explained in this introductory Python tutorial include: setting up a Python programming environment, getting started with basic Python operations, Python data types, Python statements and functions.

Front row tip: There is a CSDN exclusive welfare seed package at the end of the article!

Python environment download and configuration

1. Install and download the corresponding version from the Python official website according to the Windows version (64-bit/32-bit), as shown in Figure 1.
Insert image description here
Official download website: https://www.python.org/

2. After the download is completed, double-click the file to run the installation program to install Python, as shown in Figure 2:
Insert image description here
Note that you need to check the "Add Python 3.6 to PATH" option and click Click the "Customize installation" option. This option is used to add Python 3.6 to the system path. Checking this option will make future operations very convenient; if you do not check this option, you need to manually add the path to the system environment variable.

3. Check all options in the pop-up tab and click the "Next" button, as shown in Figure 3.
Insert image description here
4. The option "Documentation" indicates the help documentation for installing Python; the option "pip" indicates the installation of a third-party package management tool for Python; the option "tcl/tk and IDLE" indicates the installation of integrated development of Python Environment; the option "Python test suite" means to install Python's standard test suite, and the last two options mean to allow version updates.

Keep the default checked state, click the "Browse" button, and select the installation path, as shown in Figure 4.
Insert image description here
5. Click the "Install" button until the installation is completed.

After installation, bring up the command prompt and enter "python" to check whether the installation is successful. If Python is installed successfully, the interface shown in Figure 5 will appear, that is, after entering "python", you will see the ">>" symbol.
Insert image description here

Commonly used IDE——PyCharm

After installing the Python3.6 environment, you also need to configure a programmer-specific tool, namely PyCharm, which is a multi-functional IDE (integrated development environment) suitable for development. Download the community version (free version), The download address is
http://www.jetbrains.com/pycharm/download/#section=windows (see Figure 6):
Insert image description here
PyCharm is very easy to use. Libraries can be downloaded, installed and managed through PyCharm.

Commonly used IDE——Anaconda

Anaconda is an IDE specifically used for statistics and machine learning. It integrates Python and many basic libraries. If the business scenario is statistics and machine learning, then you only need to install Anaconda, which saves many complex configuration processes.

The official download address of Anaconda is:
https://www.anaconda.com/download/, see Figure 7:
Insert image description here
Download by default here The version is 64-bit. If you need the 32-bit version, you can click the text link under the "Download" button.

There is no need to install Python in advance to use Anaconda. It can be run after installation: call the run window through the shortcut key [Win+R], enter "ipython jupyter", and then click the "OK" button (see Figure 8).
Insert image description here

Getting started with Python operations

Write your first Python code

After running PyCharm, you need to create a new plan first, click the "Create New Project" option (see Figure 9):
Insert image description here
Set the Location (path) and Interpreter (translator), here Select the original Python translator, and then click the "Create" button in the lower right corner, as shown in Figure 10:
Insert image description here
After creating a new Project, right-click the mouse in the project window on the left , select the "New" ➔ "Python File" command in the shortcut menu to create a new Python file (see Figure 11).
Insert image description here
Set the Name (file name) and click the OK button in the lower right corner (see Figure 12).
Insert image description here

After creating a new file, the blank area on the right is the code editing area (see Figure 13).
Insert image description here
Let’s start with “Hello World”! Enter print('Hello, World!') in the editing area. print() is a printing function that prints the text in brackets in the immediate window.

Then place the mouse cursor on the right side of the bracket, right-click the mouse, and select the "Run 'test'" command in the shortcut menu, where test in single quotes is the current file name. Be sure to pay attention to the file name to be run and the file to be run. Keep the name consistent. After running, you can observe that "Hello, World!" is printed in the immediate window, as shown in Figure 14.
Insert image description here

Python basic operations

Python annotations

The purpose of comments is to allow readers to easily understand the meaning of each line of code, and also to facilitate later code maintenance. In Python, single-line comments begin with a # sign, as shown below:

#First comment

print(‘Hello, World!’)#Second comment

Python's multi-line comments are enclosed in two triple quotes '', as shown below:

'''
第一行注释
第二行注释
'''
print('Hello,World!')

Python lines and indentation

The most distinctive feature of Python is the use of indentation to represent code blocks without the need for braces. The number of indented spaces is variable, but statements in the same code block must contain the same number of indented spaces. Inconsistent indentation will cause code running errors.

An example of correct indentation is as follows:

if True:
 print("True")
else
 print("False")

Examples of incorrect indentation include:

if True:

print("True")

else:

print("False")

multi-line statement

Python usually writes one statement per line, but if the statement is very long, you can use backslash (\) to implement a multi-line statement.

weekdays ="Little Robert asked his mother for two cents.\

‘What did you do with the money I gave you yesterday?’"

print(weekdays)

The output here is "Little Robert asked his mother for two cents. 'What did you do with the money I gave you yesterday?'".

Wait for user input

The input() function in Python is used to interact with the user, as shown below:

print("Who are you?")
you = input()
print("Hello!")
print(you)

At this time, the running result is "Who are you?".

When the user enters Lingyi and then presses the [Enter] key, the program will continue to run, and the output results are as follows:

Hello!

Lingyi

variable

variable assignment

Enter the following code in the editing area:

a = 42

print(a)

Note: Python variables do not need to be declared in advance. The variables are declared when assigning values.

Variable naming

Python has its own keywords (reserved words), and any variable name cannot be the same as them. A keyword module is provided in Python's standard library, which can check all keywords of the current version, as shown below:

import keyword

keyword.kwlist

Python data types

There are 6 major data types in Python: number, string, list, tuple, sets, and dictionary.

number

Python 3 supports 4 types of numbers: int (integer type), float (floating point type), bool (Boolean type), and complex (plural type).

In Python 3 you can use the type() function to view numeric types as shown below.

a=1 b=3.14 c=True

print(type(a)) print(type(b)) print(type©)

Output result<class'int>> Output result<class'float>> Output result<class'bool>

The operation types supported by Python3 include addition, subtraction, division, integer division, remainder, multiplication and exponentiation:

print((3+1)) #加法运算,输出结果是 4
print((8.4-3)) #减法运算,输出结果是5.4
print(15/4) #除法运算,输出结果是 3.75
print(15//4) #整除运算,输出结果是 3
print(15%4) #取余运算,输出结果是 3
print(2*3) #乘法运算,输出结果是 6
print(2**3) #乘方运算,输出结果是 8

string

A string is the text between single quotes, double quotes, and triple quotes. Example of single quotes: print('welcome to hangzhou'), where all spaces and tabs are retained as they are. The functions of single quotes and double quotes are actually the same, but when the quotes contain single quotes, the quotes need to use double quotes, for example: print ("what’s your name?"). Triple quotes can indicate a multi-line string, and single and double quotes can be used freely within triple quotes, as shown below:

print(‘’'Mike:Hi,How are you?

LiMing:Fine,Thank you!and you?

Mike:I’m fine,too!‘’')

If you want to use the single quote itself in a single-quoted string and the double quote itself in a double-quoted string, you need to resort to the escape character (\), as shown below:

print(‘whar’s your name?’)

#The output is as follows: whar’s your name?

Note: In a string, a single slash at the end of a line indicates continuation on the next line, rather than starting a new line. In addition, double backslashes (\) can be used to represent the backslash itself, and \n represents a newline character. .

If you want to indicate that some string does not require special processing using escape characters, you need to specify a raw string. The original string is specified by prefixing the string with r or R. For example, if you need to output \n as it is instead of wrapping it, the code is as follows:

print(r"Newlines are indicated by \n")

#The output result is Newlines are indicated by \n

The interception format of the string is as follows:

String constant [start_index:end_index+1]

Here is an explanation of why 1 is added: The interception of the string starts from start_index and ends at end_index, which is what everyone often understands as left closing and right opening, as shown below:

str = 'Lingyi'
print(str[0]) #输出结果为L
print(str[1:4]) #输出结果为ing
print(str[-1]) #输出结果为i

Try the following code:

num = 1
string = '1'
print(num+string)

At this time, an error will be reported when running the program. The error message is as follows. Why?

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

String (string) is just a data type in Python. The following statement uses single quotes on the right side when assigning values. The data type is string (string).

string = ‘1’

The data type of the following statement is integer.

num = 1

Operations cannot be performed between different data types. However, different data types can be converted to each other. The above code can run normally after modification. The modified code is as follows:

num = 1
string = '1'
num2 = int(string)
print(num+num2)

Note that the "+" sign used in the middle of a string is a connector, and the "+" sign used in the middle of a value is an operator: int() converts the value or text in parentheses into an integer data type.

After is run, the result printed in the immediate window is 2, as shown in Figure 15.
Insert image description here
The four basic operations are as follows:

a = 1
b = 2
c = a+b
print(c)

Because both sides of the addition are numerical, the "+" sign is the operator at this time, and the results are as follows:

3

Both sides of the addition are character data, and the "+" sign is the connector:

a = 1
b = 2
c = 'a'+'b'
print(c)

The running results are as follows:

ab

list

A Python list is an ordered collection of arbitrary objects. The list is written in square brackets [] and the elements are separated by commas. Any object here can be either a list, a nested list, or a string, as shown below:

list = [“Python”,12,[1,2,3],3.14,True]

print(list)#The operation result is [‘Python’, 12, [1, 2, 3], 3.14, True]

The elements in each list (list is a variable customized by the author) start counting from 0. The following code can select the first element in the list:

list = [1,2,3,4]
print(list[0])
#运行结果为1

The remove method can be used to delete the list. You only need to add a period after the variable name to call it easily. PyCharm has an automatic association function. Select the target method or function and press the [Tab] key to quickly type, such as As shown in Figure 16:
Insert image description here
The following code is used to delete the third element and print the result using print. The remove method is used to delete elements of the list:

list.remove(3)

print(list)#The operation result is [1, 2, 4]

tuple

A tuple is similar to a list, except that its elements cannot be modified. Tuples are written in parentheses (), and the elements are separated by commas, as shown below:

tuple = ['abc',76,'ly',898,5.2]
print(tuple[1:3])
#运行结果是[76,'ly']

gather

A set is an unordered sequence of non-repeating elements. You can use curly brackets {} or the set() function to create a set. It should be noted that an empty set must be created using the set() function instead of braces {}, because braces {} are used to create an empty dictionary, as shown below:

age = {18,19,18,20,21,20}
print(age)
#运行结果是{18, 19, 20, 21}

dictionary

The dictionary is a mutable container model and can store any type of object, marked with {}. A dictionary is an unordered collection of key-value pairs with the following format:

dic = {key1 : value1, key2:value2}

Next, create a dictionary with the following code:

information = {
 'name':'liming',
 'age':'24'
}
print(information)
#运行结果是{'name': 'liming', 'age': '24'}

Where name is a key and limbing is a value.

When adding data to the dictionary, you can use the following methods:

information['sex'] = 'boy'
print(information)
#运行结果是{'name': 'liming', 'age': '24', 'sex': 'boy'}

When deleting data from the dictionary, you can use the del function. The code is as follows:

del information['age']
print(information)
#运行结果是{'name': 'liming', 'sex': 'boy'}

Python statements and functions

Conditional statements

Next, perform the login verification operation. First assign a value to the variable password, and then determine whether the password (password) is correct. If it is correct, it will print "login success!" (Login successful!), if it is wrong, it will print "wrong password" (wrong password):

password = '12345'
if password == '12345':
 print('login sucess!')
else
 print('wrong password')

In Python, you can use "==" two equal signs to determine whether they are equal (a single equal sign is an assignment).

The syntax of the conditional statement is as follows:

if judgment condition:

Execute statement...

else:

Execute statement...

loop statement

Pay attention to indentation in Python. Conditional statements use indentation to determine the ownership of the executed statement.

The for statement is used below to implement the accumulation of 1 to 9:

sum = 0;
for i in range(1,10,1):#不包含 10,实际为1-9
 sum = i + sum
print(sum)
#运行结果是45

where range represents the range, i starts iterating from 1 (the 1st parameter), adding 1 (the 3rd parameter) each time, until i becomes 10 (the 2nd parameter), so it will not be executed when i=10 statement, the for loop is 9 iterations. The # sign represents a comment, and the text after the # sign will not be executed. In PyCharm, if you want to comment the code, you can select the code and press the key combination [Ctrl+/].

The syntax for for is as follows:

for iteration variable in number of iterations:

Execute statement...

If it is a list or dictionary, there is no need to use the range() function. Use the list or dictionary directly. At this time, i represents the element in the list or dictionary. The code is as follows:

list = {1,2,3,4}
for i in list:
 print(i)

The running results are as follows:

1

2

3

4

function

Among the functions just touched, print() is a function that prints out the results, and int() is a function that converts the string type into a data type. Functions like this are collectively called built-in functions, and built-in functions can be called directly.

Where there is an inside, there is an outside. External functions are actually what is commonly called custom functions.

The syntax of the custom function is as follows:

def f(x):

Define process

return f(x)

def (define means definition) is a way to create a function. Let’s use def to create an equation: y=5x+2:

def y(x):
 y = 5*x + 2
 return y
#下面调用自定义函数y
d = y(5)
print(d)
#运行结果是 27

What happens in 30 minutes?

This basic Python tutorial only gives readers who have never been exposed to Python a preliminary impression of Python, so many knowledge points are not discussed; for example, this tutorial does not mention slices, modules, classes and objects, file operations, and processes. Threads, graphical interfaces, network programming, etc.

However, the editor has provided learning materials for everyone to continue learning.

Guess you like

Origin blog.csdn.net/BlueSocks152/article/details/134321984