# python learning -- rookie tutorial + station B video

Life is short. I learn python. ei, I don't learn. I play the web and live two more years. Ha ha ha

Let's talk about the learning of professional courses. It's not that we don't support the introduction of watching videos, but the learning of all contents must return to the reading of books and documents! Sincerely, the sooner you learn documents, the better * * on the importance of learning by consulting documents**

## 1, Sharing of learning materials:

1, Python 3 tutorial | rookie tutorial
2, Dark horse python tutorial video : I only see about 300. I'm a vegetable chicken, 🤣

## 2, Exercise code [not surprisingly, all can be run]:

##### 1. varabile variable exercise.py
```x = "10"
print(int(x))
print(float(x))
'''
price_str = input("Unit price of apple:");
weight_str = input("Apple weight:")
money = float(price_str)*float(weight_str)
print(money)

price = float(input("Unit price of apple:"))
weight = float(input("Critical weight:"))
money = price*weight
print(money)
'''
name = "Xiao Ming"

# Define integer variables and output my student number 00001
student_no = 1
print("My student number is%04d"%student_no)

price = 8.5
weight = 7
money = price * weight
print("Apple unit price%.2f element/Jin, bought it%.3f Jin, need to pay%.4f element"%(price,weight,money))

# Define a decimal scale, and the output data scale is 10.00%
scale = 0.25
print("Data scale%.2f%%"%(scale*100))
```
##### 2. Logical operation.py
```# Exercise 1: define an integer variable age and write code to judge whether the age is correct
age = 120
# The age of the person required is between 0-120

if age >= 0 and age <= 120:
print("Correct age")
else:
print("Incorrect age")

# Exercise 2: defining two integer variables python_score/c_score, write code to judge the score
python_score = 61
c_score = 60
if python_score > 60 or c_score > 60:
print("Pass the exam")
else:
print("If you fail in the exam, keep working hard")

is_employee = True
if not is_employee:
print("Non company personnel are not allowed to enter")
else:
```
##### 3. Girlfriend's festival.py
```# Define holiday_name character
holiday_name = "Valentine's Day"

# If it's Valentine's day,
if holiday_name == "Valentine's Day":
print("watch movie")

elif holiday_name == "Christmas Eve":
else:
print("Every day is a festival!")
```
##### 4. Ticket progress.py
```has_ticket = True
knife_length = 30
if has_ticket:
print("Pass the ticket check and prepare to start the security check")
if knife_length > 20:
print("hold🔪Throw it away")
else:
else:
```
##### 5. Calculate even and. py
```i = 0
result = 0
while i<20:
if i % 2 == 0:
result += i
i += 1

print(result)
```
##### 6. break and continue
```i= 0

while i < 10:
if i == 3:
break
print(i)
i += 1
print("over")

i = 0
while i< 10:
if i == 3:
# If you use the keyword continue, you need to confirm whether the count of the loop is modified, otherwise the loop will die
continue
print(i)
i += 1
```
##### 7. Loop nesting - print asteroid. Experience, end.py
```row = 1
while row <= 5:
print("*" * row)
row += 1

row = 1
while row <= 5:
if row == 2:
print("*" * row, end="")
else:
print("*" * row)
row += 1

```
##### 8. Do not * print small stars
```row = 1
while row <= 5:
col = 1
while col <= row:
print("*",end="")
col += 1
print()

row += 1
```
##### 9. Print 99 multiplication table
```row = 1
while row <= 9:
col = 1
while col <= row:
print("%d*%d = %d"%(col, row, col*row), end="    ")
col += 1
print()
row += 1

row = 1
while row <= 9:
col = 1
while col <= row:
print("%d*%d=%d"%(col, row, col*row), end="\t")
col += 1
print()
row += 1
```
##### 10. String
```str = '123456789'

print(str)  # Output string
print(str[0:-1])  # Output all characters from the first to the penultimate
print(str)  # First character of output string
print(str[2:5])  # Output characters from the third to the fifth
print(str[2:])  # Output all characters starting from the third
print(str[1:5:2])  # Output every other character from the second to the fifth (in steps of 2)
print(str * 2)  # Output string twice
print(str + 'Hello')  # Connection string

print('------------------------------')

print('hello\nrunoob')  # Escape special characters with backslash (\) + n
print(r'hello\nrunoob')  # Add an r before the string to represent the original string without escape
```
##### 11. Stone scissors cloth_ random.py
```import random
# print(random.randint(2,4))
# print(type(random.randint(2,4)))
i= 1
while i <= 50:
player = int(input("Please enter the stone you want to punch (1)/Scissors (2)/Cloth (3)"))
computer = random.randint(1,3)
print("The fist selected by the player is%d - The fist at the computer is%d"%(player,computer))
if ((player == 1 and computer == 2)
or (player == 2 and computer ==3)
or (player == 3 and computer == 1)):
print("The computer is too delicious!")
elif player == computer:
print("One more game")
else:
print("What a pity!")
i = i+1
```
##### 12. Function experience.py
```import zero_Print 99 multiplication table
name = "Xiao Ming"

def say_hello():
print("hello 1")
print("hello 1")
print("hello 1")

print(name)

say_hello()
print(name)
```
##### 13. Return value of function
```def sum_2_sum(num1,num2):
"""Summation of two numbers"""
result =num1 + num2
# You can use the return value
return result

sum_result = sum_2_sum(10,20)
print("Calculation results: %d"%sum_result)

```
##### 14. Print split lines
```def print_line(char,times):
print(char*times)

def print_n_line(chars,times,row):
row1 = 0
while row1 < row:
print_line(chars,times)
row1 += 1
print_n_line("a",50,5)
```
##### 15 common list operations - add, delete, modify query
```name_list = ["zhangsan","lisi","wangwu"]
# c take values from the list
print(name_list)
# Index from list
print(name_list.index("lisi"))
print(name_list.index("zhangsan"))

'''
Modify the data of the list
'''
name_list = "niutingtingt"
print(name_list)

"""
"""
name_list.append("Wang Xiaoer")
name_list.insert(1,"youngest sister")
print(name_list)
temp_list = ["Sun WuKong","Zhu Erge","Sha Shidi"]
name_list.extend(temp_list)
print(name_list)

"""
Delete data
"""
name_list.remove("niutingtingt")
print(name_list)
name_list.pop()
name_list.pop(3)
print(name_list,end="")
print("pop Delete data")
# The keyword used is to delete the variable from memory. Subsequent codes cannot use this variable
del name_list
print(name_list)
name_list.clear()
print(name_list)
# print(name_list.clear())

```
##### 16 list statistics
```name_list = ["Sha Shidi","Sun WuKong","Wang Xiaoer"]

# The len function counts the total number of elements in the list
list_len = len(name_list)
print("List contains%d Elements"%list_len)

# The count method can count the number of times a data appears in the list
# ctrl + q yes
count = name_list.count("Zhang San")
print("Zhang San appeared%d"%count)
```
##### 17. Definition and use of tuples
```info_truple = ("Zhang San", 19 ,8.97, "Zhang San")
print(type(info_truple))
print(info_truple)

# Create empty tuple
empty_temple = ()
print(type(empty_temple))

single_truple = (5)
print(type(single_truple))
single_truple = (5,)
print(type(single_truple))

# Value and index
print(info_truple)
# Know the index of the data in the tuple
print(info_truple.index("Zhang San"))
# Statistical counting
print(info_truple.count("Zhang San"))
# Count the number of elements contained in the tuple
print(len(info_truple))

```
##### 18 characteristics of keywords, functions, methods and elements, and loop traversal
```import keyword
print(keyword.kwlist)

name_list = ["Zhang San","Li Si","Wang Wu"]

# Iterate through the list using
"""
Get data from the list in sequence, and in each cycle
"""
for name in name_list:
print(name_list[i])

tuple =("Zhan Shan","wide","jfdsif",2394)
i = 1
# Use iteration to traverse tuples
for my_info in tuple:

print(tuple[i])
i += 1
```
##### 19 tuple format string
```num_list = [1, 2, 3, 4]

print(type(num_list))

num_tuple = tuple(num_list)
print(type(num_tuple))

num2_list = list(num_tuple)
print(type(num2_list))
```
##### 20. Switching between tuples and lists
```num_list = [1, 2, 3, 4]

print(type(num_list))

num_tuple = tuple(num_list)
print(type(num_tuple))

num2_list = list(num_tuple)
print(type(num2_list))
```
##### 21 sorting and inversion
```nuk_list= ["zhangsan", "list", "nihao", "ntt"]
list_name = ["Zhu Bajie","Sun WuKong","hhh"]

# # Ascending order
# nuk_list.sort()
# list_name.sort()

# # Descending order
# nuk_list.sort(reverse=True)
# list_name.sort(reverse=True)

# Reverse order
nuk_list.reverse()
list_name.reverse()

print(nuk_list)
print(list_name)

```

