Python Learning Notes

Keywords: Python Back-end

Python Learning Notes

python language base

variable

Variable name specification:
1. Can only consist of letters, numbers and underscores
2. Cannot start with a number
3. You cannot name a Python built-in key

data type

int      plastic
float    float
str      Character string
bool     Boolean
tuple    tuple
list     list
set      aggregate
dict     Dictionaries

Format

%s Format output string
%f Format Output Floating Point
%d Formatted output signed decimal integer

input

input() Enter information that accepts input from the user
Syntax: input
Characteristic:

  1. The console freezes when it encounters an input and waits for the user to enter information before the program continues to run
  2. input inputs are generally assigned to variables
eval Data type for extracting variable values
a='0.1'
eval(a) After running a It is no longer a character type. And it's floating point

Grammatical Structure

Single Branch Selection Structure

Grammar:
if condition:
Conditional True False
Execute Statement

Be careful with indentation!!!

age = 13
if age > 18:
    # Only if the if condition is met will the following three output statements be output; if not, only the last output statement will be output
    print("You're an adult,Can go online")
    print("Welcome")
    # A single output statement that does not involve the if statement will output regardless of whether the if condition is met
print("You are not old enough")

Double Branch Selection Structure

if conditional expression:
Code Block 1
else:
Code Block 2

age = int(input("Please enter your age:"))
if age > 18:
    print(f"Your age is{age}year,You're an adult")
    print("Welcome")
else:
    print(f"Your age is{age},You are still under age")
    print("Contact the network administrator if you want to go online")
print("System shutdown~")

Multi-Branch Selection Structure

if (conditional expression 1):
Code Block 1
elif (conditional expression 2):
Code Block 2
Else (conditional expression 3):
Code Block 3

grade = eval(input("Please enter your score:\n"))
if 100 >= grade >= 60:
    print(f"Your results are{grade},Passed")
    print("Reward a chocolate")
elif grade >= 0:
    print(f"Your results are{grade},Your grades failed")
    print("Take the bucket to the factory")
else:
    print("You're a bad boy")

for loop

for loop variable in range():
Circulatory body

 for i in range(0, 10, 2):
     # 0 is the initial value, can not be written, the default value is 0.10 is the end value, but the output does not include 10, 2 is the number of steps, just like I walk two numbers in one step, is the multiple of 2
     print(i)

 b = 0;
 for i in range(101): # range takes an integer
     if i % 2 == 0:
         b += i
print(f"1~100 Even sum of{b}")

break and continue

break jumps out of the loop and ends the whole cycle
continue Jumps Out of this Loop to continue the Next Loop

for i in range(1, 6):
    if i == 3:
        # break   # Output to end of 3 loop
        continue  # Skip number 3 to continue next cycle
    print(i)

while else and for else

for ... else:
A statement within an else is a statement executed after the normal end of the loop
If the loop ends with a brake, statements within an else will no longer be executed
while ... else:
A statement within an else is a statement executed after the normal end of the loop
If the loop ends with a brake, statements within an else will no longer be executed

for i in range(1, 5):
    print(i)
else:
    print("End of cycle")   # The normal end of the loop will run the contents of else
print("Hey Hey")

data structure

Initial string

Define a single-line string   ''  ""
''' '''  """ """    Define a multiline string \n \t Normal output

Index and slicing of strings

str1 = 'abcdefg'
#   Subscript is also called index numbering from 0
#   Format: [Subscript] Subscript can be positive or negative
print(str1[0])      # a
print(str1[-4])     # d
#   Slice [Start subscript (inclusive): End subscript (excluded): Step]
print(str1[0:3:1])  # abc
print(str1[0:3:2])  # ac
print(str1[0:3])    # Step size can be saved by default to 1
print(str1[:3])     # Start subscript can be omitted, default start from 0
print(str1[1:])     # End subscript can also be omitted, default to end
print(str1[::-1])   # str1[::-1] Reverse output
# String is an immutable operation that cannot be added or deleted

List

'''
Currency conversion: Renminbi¥And US Dollars $Conversion
 The user enters the amount and currency symbols to be converted to¥or $End
 Convert to Renminbi 6 if the user enters US dollars.382
 If the user enters Renminbi, the converted rate is 0.1567
 If no symbol is entered by the user, an error is prompted and re-entered
 Keep two decimal places for the final result
'''
while True:
    money = input('Please enter the amount and currency symbol to be converted to¥or $End:')
    if money[-1] == '$':
        USD = eval(money[0:-1])
        money1 = USD * 6.382
        print(f'The amount you entered is{USD}, The converted amount is{money1:.2f}')
        break
    elif money[-1] == '¥':
        RMB = eval(money[0:-1])
        money2 = RMB * 0.1567
        print(f'The amount you entered is{RMB}, The converted amount is{money2:.2f}')
        break
    else:
        print('The format you entered is incorrect, please re-enter!')

