From introduction to practice of Python Programming P1~P200 learning notes translated by Yuan Guozhong

From introduction to practice of Python Programming P1~P200 learning notes translated by Yuan Guozhong

From introduction to practice of Python programming, Yuan Guozhong translated P1~P200. The notes he made during his study two days ago are also recorded here for future reference. At the same time, I hope it can help more children's shoes!

1, Operation of basic data type

print("Python Case and whitespace removal for Strings")
message = "\tpython xue xi\t"
# The first letter of each word is capitalized
print(message.title())
# The way words are written in all capitals
print(message.upper())  
#  Write all words in lowercase
print(message.lower())  
# Remove whitespace before string
print(message.lstrip())
# Remove whitespace after string
print(message.rstrip())
# Remove whitespace on both sides of the string
print(message.strip())

print("\nPython Mixed operation of addition, subtraction, multiplication and division and power operation")
print(3 + 2)
print(3 - 2)
print(3 * 2)
print(3 / 2)
print(3 ** 2 + 3)
print(0.1 + 2)
print(0.1 + 0.2)
print(0.1 * 2)
print((1 + 2 - 1) * 4 / 4)

print("\n Use function str()Avoid type errors")
age = 20
print("My age this year is" + str(age) + "year\n")

print("Python List and access elements, case of elements, and removal of spaces")
shenghuo = ["chifan", "xuexi", "shuijiao", " shangban"]
print(shenghuo)
print(shenghuo[0].title())  #title case
print(shenghuo[1].upper())	#All capital letters
print(shenghuo[2].lower())	#All lowercase letters
print(shenghuo[3].lstrip())	#Remove whitespace before string
# The elements of the access list are used to remove spaces and splice characters
print(shenghuo[-1])
print(shenghuo[-2])
print("First in the day" + shenghuo[0] + "Then again" + shenghuo[-1].lstrip() + "Continue again" + shenghuo[1] + "Finally again" + shenghuo[-2])

# Modify add delete element
che = ["motuo", "qiche", "zixingche", 'huoche']
print(che)
# modify
che[0] = "kache"
print(che)
# add to
che.append("danche")
print(che)

#Define an empty list
aihao = []
aihao.append("chifan")
aihao.append("shuijiao")
aihao.append("dadoudou")
print(aihao)

# Insert element in list
aihao.insert(1, "xuexi")
print(aihao)

# delete
del aihao[2]
print(aihao)
del aihao[-1]
print(aihao)

# pop deletes the last element in the list and uses the last element deleted
shanzuihou = aihao.pop()
print(shanzuihou)
print("Now my only hobby is" + shanzuihou.title())
shanchu = aihao.pop(0)
print(shanchu)
print("I do it every day" + shanchu.title())

# Remove element based on value
che = ["motuo", "qiche", "zixingche", 'huoche']
che.remove("huoche")
print(che)
che.remove("motuo")
print(che)

# Organization list sort() permanent sort abcde forward or reverse sort
che = ["motuo", "qiche", "zixingche", 'huoche']
# Forward sort
che.sort()
print(che)
# Reverse sort
che.sort(reverse=True)
print(che)

# Organization list sorted() temporary sort abcde forward or reverse sort
# Temporary forward sort
print(sorted(che))
# Temporary reverse sort
print(sorted(che, reverse=True))

# The permanent modification order of the printed list can also be changed back at any time
che = ["motuo", "qiche", "zixingche", 'huoche']
# Reverse printing
che.reverse()
print(che)
# Reverse it again
che.reverse()
print(che)

# Confirm that the length of the list is 4
che = ["motuo", "qiche", "zixingche", 'huoche']
print(len(che))

# For loop traverses the whole list for variable name in traversal list variable name:
che = ["motuo", "qiche", "zixingche", 'huoche']
for che1 in che:
    print(che1)

# To do more in a for loop, Python is extremely strict with indentation
for che2 in che:
    print(che2.title() + 'All vehicles!')
print("You can use it when you go out!")

# Create the print list directly in the for loop
for wenzi in ["Hello", "Me too"]:
    print(wenzi)

# Create a list of numbers
for shuzi in range(1, 5):
    print(shuzi)

# Output 1-4 as a list of numbers
number = list(range(1, 5))
print(number)
# Traverse the list in number through the for loop
for num in number:
    print(num)

# Print even numbers within 10, and add 2 continuously from the first number 2
oushu = list(range(2, 10, 2))
print(oushu)

# 1-10 the square of each integer forms a list
liebiaos = []
for value in range(1, 11):
    liebiaos.append(value ** 2)
print(liebiaos)
print(liebiaos[-1])

# Carry out simple statistics on the number list, maximum value, minimum value and sum
number = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(max(number))
print(min(number))
print(sum(number))

# Assign the square of each number in the number list parsing list to message
message = [value ** 3 for value in range(1, 11)]
print(message)

# Part of the list
che = ["motuo", "qiche", "zixingche", 'huoche']
print(che[0:2])
print(che[1:-1])
print(che[:4])  # No index at the beginning is specified. It starts from 0 by default
print(che[0:])  # There is no end index specified. It ends at the end by default

# The for loop iterates over the slice and capitalizes the first letter of the word
che = ["motuo", "qiche", "zixingche", 'huoche']
for che3 in che[:2]:
    print(che3.title())

# The copy list and the verify list are two lists
che = ["motuo", "qiche", "zixingche", 'huoche']
gongju = che[:]
print(che)
print(gongju)
# Verify that the replicated list is two
che.append("kache")
print(che)
gongju.append("daba")
print(gongju)

# Tuples: Python calls immutable values and immutable lists tuples! Elements cannot be modified, while variables can be modified
# Define a tuple to traverse all the values in the tuple
yuanzu = (100, 50)
print(yuanzu[0])
print(yuanzu[1])

# for traverses all values of tuples
yuanzu = (100, 20, 30)
for bianli in yuanzu:
    print(bianli)