## 3, Record of some notes

Ctrl + Q: you can view the detailed explanation of the function

P221 – P233

### Chapter 1 Introduction to python (interpretive language)

#### 1-1 interpreter (Popular Science)

1. Computers cannot directly understand any language other than machine language
• Tools that translate other languages into machine languages are called compilers
2. Compiled language has fast parsing speed
• Interpretative language: translation line by line interpretation line by line
• Compiled language: write once and execute once

#### 1-2 Python design objectives

1. 1999, Guido van Rossum
• Simple and intuitive
• Open Source
• The code is as easy to understand as pure English
• Daily tasks suitable for short-term development
2. Design philosophy of python
• simple
• to make clear
• grace
3. In one way, it's best to do one thing in only one way

#### 1-3 features of Python

1. python is a completely object-oriented language
• Functions, modules, numbers and strings are objects, and everything is an object in Python
• It supports overloaded operators and generic design
2. With a strong Library of standards,
• The core only includes numbers and strings. List, dictionary, file and other common types and functions
• Python standard library provides system management, network communication, text processing, database interface, graphics system, XML processing and other functions
• The community provides a large number of third-party modules, which are used in a similar way to the standard library.

### Chapter 2 python Foundation

Three ways to execute python programs

• Interpretative
• Interactivity
• Integrated development environment