String additions and deletions

str1 = 'hello,python'
# find('substring', start subscript, end subscript) find subscript
# Find finds the first subscript, returns the first substring subscript, and cannot find the Return-1
# print(str1.find('y'))                  # Find the subscript for y
# print(str1.find('o'))                 # Find the subscript for o and return the subscript for the first substring
# print(str1.find('o', 5, 11))            # Include at start and exclude at end
# print(str1.rfind('l'))                  # Search from right by default
# index() lookup
# index('substring', start subscript, end subscript) lookup
# print(str1.index('a'))      # Return is the subscript of the first substring, no error found
# count() counts the number of substrings, returning 0 if none exist
# count('substring', start subscript, end subscript)
print(str1.count('y'))

String substitution

# replacer('old substring','New substring')
str1 = 'hello python'
# Replace python with world
str2 = str1.replace('python', 'world')
print(str1)
print(str2)

Method of String

# split('delimiter') splits a string into multiple objects
# Multiple objects stored in a list
'''
str1 = 'hello,python'
print(str1.split(','))
'''
# strip() removes symbols before and after strings, mostly to remove spaces
'''
str2 = '==hello=='
print(str2)
print(str2.strip(''))   # Remove whitespace
print(str2.strip('='))
print(str2.strip('=').strip(','))   # Remove left and right symbols
'''
# str.join(stp) is to add str to STP
# stp can be a string or a list
'''str3 = 'hello'
li1 = ['h', 'e', 'l', 'l', 'o']
print(','.join(str3))
print(''.join(li1))'''
# lower() all lowercase
'''str4 = 'JJHJHKJDSDSD'
print(str4.lower())'''
# upper() all converted to uppercase
'''str5 = 'adsddddfds'
print(str5.upper())'''
# title() initials uppercase
'''str6 = 'hello,python'
print(str6.title())'''
# Len (string name) Gets the length of the string
'''str7 = 'aaaaaaaaaaaaaaaaaaa'
print(len(str7))'''
# Max (string name) maximum by 26 letters
'''str8 = 'abcdefgABCDEFG'
print(max(str8))'''  # g
# Min (string name) takes the minimum value
'''print(min(str8))'''  # A

tuple

Initial tuple

tuple() Cast to tuple

Index and slicing of tuples

Tuple [subscript] can be positive or negative

Slice [Start: End: Step] Contains Start but does not Contain End

A tuple is an immutable data type, but if a variable data type such as a list is placed inside the tuple, the data in the list can be changed.

Tuple lookup

index() returns the subscript of the first matching element that cannot be found and will cause an error

count() returns the number of matching elements

list

Initial list

Definition List      Lists can hold all data types
 Define an empty list []  list()  Two forms of defining empty lists
 Define a list with data  [Data 1, Data 2, data n]     list(data)   Two lists with data defined
list() Convert other types to lists

len() returns the length of the list

max() returns the maximum value

min() returns the minimum value

Index and Slice of List

Subscript, assign a subscript in order from 0
List name [subscript] subscript can be positive or negative

Lists are variable data types that can be added, deleted, altered, and checked

Increase in list

append()  Append data to the end of the list
 Syntax: List name.append(data)

extend()  Append data to the end of the list

insert(subscript, data)  Insert data into a fixed location

List Lookup

index() Returns the subscript of the first data found
count() Number of Statistics

Delete List

del delete    Public method deletes all data types
del Variable Name
del List Name[subscript]  Remove fixed subscript elements
pop() delete      List Name.pop(subscript)		Remove the fixed subscript element and return its value
pop()Delete the last element if no subscript is written
remove() Delete Remove Matching First Element
sort()    Sorted, default from smallest to largest      reverse=False   Default value from small to large
reverse()     Reverse Output

Dictionaries

Initial Dictionary

dict Dictionaries
{key1:value1, key2:value2}
key Value is unique if key Repeat, output last
{} Define an empty dictionary
dict() Factory function
dict Create an empty dictionary
dict()Created with key-value Dictionaries
key Cannot quote
zip() Merge multiple data to merge with the fewest elements
fromkeys(keys,value) If value Omit, enter none
 Define a dictionary key Different, value Same dictionary

New Dictionary