# for modify tuple variables
yuanzu = (100, 50)
for bianli in yuanzu:
    print(bianli)
yuanzu = (200, 300)
for bianli in yuanzu:
    print(bianli)

# The use of if statements is not output according to the order of conditions, but according to the order of the list and conditions
che = ["motuo", "qiche", "zixingche", 'huoche']
for che1 in che:
    if che1 == 'qiche':
        print(che1.upper())  # All uppercase QICHE
    else:
        print(che1.title())  # Initial capital Motuo Zixingche Huoche

# Check whether a specific value is included in the list or not
che = ["motuo", "qiche", "zixingche", 'huoche']
baohan = 'huoche1'
if baohan in che:
    print(baohan + 'Include in list')
else:
    print((baohan + "Not included in the list"))
if baohan not in che:
    print(baohan.title() + 'Not included in the list')

# Use of simple conditional judgment statements if else if_ elif-else
a = 18
if a > 17:
    print('a The value of is greater than 17')
if a > 19:
    print('a The value of is greater than 19')
else:
    print('a The value of is less than 19')
if a > 19:
    print('a The value of is greater than 19')
elif a == 18:  # else if in Java is elif in Python
    print('a The value of is 18')
else:
    print('a The value of is less than 19')

2, Zen of Python

import this

3, Python keyword

# Output keywords in Python
# ['False', 'None', 'True', 'and', 'as', 'assert', '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 keyword
print(keyword.kwlist)

4, Python () [] {} differences

() represents a tuple

# Tuples: Python calls immutable values and immutable lists tuples! Elements cannot be modified, while variables can be modified
# Define a tuple to traverse all the values in the tuple
yuanzu = (100, 50)
print(yuanzu[0])
print(yuanzu[1])
# for traverses all values of tuples
yuanzu=(100,20,30)
for bianli in yuanzu:
    print(bianli)
# for modify tuple variables
yuanzu = (100, 50)
for bianli in yuanzu:
    print(bianli)
yuanzu=(200,300)
for bianli in yuanzu:
    print(bianli)

[] indicates a list

# Organization list sort() permanent abcde forward or reverse sort
che = ["motuo", "qiche", "zixingche", 'huoche']
# Forward sort
che.sort()
print(che)
# Reverse sort
che.sort(reverse=True)
print(che)
# Organization list sorted() temporary abcde forward or reverse sort
# Temporary forward sort
print(sorted(che))
print(sorted(che, reverse=True))

{} represents a dictionary

# Python dictionary {} is equivalent to key value pairs in Java
che = {"motuo":'motuoche', 'huoche':5}
print(che['motuo'])
print(che['huoche'])

5, Dictionary and list (nested) use

# Python dictionary {} key value pair
che = {"motuo": 'motuoche', 'huoche': 5}
print(che['motuo'])
print(che['huoche'])

# Dictionary add key value pair
che = {"motuo": 'motuoche', 'huoche': 5}
che['kache'] = 1
che['qiche'] = 3
print(che)

# Create an empty dictionary and add, modify and delete key value pairs
che1 = {}
che1['kache'] = 'green'
che1['motuo'] = '1'
che1['huoche'] = '2'
che1['qiche'] = '3'
che1['daba'] = 'red'
print(che1)

# Modify values in the dictionary
che2 = {'kache': 'green'}
print(che2)
che2['kache'] = 'yellow'
print(che2)

# Delete key value pair
che1 = {'kache': 'green', 'motuo': '5', 'huoche': '2', 'qiche': '3', 'daba': 'red'}
print(che1)
del che1['huoche']
print(che1)
che1['huoche'] = '4'  # Add back deleted key value pairs
print(che1)
print('kache Vehicle color:' + che1['kache'].title() + '\t' + 'daba What is the color of the vehicle' + che1['daba'].upper())
# The for loop traverses and prints out all the keys in the key value pair
for key in che1.keys():
    print(key.title())
# The for loop traverses and prints out all the values in the key value pair
for value in che1.values():
    print(value)
# The for loop traverses and prints out all the keys in the key value pair and sorts them in order
for key in sorted(che1.keys()):
    print(key.upper().lower().title())  # Print out the value of the key first in uppercase, then in lowercase, and then output the first letter in uppercase
# The for loop iterates through all the values in the key value pair and arranges them in order
for value in sorted(che1.values()):
    print(str(value.upper().lower().title()))

# Store the dictionary combination in the list and print out the dictionary of each key value pair or all dictionaries in the list
che1 = {'kache': '5', 'motuo': '10'}
che2 = {'huoche': '20', 'qiche': '15', }
che3 = {'gongjiao': '30', 'daba': '25'}
che = [che1, che2, che3]
for gongju in che:
    print(gongju)
# Print the first two dictionary key value pairs in the display list
for gongju2 in che[:2]:
    print(gongju2)
# Copy the list of the first two key value pairs, add new key value pairs, and view the list composed of the original and copied dictionaries / store dictionaries in the list
che4 = che[:]
a = {'mache': '35', 'luche': '40'}
che4.append(a)
print(che)
print(che4)
print(str(len(che4)))  # Displays the total number of dictionaries in the list

# Store the list in the dictionary and print out all the values in the list through traversal
che1 = {'kache': 'dakache',
        'motuo': ['xiaomotuo', 'damotuo'],
        }
for motuo1 in che1['motuo']:
    print(motuo1)
print("For pulling goods" + che1['kache'] + '\t' + "Motorcycle is" + motuo1)
# Store the dictionary in the dictionary and access the data of keys and values in each level of the dictionary
che5 = {'che6': {'kache': '5', 'huoche': '6'}}
for key, value in che5.items():
    print(key)
    print(value)
    b=value
    print(b.keys())
    print(b.values())

6, User input and while loop

# User input and while loop function input()
message = input('Please enter:')
print("Output user input:\t" + message)

# Use Input to output a famous saying and splice a complete sentence
qian = "Say what you did,"
hou = 'Do what you said!'
name = input('Please enter who said this:')
print(qian + hou + '\n' + '\t\t\t' + '--' + name)