#### 2-1 notes

##### 2-1-1 single line note
1. #Label comment after space: skip this line comment directly
2. print("two spaces between code and comment") # is empty
##### 2-1-2 multiline annotation (block annotation)
1. ```'''
multiline comment
'''
```

#### 2-2 arithmetic operators

//Take and divide
%Remainder
**Power (2 * * 3 = 8)
1. Yun Sufu can also be used for string. The calculation result is the result of string repetition for a specified number of times

```"-" * 10
# '----------'
```
2. Priority:

• Power >

### Chapter III program execution principle

#### 3-1 three major pieces in computer

1. CPU
• CPU is a large-scale integrated circuit
• Responsible for data processing / calculation
2. Memory
• Temporarily store data (data disappears after power failure)
• Fast speed
• Small space (high unit price)
3. Hard disk:
• Permanently store data
• Slow speed
• Large space (low unit price)

#### 3-2 clarify the role of the procedure:

1. Programs are used to process data
• Inside the program, the space allocated in memory for QQ number and QQ password is called variable
• Programs are used to process data and variables are used to store data
• Variable names define variables only when they first appear
• The variable name appears again to use the defined variable

#### 3-3 variables

##### 3-3-1 definition of variables
1. Create a variable in memory, including:

• Name of the variable
• Variable saved data
• The type of data the variable stores
2. Variable drill_ personal information

```# The python interpreter will automatically deduce the standard type of data stored in the variable according to the right side of the equal sign of the assignment statement, and str represents a string type
# str represents the string type
name = "Xiao Ming"
# int indicates integer type
print(name)

age = 18
# bool means a boolean type, False
gender = True  # yes
```
• str: String
• bool: Boolean
• int: integer
• float: floating point number (decimal)
##### 3-3-2 types of variables
1. Defining variables in python does not require specifying types
• Data types can be divided into numeric and non numeric types
2. Digital:
• plastic
• int
• long
• float
• Boolean
• complex
• It is mainly used for scientific calculation
3. Non numeric:
• character string
• list
• tuple
• Dictionaries
4. [ipython] use type (gender) to view the type of variable
5. In Python 2. X, integers have long type, and 3.0 does not
##### 3-3-3 calculation between variables
1. Digital direct calculation