# Dictionaries are variable data types
dict1 = {'name': 'Ada', 'age': 20}
'''
print(dict1[0])         # Dictionaries do not support subscripts and slicing
print(dict1['name'])    # You can use key to return value
'''
# Dictionary name [key] = value adds a key-value
'''
dict1['name'] = 'Afei'     # Modify the value if the key exists
dict1['height'] = '183cm'   # If key does not exist, add a key-value
print(dict1)
'''
# Dictionary name. update() adds more than one key-value
'''
dict2 = {'width': 140, 'hobby': 'Play with the smarthphone'}
dict1.update(dict2)
print(dict1)
'''
# Set default (key, value) add a key-value
'''
dict1.setdefault('girlfriend', 'lili')  # If key does not exist, add a key-value
dict1.setdefault('width', '150')      # Value value cannot be modified if key exists
print(dict1)
'''

Delete Dictionary

del Dictionary Name Deletes the entire dictionary
 Dictionary Name.pop(key) delete key-value,And back value
popitem()     Delete Last key-value
clear() Empty Dictionary

Dictionary Lookup

Dictionary Name[key] Return this key Of value
 Dictionary Name.get(key) Return this key Of value
keys() Return to All key
values() Return to All value
items() Return to All key-value

aggregate

Initial Set

set{Element 1, element 2, element n}
Collection has automatic weighting
{}Define an empty dictionary, not an empty collection
set()Force Conversion to Collection
 The collection is out of order and cannot be indexed(subscript)And slicing,It cannot be connected, checked or counted.

Delete and increase of collection

add() Add one data at a time
update()  Add multiple new data, which can be lists, tuples, collections
pop() delete
remove()  Delete Delete Fixed Values
sorted() Sort from smallest to largest by default
copy() copy

Student Management System