# Modulus operation determines whether the user inputs an odd number or an even number according to the number entered by the user!
number = input("Please enter any integer that is not 0:")
number = int(number)
if number % 2 == 0:
    print('The number entered by the user is' + str(number) + 'It's an even number!')
else:
    print('The number entered by the user is' + str(number) + 'It's an odd number!')

# Let the user choose when to exit. As long as the data entered by the user is not equal to jieshu, it will always let the user enter data. When the user enters jieshu, it will directly exit the loop
message=''
while message!='jieshu':
    message=input('Please enter:') #Enter jieshu to terminate the program directly
    if message!='jieshu':  #Using the if statement can reduce the printing of the last jieshu. The message will be printed only when the message is not equal to jieshu. Otherwise, it is vice versa!
        print(message)
# While allows the user to choose when to launch the loop. The default of while loop is True. By default, it executes the loop and outputs information. Only when the user inputs tuichu, Active is False, and it will end!
xinxi='Please enter information:'
active=True
while active:
    message=input(xinxi)
    if message=='tuichu':
        active=False
    else:
        print(message)

# If the user enters tuichu, use break to jump out of the loop
xinxi='Please enter information:'
active=True
while active:
    message=input(xinxi)
    print(message)
    if message=='sign out':
        break
    else:
        print("I love You"+message)

# Use continue in the loop to output odd numbers of 1 ~ 10 numbers
shuzi = 0
while shuzi < 10:
    shuzi += 1
    if shuzi % 2 == 0:
        continue
    print(shuzi)

# Use the while loop to process the list dictionary
unconfirmed_users=['alice','brian','candace']
confirmed_users=[]
while unconfirmed_users:
    current_user=unconfirmed_users.pop()
    print(current_user.title())
    confirmed_users.append(current_user)

# Deletes a list element that contains a specific value
che = ["motuo", "qiche", "zixingche", 'huoche'];
print(che)
# Remove qiche
while 'qiche' in che:
    che.remove('qiche')
print(che)

# Use user input to populate the dictionary and let the user decide whether to continue the investigation. The default is True
responses={}
active=True
while active:
    name=input('\n What's your name? Please enter:')
    respons=input('Where do you come from? Please enter:')
    responses[name]=respons
    repeat=input('Is there anyone else to take part in the investigation?(yes/no)')
    if repeat=='no':
        active=False
for name,response in responses.items():
    print(name+'\t'+response)

7, Function

# Python functions are equivalent to methods in java
def greet_user():
    '''Output a sentence'''
    print("Output a sentence")
greet_user()

# Pass information to function argument: rj formal parameter: username
def greet_user(username):
    print('This man's name is'+username)
greet_user('rj')

#Arguments and formal parameters are passed. The argument position argument calls the function multiple times
def describe_pet(animal_type,pet_name):
    '''Display pet information'''
    print('The types of pets are:'+animal_type+'.')
    print('What's the pet's name:'+pet_name.title()+'.\n')
describe_pet('small-scale','h Shiqi')
describe_pet('large','z Tibetan Mastiff')

# Keyword arguments can ignore the order: when writing arguments, you don't have to call function verification multiple times in the order of formal parameters
def describe_pet(animal_type,pet_name):
    '''Display pet information'''
    print('The types of pets are:'+animal_type+'.')
    print('What's the pet's name:'+pet_name.title()+'.\n')
describe_pet(animal_type='medium-sized',pet_name='m Sheep dog')
describe_pet(pet_name='m Sheep dog',animal_type='medium-sized')

#Function to set default values for formal parameters
def describe_pet(animal_type,pet_name='s Magic grey'):
    '''Display pet information'''
    print('The types of pets are:'+animal_type+'.')
    print('What's the pet's name:'+pet_name.title()+'.\n')
describe_pet(animal_type='medium-sized')
describe_pet('small-scale')

#Function arguments and formal parameters, simple return values, multiple calls to the function complex assignment form a list, and the for loop traverses the list output value!
def person(name,age):
    xinxi='This man's name is'+name+','+"Age:"+age
    return xinxi
person_xinxi=person('aaa','20 year')
person_xinxi1=person('bbb','21 year')
per_xinxi=[person_xinxi,person_xinxi1]
for pers_xinxi in per_xinxi[:]:
    print(pers_xinxi)
# The function adds a message to the dictionary to form a new dictionary. The for loop iterates over the key values of all dictionaries, and finally outputs
def person1(name,sex,age=''):
    person1={'n':name,'s':sex}
    if age:
        person1['a']=age #Add a dictionary of 'a':age to the above person1 dictionary
        return person1
xinxi=person1('rj','male',age='20')
'''Print all the information in the dictionary'''
print(xinxi)
'''Print all keys-value'''
for key,value in xinxi.items():
    print(key)
    print(value)
'''Print only the keys in the dictionary'''
for key in xinxi.keys():
    print(key)
'''Print only the values in the dictionary'''
for value in xinxi.values():
    print(value)

# Combining functions with while loops
def mingzi(first_name,last_name):
    '''Returns a full name'''
    full_name=first_name+' '+last_name
    return full_name.title()
'''This is an infinite loop'''
while True:
    print('Please enter your name')
    f_name=input("Please enter your First_name:")
    if f_name=='tuichu':
        break
    l_name=input("Please enter your Last_name:")
    if l_name=='quxiao':
        break
    '''Call the previously defined function'''
    suoyou_name=mingzi(f_name,l_name)
    print(suoyou_name)
# Delivery list
def greet_users(names):
    '''Send a simple greeting to each user in the list'''
    for name in names:
        print('Hi',name.title()+'!')
names=['rj','cj','ft']
greet_users(names)

# Modify the list in the function. while loop removes the data and the available data and adds it to the tool. The for loop traverses the removed available data and outputs the modified list data
che = ["motuo", "qiche", "zixingche", 'huoche']
gongju=[]
while che:
    che3=che.pop()
    print('gongu:'+che3)
    gongju.append(che3)
for che4 in sorted(gongju): #sorted() temporary abcde forward or reverse sort
    print(che4)

#The function assignment is called multiple times by passing any number of arguments
def make_pizza(*toppings):
    print(toppings)
make_pizza('wuai')
make_pizza('wuai','po','jie','wuaipo','pojie','wuaipojie')

#Pass any number of arguments, call the function assignment multiple times, and loop through the arguments and output
def make_pizza(*toppings):
    print('Here you want to output the name result of loop traversal:')
    for topping in toppings:
        print('-'+topping)
make_pizza('wuai')
make_pizza('wuai','po','jie','wuaipo','pojie','wuaipojie')

# The combination of location arguments and any number of arguments is not enough to match location arguments and keyword arguments
def make_pizza(size,*toppings):
    print('Total required'+str(size)+'Here you want to output the name result of loop traversal:')
    for topping in toppings:
        print('-'+topping)
make_pizza(16,'wuai')
make_pizza(12,'wuai','po','jie','wuaipo','pojie','wuaipojie')

1. Import module

pizza.py module

def make_pizza(size, *toppings):
    print('Total required' + str(size) + 'Here you want to output the name result of loop traversal:')
    for topping in toppings:
        print('-' + topping)

making_pizzas.py import module name

import pizza   #Name of the imported module pizza
pizza.make_pizza(15,'wuai')
pizza.make_pizza(18,'wuai','po','jie')

2. Import specific functions

making_pizzas.py from module name import function name

from pizza import make_pizza   #Import specific function make_pizza
make_pizza(15,'wuai')
make_pizza(18,'wuai','po','jie')

3. Use as to assign an alias to the function

making_pizzas.py from module name import function name as alias

from pizza import make_pizza as mp   #Import specific function make_pizza and specify an alias
mp(15,'wuai')
mp(18,'wuai','po','jie')

4. Use as to assign an alias to the module

making_pizzas.py import module name as alias

import pizza as pi   #The name of the imported module is pizza and the alias pi is specified
pi.make_pizza(15,'wuai')
pi.make_pizza(18,'wuai','po','jie')

5. Import all functions in the module

making_pizzas.py from module name import*

from pizza import *   #Import all functions in the module
make_pizza(15,'wuai')
make_pizza(18,'wuai','po','jie')

8, Class

1. Create and use classes

dog.py

class Dog():
    '''A simple test simulating a dog'''
    #init is a special method. There are two underscores at the beginning and end, and three parameter parameters, self, are essential
    def __init__(self, name, age):
        '''Initialize properties name and age'''
        self.name = name
        self.age = age

    def sit(self):
        '''Simulate a dog squatting when ordered'''
        print(self.name.title() + 'is now sitting.')

    def roll_over(self):
        '''Simulate a dog rolling when ordered'''
        print(self.name.title() + 'rolled over')

2. Create instances / multiple instances according to classes

dog.py

my_dog = Dog('gougou', 6)
you_dog = Dog('xiaogou', 7)
print('My dog's name is:' + my_dog.name.title() + '.')
print('This year it has:' + str(my_dog.age) + 'Years old!')

dog.py # call method

my_dog = Dog('gougou', 6)
my_dog.sit() #Call sit squat method
my_dog.roll_over() #Call roll_over rolling method

3. Use classes and instances

che. The PY attribute specifies the default value and the value of the modified attribute (direct and custom functions). The year is not allowed to be smaller than before

# In the method, modify the value of the attribute through the custom modification function
class Che():
    def __init__(self, gongjiao, daba):
        self.gongjiao = gongjiao
        self.daba = daba
        self.year = 9

    def dache(self):
        dache1 = self.gongjiao + self.daba
        return dache1

    def nian(self):
        print('The service life of these two carts is:' + str(self.year) + 'Year!')

    def update(self, nianfen):
        '''Use the modification method to set the value for the age'''
        self.year = nianfen
        if nianfen >= self.year:
            self.year = nianfen
        else:
            print('The year is not allowed to be smaller than the current value!')


gongju1 = Che('transit', 'bus')
print(gongju1.dache())
gongju1.update(8)
gongju1.nian()

9, Inherit

che.py

# Modify the value of an attribute through a custom modification function in the method
class Che():
    def __init__(self, gongjiao, daba):
        self.gongjiao = gongjiao
        self.daba = daba
        self.year = 9

    def dache(self):
        dache1 = self.gongjiao + '\t' + self.daba
        return dache1

    def nian(self):
        print('The service life of these two carts is:' + str(self.year) + 'Year!')

    '''Modify or increase the value of an attribute'''

    def update(self, nianfen):
        '''Use the modification method to set the value for the age'''
        self.year += nianfen
        if nianfen >= self.year:
            self.year = nianfen
        else:
            print('The year is not allowed to be smaller than the current value!')


gongju1 = Che('transit', 'bus')
print(gongju1.dache())
gongju1.update(10)
gongju1.nian()


# Inherit subclass inherit parent class when super is used to initialize the attribute output of the parent class, the subclass calls the function of the parent class
class ElectricCar(Che):
    '''What kinds of cars are there'''

    def __init__(self, gongjiao, daba):
        '''use super Initializes the properties of the parent class'''
        super(ElectricCar, self).__init__(gongjiao, daba)


gongjuzilei = ElectricCar('Public transport subclass', 'Bus subclass')
print(gongjuzilei.dache()) #The subclass calls the function output of the parent class

1. Define attributes and methods for subclasses

che.py che is the parent class, ElectricCar is the child class, and the child class inherits the parent class, that is, the child class (parent class)

# Modify the value of an attribute through a custom modification function in the method
class Che():
    def __init__(self, gongjiao, daba):
        self.gongjiao = gongjiao
        self.daba = daba
        self.year = 9

    def dache(self):
        dache1 = self.gongjiao + '\t' + self.daba
        return dache1

    def nian(self):
        print('The service life of these two carts is:' + str(self.year) + 'Year!')

    '''Modify or increase the value of an attribute'''

    def update(self, nianfen):
        '''Use the modification method to set the value for the age'''
        self.year += nianfen
        if nianfen >= self.year:
            self.year = nianfen
        else:
            print('The year is not allowed to be smaller than the current value!')


gongju1 = Che('transit', 'bus')
print(gongju1.dache())
gongju1.update(10)
gongju1.nian()


# Inherit subclass inherit the parent class. When using super to initialize the attribute output of the parent class, the child class calls the function of the parent class to define attributes and methods for the child class
class ElectricCar(Che):
    '''What kinds of cars are there'''

    def __init__(self, gongjiao, daba):
        '''use super Initializes the properties of the parent class'''
        super(ElectricCar, self).__init__(gongjiao, daba)
        self.daxiao=70   #Define attributes specific to a subclass
    def chedaxiao(self):
        '''Print a message about the size of the car'''
        print('The size of the car is:'+str(self.daxiao)+'rice')

#Assign values to the properties of subclasses 
gongjuzilei = ElectricCar('Public transport subclass', 'Bus subclass')
print(gongjuzilei.dache()) #The subclass calls the function output of the parent class
gongjuzilei.chedaxiao()   #Output the attribute value specific to this subclass in the subclass

2. Subclass overrides the method of parent class

che.py che is the parent class, ElectricCar is the child class, and the child class inherits the parent class, that is, the child class (parent class)

# In the method, modify the value of the attribute through the custom modification function
class Che():
    def __init__(self, gongjiao, daba):
        self.gongjiao = gongjiao
        self.daba = daba
        self.year = 9

    def dache(self):
        dache1 = self.gongjiao + '\t' + self.daba
        return dache1

    def nian(self):
        print('The service life of these two carts is:' + str(self.year) + 'Year!')

    '''Modify or increase the value of an attribute'''
    def update(self, nianfen):
        '''Use the modification method to set the value for the age'''
        self.year += nianfen
        if nianfen >= self.year:
            self.year = nianfen
        else:
            print('The year is not allowed to be smaller than the current value!')


gongju1 = Che('transit', 'bus')
print(gongju1.dache())
gongju1.update(10)
gongju1.nian()


# Inherit subclass inherit the parent class. When using super to initialize the attribute output of the parent class, the child class calls the function of the parent class to define attributes and methods for the child class
class ElectricCar(Che):
    '''What kinds of cars are there'''

    def __init__(self, gongjiao, daba):
        '''use super Initializes the properties of the parent class'''
        super(ElectricCar, self).__init__(gongjiao, daba)
        '''Add two attributes of size and year'''
        self.daxiao = 70
        self.nianfen=2

    def chedaxiao(self):
        '''Print a message about the size of the car'''
        print('The size of the car is:' + str(self.daxiao) + 'rice')

    def nian(self):
        print('The service year of this cart is:' + str(self.nianfen) + 'Year!')

    def update(self, nianfen):
        '''Modify the service life of the car'''
        self.nianfen = nianfen

# Passing parameters to attributes through subclasses
gongjuzilei = ElectricCar('Public transport subclass', 'Bus subclass')
print(gongjuzilei.dache())  # The subclass calls the function output of the parent class
gongjuzilei.chedaxiao()
gongjuzilei.update(12) #Pass the year information to the parameter
gongjuzilei.nian() #Subclass calls the function of year to pass relevant year information

3. Import class / single class

car.py

# Specify a default value for the property, define a class, and define several functions in the class
class Car():
    def __init__(self, qiche, huoche):
        '''Type of initialization description vehicle'''
        self.qiche = qiche
        self.huoche = huoche
        self.year = 6

    def chexing(self):
        '''Function of determining a vehicle model'''
        message = (self.qiche + '\t' + self.huoche)
        return message.title()

    def nian(self):
        '''Define a function that outputs the year of the car'''
        print('The year of the car is:' + str(self.year) + 'Year!')

mycar.py

from car import Car # from file name import class name
# Assign a value to the formal parameter of the class
my_car = Car('automobile', 'train')
# Call the function output of chexing
print(my_car.chexing())
# Modify the value of the property and call the related function output
my_car.year = 12
my_car.nian()

4. Multiple classes / class inheritance imports are stored in the module

car.py

# Specify a default value for the property, define a class, and define several functions in the class
class Car():
    def __init__(self, qiche, huoche):digits
        '''Type of initialization description vehicle'''
        self.qiche = qiche
        self.huoche = huoche
        self.year = 6

    def chexing(self):
        '''Function of determining a vehicle model'''
        message = (self.qiche + '\t' + self.huoche)
        return message.title()

    def nian(self):
        '''Define a function that outputs the year of the car'''
        print('The year of the car is:' + str(self.year) + 'Year!')


# Inherit subclass inherit the parent class. When using super to initialize the attribute output of the parent class, the child class calls the function of the parent class to define attributes and methods for the child class
# Overriding the method of the parent class defines a method with the same name as the method in the parent class in the child class. Python will not consider the method in the parent class, but only focus on the corresponding method defined in the child class
class ElectricCar(Car):
    '''What kinds of cars are there'''

    def __init__(self, gongjiao, daba):
        '''use super Initializes the properties of the parent class'''
        super(ElectricCar, self).__init__(gongjiao, daba)
        self.daxiao = 70
        self.nianfen = 2

    def chedaxiao(self):
        '''Print a message about the size of the car'''
        print('The size of the car is:' + str(self.daxiao) + 'rice')

    # Subclass overrides parent function
    def nian(self):
        print('The service year of this cart is:' + str(self.nianfen) + 'Year!')

    # Subclasses override the functions of the parent class
    def update(self, nianfen):
        '''Modify the service life of the car'''
        self.nianfen = nianfen

my_electric_car.py imports multiple class formats from a module: from module name, import class name, class name or*

from car import Car,ElectricCar

# Pass the parameter of the argument to the formal parameter and output the passed parameter
my_tesla = ElectricCar('transit', 'bus')
print(my_tesla.chexing())
# Modify the value of the property and call the function to output relevant information
my_tesla.daxiao = 80
print(my_tesla.chedaxiao())
# Modify the value of the attribute and call the function to output relevant information
my_tesla.nianfen = 5
print(my_tesla.nian())

5. Import all classes in the whole module / module

my_cars.py import module name from module name import all classes

import car
from car import *

6.Python standard library

Dictionaries allow you to associate with information, but do not record the order in which key value pairs are added. To create a dictionary and record data in key value pairs, you can use the OrderedDict class in module collections. The OrderedDict instance is almost the same as the dictionary, except that the order of recording key value pairs!

from collections import OrderedDict  # Import a function in a module

favorivte_languages = OrderedDict()  # Assign a class to favorte_ languages
'''to favorivte_languages Add dictionary information to'''
favorivte_languages['che'] = 'qiche'
favorivte_languages['che1'] = 'mache'
favorivte_languages['che2'] = 'huoche'
favorivte_languages['che3'] = 'kache'
# The for loop iterates over the dictionary information of the output class
for che, mingzi in favorivte_languages.items():
    print('these' + che.title() + '\t' + 'Call:' + mingzi.title() + '.')

10, File and exception

1. Read the entire file (read)

pi_digits.txt

3.1415926535
  8979323846
  2643383279

file_reader.py reads the entire file in the format: with open("file name") as file_object:

# Relative file path (preferred)
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())  # When there is one more blank line, you can use rstrip() to remove the blank after the string

# Place the file in the project folder relative to the file path (preferred)
with open('text_files\pi_digits.txt') as file_object:
    shuchu = file_object.read()
    print(shuchu)

# Absolute file path for placing files on the computer desktop
file_path = 'C:\\Users\lenovo\Desktop\pi_digits.txt'
with open(file_path) as file_object:
    print(file_object.read())

# Read the information of the file line by line
file_path = 'pi_digits.txt'
with open(file_path) as file_object:
    for line in file_object:
        print(line.rstrip())  # When there is one more blank line, you can use rstrip() to remove the blank after the string

# Read the information of the file line by line, using readlines()
file_path = 'pi_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()
    for line in lines:
        print(line.rstrip())  # When there is one more blank line, you can use rstrip() to remove the blank after the string

2. Read / splice / length using the contents of the file

pi_string.py

# Read the information of the file line by line, using readlines()
file_path = 'pi_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()  # Read the information of each line in the file
pi_string = ''  # Create a string
for line in lines:  # Traverse each line of the read file and store the information in line
    pi_string += line.strip()  # Read each line of information + created string, and use strip() to remove the spaces at both ends
print(pi_string)  # Output information after splicing
print(len(pi_string))  # Output the string length of the spliced information

3. Read a large file with millions of bits

pi_string.py

# Read the information of the file line by line, using readlines()
file_path = 'pi_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()  # Read the information of each line in the file
pi_string = ''  # Create a string
for line in lines:  # Traverse each line of the read file and store the information in line
    pi_string += line.strip()  # Read each line of information + created string, and use strip() to remove the spaces at both ends
print(pi_string[:9]+'...')  # Output the information after splicing, only the first 9 bits in the list are output. If millions of bits are output, change 9 to 1000000
print(len(pi_string))  # Output the string length of the spliced information

4. Write to empty file (multiple lines) / attach / read

pi_string.py

# After writing the file, a Xieru will be generated in the file directory Txt file content is' Yi Ruijie is learning Python '
file_path='xieru.txt'
with open(file_path,'w') as file_object:
    file_object.write('rj I am learning Python') 

pi_string.py

# Write file reads the contents and length of the written file
file_path = 'wenjian.txt'
with open(file_path, 'w') as file_object:  # w: Means write to this file
    file_object.write('rj I am learning Python' + '\n')
    file_object.write('rj I am learning Python1' + '\n')
with open(file_path, 'a') as file_object:  # a: Means attach to this file
    file_object.write('rj I am learning Python' + '\n')
with open(file_path, 'r') as file_object:  # r: Means to read the contents of this file
    lines = file_object.readlines()
    for line in lines:
        print(line.strip())
        print(len(line))

pi_string.py

# Prompt the user to enter their own name, and then write the name entered by the user into the file for output
file_path = 'tishishuru.txt'
with open(file_path, 'w') as file_object:  # w: Means write to this file
    message = input('Please enter your name:')
    file_object.write(message)

division.py

# Exception division by zero
print(5/0)
# Exception division by zero (zero division error)
'''try-except The code block package shortcut key is Ctrl+Alt+T'''
try:
    print(5/0)
except ZeroDivisionError:
    print('Your divisor cannot be zero!')
# Parse text split string for loop traversal output
title = "r j study Python"
print(title.split())  #Traversal according to the space split output is a list
fenxi = title.split()  # Split text with spaces as separators
for wenben in fenxi:  # Traverse the text split according to the space and output it
    print(wenben)

division.py uses multiple files

# Define the function to exclude exceptions, read the file, split the file content, calculate the length of the content, and write it to a new file
def count_words(filename):
    try:
        with open(filename, 'r') as file_object:
            contents = file_object.read()
    except FileNotFoundError:
        print('file' + filename + 'It doesn't exist!')
    else:
        words = contents.split()
        for wenben in words:
            print(wenben)        #Traverse each piece of information after the output split
        num_words=(len(words))
        print('This file really exists'+filename+'The length of the content in the file is:'+str(num_words))

filename = 'alice.txt'
count_words(filename)
# Define the function to exclude exceptions, read the file (multiple files), split the file content, calculate the length of the content, and write it to a new file
def count_words(filename):
    try:
        with open(filename, 'r') as file_object:
            contents = file_object.read()
    except FileNotFoundError:
        print('file' + filename + 'It doesn't exist!')
    else:
        words = contents.split()
        for wenben in words:
            print(wenben)
        num_words=(len(words))
        print('This file really exists'+filename+'The length of the content in the file is:'+str(num_words))

'''When one file does not exist, it does not affect the other files'''
filenames = ['alice1.txt','alice2.txt','alice3.txt','alice4.txt']
for filename in filenames:
    count_words(filename)

5. Store data

number_reader.py json.dump() and JSON load()

import json

# Store the list data in number JSON file
number = [2, 3, 4, 5, 7, 11, 13]
filename = 'number.json'
with open(filename, 'w') as f_obj:
    json.dump(number, f_obj)  # json.dump is used to store. number: the data source to store JSON text f_obj: the location of the file saved to
    print('Data storage to' + filename + 'Done!')

# Read and write to number Data content of JSON file
filename = 'number.json'
with open(filename, 'r') as f_obj:
    numbers = json.load(f_obj)  # json.load is used to read. f_obj: the location of the read data source
    print(numbers)
for number in numbers:  # The for loop iterates through the data in each list in the read file and prints the output
    print(number)

remember_me.py saves and reads the data entered by the user

import json

# Save the data generated during user input into the json file
username = input("Please enter your name:")
filename = 'username.json'
with open(filename, 'w') as f_obj:
    json.dump(username, f_obj)  # json.dump is used to store. Username: the data source to store JSON text f_obj: location of file saved to username json
    print('This person's name is:' + username)

# Read user input data stored in json
filename = 'username.json'
with open(filename, 'r') as f_obj:
    username = json.load(f_obj)  # json.load is used to read. f_obj: the location of the read data source
    print('The information read in the file is:' + username)
import json

# json. dump()  json. Load() is used in combination with try except else
# Load the user name if it was previously stored, otherwise prompt the user for the user name and store it
filename = 'username.json'
try:
    with open(filename, 'r') as f_obj:
        username = json.load(f_obj)  # json.load is used to read. f_obj: the location of the read data source
        print('The information read in the file is:' + username)
except FileNotFoundError:
    # Save the data generated during user input into the json file
    username = input("Please enter your name:")
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)  # json.dump is used to store. Username: the data source to store JSON text f_obj: location of the file saved to username json
        print('This person's name is:' + username)
else:
    print('Welcome:' + username + '!')

6. Reconstruction

remember.py

import json

# json. dump()  json. Load() is used in combination with try except else
# Load the user name if it was previously stored, otherwise prompt the user to enter the user name and store it
def greet_user():
    '''Greet the user and indicate their name'''
    filename = 'username.json'
    try:
        with open(filename, 'r') as f_obj:
            username = json.load(f_obj)  # json.load is used to read. f_obj: the location of the read data source
            print('The information read in the file is:' + username)
    except FileNotFoundError:
        # Save the data generated during user input into the json file
        username = input("Please enter your name:")
        with open(filename, 'w') as f_obj:
            json.dump(username, f_obj)  # json.dump is used to store. Username: the data source to store JSON text f_obj: location of file saved to username json
            print('This person's name is:' + username)
    else:
        print('Welcome:' + username + '!')


greet_user()

remember.py

import json


# json. dump()  json. Load() is used in combination with try except else
# Load the user name if it was previously stored, otherwise prompt the user to enter the user name and store it
# Define function get_stored_username reads the existing user information
def get_stored_username():
    '''Greet the user and indicate their name'''
    filename = 'username.json'
    try:
        with open(filename, 'r') as f_obj:
            username = json.load(f_obj)  # json.load is used to read. f_obj: the location of the read data source
            print('The information read in the file is:' + username)
    except FileNotFoundError:
        return None
    else:
        return username


# Unable to read the existing information. Use greet_ The user function prompts the user for information and writes it to the json file
def greet_user():
    username = get_stored_username()
    if username:
        print("This person's name is:" + username)
    else:
        username = input('Please output your name:')
        filename = 'username.json'
        with open(filename, 'w') as f_obj:
            json.dump(username, f_obj)
            print('The data entered by the user is:' + username)


greet_user()
import json


# json. dump()  json. Load() is used in combination with try except else
# Load the user name if it was previously stored, otherwise prompt the user to enter the user name and store it
# Define function get_stored_username reads the existing user information
def get_stored_username():
    '''Greet the user and indicate their name'''
    filename = 'username.json'
    try:
        with open(filename, 'r') as f_obj:
            username = json.load(f_obj)  # json.load is used to read. f_obj: the location of the read data source
            print('The information read in the file is:' + username)
    except FileNotFoundError:
        return None
    else:
        return username


def get_new_username():
    '''Prompt user for name'''
    username = input('Please output your name:')
    filename = 'username.json'
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
    return username


# Get is called when the existing information is read_ stored_ Username function and output
# Unable to read the existing information, call get_ new_ The username function prompts the user for information and writes it to username JSON file
def greet_user():
    username = get_stored_username()
    if username:
        print("This person's name is:" + username)
    else:
        username = get_new_username()
        print('The data entered by the user is:' + username)


greet_user()

11, Test code

1. Test function

name_function.py

def get_formatted_name(first, last):
    '''Generate neat names'''
    full_name = first + ' ' + last
    return full_name.title()

name.py from module name import function name

from name_function import get_formatted_name

# from name_function import *
# from name_function import get_formatted_name as gfn

print('input'q'Is to exit the program!')
while True:
    first = input('Please enter your first name:')
    if first == 'q':
        break
    last = input('Please enter your last name:')
    if last == 'q':
        break
    formatted_name = get_formatted_name(first, last)
    print('\t The two names entered by the user result in:' + formatted_name)

2. Unit test and test case / pass test / add new test

name_function.py

def get_formatted_name(first, last):
    '''Generate neat names'''
    full_name = first + ' ' + last
    return full_name.title()

test_name_function.py

import unittest
from name_function import get_formatted_name


class NamesTestCase(unittest.TestCase):
    '''test name_function.py'''

    def test_first_last_name(self):
        '''See whether the processed information asserts equal to(assertEqual) Expected output information'''
        formatted_name = get_formatted_name('wuai', 'rj')
        self.assertEqual(formatted_name, 'Wuai Rj')


if __name__ == '__main__':
    unittest.main()

Add new test

name_funciton.py

def get_formatted_name(first, last):
    '''Generate neat names'''
    full_name = first + ' ' + last
    return full_name.title()

test_name_function.py

import unittest
from name_function import get_formatted_name


class NamesTestCase(unittest.TestCase):
    '''test name_function.py'''

    def test_first_last_name(self):
        '''See whether the processed information asserts equal to(assertEqual) Expected output information'''
        formatted_name = get_formatted_name('wuai', 'rj')
        self.assertEqual(formatted_name, 'Wuai Rj')
    def xin_test_first_last_name(self):
        '''See if the processed information asserts equal to(assertEqual) Expected output information'''
        formatted_name = get_formatted_name('rj', 'wuai')
        self.assertEqual(formatted_name, 'Rj Wuai')


if __name__ == '__main__':
    unittest.main()

3. Testing

Six assertion methods commonly used in testing

        self.assertEqual(a,b)                    #Verify a==b
        self.assertNotEqual(a,b)                 #Verify a= b
        self.assertTrue(x)                       #Verify that x is True
        self.assertFalse(x)                      #Verify that x is false
        self.assertIn(item,list)                 #Verify that the item is in the list
        self.assertNotIn(item,list)              #Verify that the item is not in the list

survey.py # a class to test

class AnonymousSurvey():
    '''Collect answers to anonymous questionnaires'''

    def __init__(self, question):
        '''Store a question without storing an answer for preparation'''
        self.question = question
        self.responses = []

    def show_question(self):
        '''Display questionnaire'''
        print(self.question)

    def store_response(self, new_response):
        '''Store a single questionnaire'''
        self.responses.append(new_response)

    def show_results(self):
        '''Display all collected answers'''
        print('The result of the survey is:')
        for response in self.responses:
            print('-' + response)

language_survey.py # a class of the class to use the test

from survey import AnonymousSurvey

# Define a question and create an anonymous survey object that represents the survey
question = 'what language did you first learn to speak?'
my_survey = AnonymousSurvey(question)

# Display questions and store answers
my_survey.show_question()
print("User input'q'You can quit")
while True:
    response = input('Language:')
    if response == 'q':
        break
    my_survey.store_response(response)

# Displays the results to be investigated
print('Thank you for participating in this survey!')
my_survey.show_results()

Test the AnonymousSurvey class

import unittest
from survey import AnonymousSurvey


# The child class inherits the parent class, and the parent class is the test class
class TestAnonymousSurvey(unittest.TestCase):
    '''in the light of AnonymousSurvey Class testing'''

    def test_store_single_response(self):
        '''Test individual answers will be stored properly'''
        question = 'what language did you first learn to speak?'
        my_survey = AnonymousSurvey(question)
        my_survey.store_response('English')
        self.assertIn('English', my_survey.responses)  # Verify whether English is in my_ survey. In responses


if __name__ == '__main__':
    unittest.main()

test_survey.py for traversing the answer list method setUp() in the test class

import unittest
from survey import AnonymousSurvey


# The child class inherits the parent class, and the parent class is the test class
class TestAnonymousSurvey(unittest.TestCase):
    '''in the light of AnonymousSurvey Class testing'''

    def setUp(self):
        '''Create a variance adjustment object and a set of answers for the test method used'''
        question = 'what language did you first learn to speak?'
        self.my_survey = AnonymousSurvey(question)
        self.response = ['English', 'Spanish', 'Mandarin', 'Chinese']

    def test_store_single_response(self):
        '''Test individual answers will be stored properly'''
        self.my_survey.store_response(self.response[0])
        self.assertIn(self.response[0], self.my_survey.responses)  # Verify whether English is in my_ survey. In responses

    def test_store_three_responses(self):
        '''The three answers to the test will be stored properly'''
        for response in self.response:
            self.my_survey.store_response(response)
        for response in self.response:
            self.assertIn(response, self.my_survey.responses)


if __name__ == '__main__':
    unittest.main()

13, Write a program / package it as exe and run it

shuzi.py creates a numerical list of 1 ~ 100 and stores it in the file Shuzi Txt and read it displayed on the console!

print('Create 1~100 A list of numbers stored in the file shuzi.txt And read the display on the console!')


def kaishi():
    message = input('Please enter start or end(Y/N):')
    if message == 'Y':
        # Create a list of numbers from 1 to 100 and output to a file
        print('congratulations! File content output succeeded!')
        number = list(range(1, 101))
        print(number)
        file_name = '1~100.txt'
        with open(file_name, 'w') as file_object:
            for shuzi in number:
                file_object.write(str(shuzi) + '\n')
        with open(file_name, 'r') as file_object:
            line = file_object.readlines()
            for shuzi in line:
                print(shuzi.strip())
    elif message == 'N':
        print('Sorry, you chose to quit! bye-bye!')
    else:
        print('be careful!!! Please input according to the instruction! Y perhaps N ')
        kaishi()


kaishi()

1. Packaging tutorial

Package generation reference link 1 Package generation reference link 2

win+R enter cmd to enter the command line window and execute pip install Pyinstaller to install the packaged plug-in

Then cd to the path of the file project to be packaged: D:\SoftwareProject\PyCharmProject\peoject1

You can also directly add cmd D:\SoftwareProject\PyCharmProject\peoject1 in front of the window path of the file project and enter by typing enter

Execute the command pyuninstaller - F test (file name to be packaged) in the cmd window py

Pyinstaller -F file name py / / package exe

Pyinstaller -F -w file name py / / packaging without console

Pyinstaller -F -i xx.ico file name py / / package the specified exe Icon

Complete successfully appears.
The generated exe file is in dist. this exe file can be run in any location.

Keywords: Python

Added by zoidberg on Tue, 25 Jan 2022 12:29:26 +0200