2. There are two ways to splice strings:

```# String splicing
first_name = "three"
last_name ="Zhang"
print(first_name + last_name)
print(last_name * 10)
print((last_name+ first_name)*10)
```
3. String variable

```# String variables and numbers cannot perform any other calculations
first_name = "zhang"
x = 10
print("x" + first_name)
# xzhang
print(x + first_name)
'''
Traceback (most recent call last):
File "D:\python\python\pc_practise\hello_python.py", line 59, in <module>
print(x + first_name)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
'''
```
##### 3-3-4 input of variables
1. Input: the input function is required

• print()

• type()

• Function: a function prepared in advance, which can be used directly

2. The input function implements keyboard input:

• Anything entered by the user becomes a string
• Syntax: string variable = input("prompt information:")
##### 3-3-5 type conversion
• String to integer: int()
• float(x): converts x to a floating point number
```x = "10"
print(int(x))
```
1. ```price_str = input("Unit price of apple:");
weight_str = input("Apple weight:")
money = float(price_str)*float(weight_str)
print(money)

price = float(input("Unit price of apple:"))
weight = float(input("Critical weight:"))
money = price*weight
print(money)
```
##### 3-3-6 formatted output of variables
1. %It is called a format operator and is specifically used to handle the format in a string

• A string containing% is called a formatted string
• %When used with different characters, different types of data need to use different formatting characters
2. Format charactermeaning
%scharacter string
%dSigned decimal integer.% n 06d indicates that the output integer displays 6 bits, and 0 is used where it is insufficient
%fFloating point number.% 02f indicates that only two digits are displayed after the decimal point
%%Output%
• The syntax format is as follows:

```print("format string "%Variable 1)
print("format string "% (Variable 1, variable 2...))
```
3. Example:

```name = "Xiao Ming"print("My name is%s，Please take care"%name)# Define integer variables and output my student number 00001 student_no = 1print("My student number is%04d"%student_no)price = 8.5weight = 7money = price * weightprint("Apple unit price%.2f element/Jin, bought it%.3f Jin, need to pay%.4f element"%(price,weight,money))# Define a decimal scale. The output data ratio is 10.00%scale = 0.25print("data ratio%. 2f%%"%(scale*100)) ` ` ` my name is Xiao Ming. Please take care of it. My student number is 0001. The unit price of apple is 8.50 yuan / kg. If you buy 7.000 kg, you need to pay 59.5000 metadata. For example, 25.00%```
```

#### 3-4 naming of variables

##### 3-4-1 keyword concept and identifier
• Identifiers and keywords
• Naming rules for variables
1. Identifiers and keywords
• The identifier is the variable name and function name defined by the programmer
• Identifiers can consist of letters, underscores, and numbers
• Cannot have the same name as the keyword
##### 3-4-2 keywords
• Keywords are identifiers used internally in python

• Keywords have special functions and meanings

```# ['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']import keywordprint(keyword.kwlist)
```
1. Import can import a toolkit

2. Naming rules for variables:

• Naming rules can be regarded as "conventions" to increase the recognition and readability of code
• Increase code recognition and readability
3. Note: identifiers in python are case sensitive

• When defining variables, in order to ensure the code format, a space should be left around =
• Hump nomenclature: first name

### Chapter IV judgment, circulation,

#### 4-1 judgment statement:

##### 4-1-1 if else statement:
1. Judgment in program is also called branch statement

2. Note: the code is indented with a tab key

• tab and space cannot be mixed
3. example:

```age = int(input("Enter your age"))if age >= 18:    print("You can have fun")    print(".")print("aaa")
```
• Note the code block, input 14, and output aaa directly
4. else

```if aaa=0:    dfsfelse:    sffffffffg
```
5. Think of if..else as a large block of code