student = []
# str.center(40,'*') centering text makes str 40, insufficient complement*
print('Welcome to the Student Management System'.center(30, '='))
while True:
    print('''Please enter the serial number to select the appropriate function:
        1,Add Student Information
        2,Delete Student Information
        3,Modify Student Information
        4,Query Student Information
        5,Query all students
        6,Exit the current system''')
    num = input('Enter the serial number for the function:')
    if num == '1':              # Add Student Information
        '''
        1.Student Information: Class 100, Age 21, School Number 1000, Gender, Name
        Student information is stored in a dictionary
        2.Determine if a number exists: it is unique
        If the number exists: the student's information cannot be added
        If the number does not exist, append the student information to student List append()
        '''
        print('New Student Information Interface'.center(30, '-'))
        new_class = input('Please enter the student's class:')
        new_age = input('Please enter the student's age:')
        new_id = input('Please enter the student's number:')
        new_name = input('Please enter the name of the student:')
        stu_dict = {}           # Empty Dictionary Receives Student Information
        for i in student:
            if new_id == i.get('id'):
                print('Student already exists')
            else:
                stu_dict['class'] = new_class
                stu_dict['age'] = new_age
                stu_dict['id'] = new_id
                stu_dict['name'] = new_name
                student.append(stu_dict)
                print(student)
    elif num == '2':
        '''
        Needs Analysis:
        1.Delete by number
        2.Delete the student if the number exists
        3.If the number does not exist, it cannot be deleted
        '''
        print('Delete Student Information Interface'.center(30, '-'))
        del_id = input('Please enter the student number you want to delete:')
        # for...else
        #
        for i in student:
            if del_id == i['id']:
                student.remove(i)
                break
        else:
                print('The number does not exist, please confirm before deleting')
        print(student)
    elif num == '3':
        print('Modify Student Information'.center(30, '*'))
        """
        Modify student information according to number:
        1.Enter a number
        2.Determine if the number exists 2-1 Exist, modify information     2-2 does not exist, no such person found
        """
        modify_id = input('Please enter the student number that needs to be modified:')
        for i in student:
            if modify_id == i.get('id'):
                i['class'] = input('Please enter a new class:')
                i['age'] = input('Please enter a new age:')
                i['name'] = input('Please enter a new name:')
                break
        else:
            print('No such person found')
    elif num == '4':
        print('Query Student Information'.center(30, '*'))
        query_id = input('Enter the number of the student you want to inquire about:')
        for i in student:
            if query_id == i['id']:
                print(f'Class is{i["class"]}, The number is{i["id"]}, Age is{i["age"]}, Name is{i["age"]}')
                break
        else:
            print('No such person found')
    elif num == '5':
        print('Query all students'.center(30, '*'))
        print('class\t Age\t School Number\t Full name')
        for i in student:
            print(i["class"], i["age"], i['id'], i['name'])
    elif num == '6':
        ty = input('Whether to exit the current system(input y or n): ')
        if ty == 'y':
            break               # break ends the entire loop
        else:
            continue            # continue Ends the current loop and proceeds to the next one
    else:
        print('Error entering serial number, please re-enter:')

Derivation (Generation)

# Derivative (Generative) Simplified Code
# Syntax: variable for variable in range
# List derivation [variable for variable in range]
# [0,1,2,3,4,5,6,7,8,9]
li1 = []
for i in range(10):
    li1.append(i)
print(li1)
li2 = [i for i in range(10)]
print(li2)
li3 = [1, 2, 1.1, 'a', 20.4, 'jj', 8]
# [variable for variable in range if condition]
li4 = [i for i in li3 if type(i) == int]
print(li4)
str1 = 'ABC'
str2 = '123'
print([i+j for i in str1 for j in str2])
# Dictionary derivation {key:value}
print({i: j for i in str1 for j in str2})
# Generate a dictionary with keys 1, 2, 3, 4, 5 being their squares
print({i: i**2 for i in range(1, 6)})
# Set derivation {}
l1 = [1, 2, 3, 1, 2, 3, 4, 5, 6]
# Place the square of each element in l1 in the set
print({i**2 for i in l1})       # Sets are out of order and automatically de-weighted

function

Definition and use of functions

Functions are designed to achieve more efficient code reuse and improve code consistency
 Definition of function:
def Function name(parameter list):
    """Description Documentation(Notes)Usually on the first line"""
    Function Body(Code)
Call function: Function name(parameter)
Notes: 1. Parameters may or may not be available for different requirements
2,stay python In, functions must be defined before they can be used
3,Functions must be called before they can be used

Parameters of the function

Parameters of a function: To make a function more flexible
 Parameters: When defining a function, parameters to end the data are also defined
 Arguments: The actual data passed when the function is called

Return value of function

return Returns a value, returning a value to the place where the function was called
return:
1. Without return,Will return a None
2. return Represents the end of the current function, return The statement below will not be executed
3. If you want to return more than one value, go directly to the return Write multiple values, which are returned as tuples to the object calling the function
4. The return value can be of any data type
5. The return value can be assigned to a variable or passed to the next function as an argument

Parameter Advancement of Functions

# Position parameter transfers parameter position and number are fixed according to parameter position
def test01(name, age, sex):
    print(f'Name is{name},Age is{age}Age, gender{sex}')
test01('Conger', 1, 'Unknown')
# Keyword parameters are passed as "key = value"
test01(name='Agam', age=21, sex='male')
test01(age=21, sex='male', name='Agam')     # The order of the parameters does not affect the output results and is more flexible than position parameters
# Default parameters, default parameters can pass parameters without passing arguments Default parameters must be at the end of the parameter list
def test02(name, age, sex='male'):
    print(f'Name is{name},Age is{age},Gender is{sex}')
test02('Ada', 19)
test02('Asa', 28, 'female')
# Indefinite length parameter (indeterminate length)
# 1. Parcel location parameter * args passes parameters as tuples
def test03(*args):              # test03(*aaa) parameter name is arbitrary
    sum = 0
    for i in args:
        #sum = sum + i
        sum += i
    print(sum)
test03(10, 34, 45, 76, 99)
test03(100, 999999)
def test04(a, b, *args):
    print(args, a, b)
test04(1, 2, 3, 4, 5, 6, 7)
# 2. Package keyword parameters**kwargs
def test05(**kwargs):
    for i in kwargs:
        print(i)
test05(name='Acar', age=19, sex='male')
# Define a function. Maximum and Minimum in Output List
def test06(*args):
    args = list(args)
    a = max(args)
    b = min(args)
    print(f"The maximum number you enter is{a},The minimum value is{b}")

Variable Scope of Function

# Variable Scope: The area in which the variable acts
# Local variable: A variable defined within a function whose area of action is within the function. Once the function is executed, the variable is destroyed
def test01():
    a = 10
    print(a)
test01()
# print(a)    # A is a local variable and calls outside of functions will fail
# Global variables: variables that are available both inside and outside the function
b = 3
def test02():
    global b    # Declare b as a global variable
    b = 10
    print(id(b))
    print(b)
test02()
print(f'The value of the global variable is{b}')
print(id(b))
# Local variables are faster than global variables and can be used optimally during use.
# Testing local and global variables
# import math as m        # Name math m
import math
import time
qj = math.sqrt
def quanju():
    start = time.time()
    for i in range(10000000):
        qj(199)
    end = time.time()
    print(f'Execution time of global variables{end-start}')
def jubu():
    jb = math.sqrt
    start = time.time()
    for i in range(10000000):
        jb(199)
    end = time.time()
    print(f'Execution time of local variable{end-start}')
quanju()
jubu()

Posted by CaptianChaos on Mon, 06 Dec 2021 09:12:02 -0800