##### 4-1-2 if，elif，else
1. ```# definition holiday_name character holiday_name = "Valentine's Day"# If it's Valentine's day_ Name = = "Valentine's Day": print("buy roses") print("Watch Movies") elif holiday_name = = "Christmas Eve": print("buy apples") else: print("every day is a festival!")
```
2. Nesting of if:

• Judge multiple conditions at the same time, and all conditions are level

• ```has_ticket = Trueknife_length = 30if has_ticket:    print("Pass the ticket check and prepare to start the security check")    if knife_length > 20:        print("hold🔪Throw it away")    else:        print("Please come in")else:    print("Brother, please buy the ticket first")
```

#### 4-3 while loop:

1. ```i = 0result = 0while i<20:    if i % 2 == 0:        result += i    i += 1print(result)
```

#### 4-2 logic operation

##### 4-2-1 logic operation
• When judging conditions, you need to judge multiple conditions at the same time
• Subsequent code can only be executed if multiple conditions are met
1. And: and / and

• True is returned if both conditions are met
• If one is not satisfied, False is returned
2. Or: or

• Returns True as long as one condition is met
• If it is not satisfied, it returns false
3. Not: not

not condition

4. Example:

#### 4-3 break and continue

1. ```i= 0while i < 10:    if i == 3:        break    print(i)    i += 1print("over")i = 0while i< 10:    if i == 3:        # If you use the keyword continue, you need to confirm whether the count of the loop is modified, otherwise the loop will continue print (I) I + = 1
```

#### 4-4 loop nesting

1. Print asteroids

```row = 1while row <= 5:    print("*" * row)    row += 1
```
2. By default, after the print function outputs the content, a newline is automatically added at the end of the content

• If you don't want to add a newline at the end, you can add it after the output of the print function, end = ""
• Among them, you can specify the content you want to display after the print function outputs the content
3. Don't * print asteroids

```row = 1while row <= 5:    col = 1    while col <= row:        print("*",end="")        col += 1    print()    row += 1
```
4. Print 99 multiplication table

```row = 1while row <= 9:    col = 1    while col <= row:        print("%d*%d = %d"%(col, row, col*row), end="    ")        col += 1    print()    row += 1
```

#### 4-5 get escape character from string

1. Escape character:
• \Tput a tab on the console to help maintain vertical alignment when outputting text
• \n outputs a newline character on the console

#### 4-6 processing of random numbers

• In Python, you need to import the random number module - "toolkit"
```import random
```
• Random. Random (a,b): returns the certificate between [a,b], including a and B

1. +=·%=
-=**=
*=
/=
//=

### Chapter V function

#### 5-1 function

##### 5-1-1 quick experience of function
1. Function: code blocks with independent functions are organized into a small module, which can be called when needed
2. Use steps of function:
• Defining functions: independent functions
• Call function
3. New function:
• Create another file, use import to import and call the function (starting with English)
##### 5-1-2 definition of function:
1. ```def Function name():	Function encapsulated code
```
• def is the abbreviation of define
• The function name should be able to express the function of function encapsulation code to facilitate subsequent calls
• The naming of function names should conform to the naming rules of identifiers
• Can consist of letters, underscores, and numbers
• Cannot have the same name as the keyword

#### 5-2 debugging tools for pycharm

1. F8 Step Over can debug code step by step, and will directly execute the function call as a line of code
2. F7 Step Into can execute code in one step. If it is a function, it will enter the interior of the function

#### 5-3 function document comments and parameters

##### 5-3-1
• To annotate a function, you should use three consecutive pairs of quotation marks below the defined function
• Write a description of the function between three consecutive pairs of quotation marks
• At the function call location, use the shortcut key Ctrl+0 to view the description of the function
1. The function body is relatively independent. Above the function definition, two blank lines should be reserved with other code (including comments)

#### 5-4 module

##### 5-4-1 using functions in modules
1. Module is a core concept in Python program architecture
• A module is like a toolkit. If you want to use the tools in the toolkit, you need to import the module
• Each Python source code file ending in py is a module
• The global variables and functions defined in the module are tools that the module can use directly to the outside world

### Chapter 6 Advanced variable types: list, tuple, dictionary, string, public method, advanced variable

Digital + non digital

• Digital:
• plastic
• float
• Boolean
• really
• false
• Plural form
• Non numeric

#### 6-1 list

1. Lists are the most frequently used data types in Python and are often called arrays in other languages
• Designed to store a string of information
• Lists are defined with [] and arrays are separated by
• The index of the list starts at 0
• Index is the position number of data in the list, and index can also be called subscript
• When fetching from the list, if it exceeds the index range, the program will report an error
2. name_list = ["zhangsan","list","wangwu]

#### 6-2 list common operations

• len (list): get the length of the list n+1
• List. count: the number of times data appears in the list
• List. sort(): sort in ascending order
• List. sort(reverse=True): sort in descending order
• List. reverse(): reverse / reverse
• del list [index]: deletes the data of the specified index

• List. remove [data]: deletes the first occurrence of the specified data

• List. pop: delete end data

• List. Pop (index): deletes the data of the specified index

```"""Delete data"""name_list.remove("niutingtingt")print(name_list)name_list.pop()name_list.pop(3)print(name_list,end="")print("pop Delete data")# The keyword used is to delete the variable from memory. Subsequent codes cannot use this variable del name_listprint(name_list)name_list.clear()print(name_list)
```
• Pop. Insert (index, data): inserts data at a specified location

• List. Append (data): append data at the end

• List. Extend (list 2): append the data from list 2 to list 1

• ```"""Add data to the list"""name_list.append("Wang Xiaoer")name_list.insert(1,"youngest sister")print(name_list)temp_list = ["Sun WuKong","Zhu Erge","Sha Shidi"]name_list.extend(temp_list)print(name_list)
```
• List [index] takes values from the list

• List. Index [data]: get the index of the first occurrence of data

• ```name_list = ["zhangsan","lisi","wangwu"]# c Take values from the list print(name_list)# Take the index print(name_list.index("lisi"))print(name_list.index("zhangsan")) from the list
``` #### 6-3 taking values and indexes from the list, sorting and reverse order

1. Statistics and deletion

```name_list = ["Sha Shidi","Sun WuKong","Wang Xiaoer"]# len The function counts the total number of elements in the list list_len = len(name_list)print("List contains%d Elements"%list_len)# count Method can count the number of times a data appears in the list# ctrl + q count = name_list.count("Zhang San") print("Zhang San appears% d"%count)
```
2. Sorting and inversion

```nuk_list= ["zhangsan", "list", "nihao", "ntt"]list_name = ["Zhu Bajie","Sun WuKong","hhh"]# # Ascending order# nuk_list.sort()# list_name.sort()# # Descending order# nuk_list.sort(reverse=True)# list_name.sort(reverse=True)# Reverse order nuk_list.reverse()list_name.reverse()print(nuk_list)print(list_name)
```

#### 6-4 keywords, functions and methods

1. Parentheses are not required after keywords

```import keywordprint(keyword.kwlist)# 33 ['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
```
2. Function encapsulates independent functions and can be called directly

• Function needs to remember

Function name (parameter)

#### 6-5 loop traversal

1. In order to improve the traversal efficiency of lists, Python provides an Iterator for traversal
2. py can store different types of data

#### 6-6 tuples

##### 6-6-1 definition of tuple
1. A tuple is similar to a list, except that the elements of a tuple cannot be modified

• Tuples represent a sequence of elements
• Tuples have specific application scenarios in Py development
2. It is used to store a string of information, which is used to separate data

3. Tuples are defined with ()

4. The index of tuples starts at 0

5. example:

```info_truple = ("Zhang San", 19 ,8.97)print(type(info_truple))print(info_truple)# Create empty tuple empty_temple = ()print(type(empty_temple))single_truple = (5)print(type(single_truple))single_truple = (5,)print(type(single_truple))
```
##### 6-6-2 loop traversal
1. Because tuples contain different data types, they are generally not traversed

2. ```for item in items:
```

Tags: Python Back-end

Posted on Sat, 23 Oct 2021 14:28:34 -0400 by bugsuperstar37