b station Dane python class study notes
P50 Python Basics-5.1 Course Content Review
1. Review day04
""" day04 review sentence loop statement for + range(): fixed number of cycles while:loop with conditional execution range(start,Finish,step size) range(2,6,2)->2 4 range(2)->0 1 range(2,2)-> container string str:Immutable encoded value utf-8 literal value apostrophe Double quotes triple quotes (what you see is what you get) Escapes \character string formatting "..."+variable 1+".."+Variable 2+".." "...%s..%f.."%(variable 1,Variable 2) common operation mathematical operator + * member operator element in container index:Locating a single element Slicing: positioning multiple elements function:len(container) length """ name = 'Daqiang' name = "cockroach" print(name)#cockroach
P51 Python Basics-5.2 Homework Analysis
1. Exercise 1: Formatting and printing
""" 3. According to the following format, output variables name = "goku",age = 800,score = 99.5 My name is xx,age is xx,result is xx. """
name = "goku" age = 800 score = 99.5 message = "My name is%s,age is%d,result is%.1f. " % (name, age, score) print(message)
2. Exercise 2: for loop
""" 4. Get an integer as the side length in the console. Print a rectangle according to its side length. Example: 4 **** * * * * **** 6 ****** * * * * * * * * ****** """
number = int(input("Please enter an integer:")) # 4 print("*" * number) for item in range(number - 2): # print("*" + " " * (number - 2) + "*") print("*" * number)
3. Exercise 3: String Slicing
""" 5.Enter a string in the console to determine whether it is a palindrome. judgment rule:Forward and reverse are the same. Shanghai tap water comes from the sea """
message = "Shanghai tap water comes from the sea" if message == message[::-1]: print("is a palindrome") else: print("not a palindrome")
4. Exercise 4: while loop
""" 6. (expand)A small ball from 100mdrop from height Each bounce back to half the original height. Calculation: how many times it bounces up in total (minimum bounce height 0.01m). how many meters in total """
height = 100 count = 0 # Passed distance distance = height # The height before the bounce is greater than the minimum bounce height # while height > 0.01: # The bounce height is greater than the minimum bounce height while height / 2 > 0.01: count += 1 # pop up height /= 2 print("No.%d The height of the second bounce is%f." % (count, height)) # Cumulative take-off/fall height distance += height * 2 print("total bounce%d Second-rate" % count) print("The total distance traveled is%.2f" % distance)
P52~53 Python Basics-5.3&5.4 List Introduction 01&02
1. Definition
A mutable sequence container consisting of a sequence of variables.
2. Basic operation
Create list:
ListName = []
listName = list( iterable object)
Add element:
listname.append( element)
list.insert( index, element)
Positioning elements:
index, slice
Iterate over the list:
Forward: for variable name in list name: The variable name is the element Reverse: for index name in range(len(list name)-1,-1,-1): list name[index name]is the element
Remove element:
listname.remove( element)
del listName [index or slice]
3. Example code
# 1. Create a list # null list01 = [] list01 = list() # Defaults list02 = ["Goku", 100, True] list02 = list("I'm Monkey King") # 2. Get the element # index print(list02[2]) # together # slice print(list02[-4:]) # ['Qi', 'Heaven', 'Big', 'Holy'] # 3. Add elements # Append (add at the end) list02.append("Bajie") # Insert (add at specified position) list02.insert(1, True) # Add True at index 1 (second) # 4. Delete elements # delete by element list02.remove("yes") # delete by location del list02[0] print(list02) # 5. Define elements, purpose: to add, delete, modify and check elements. # slice del list02[1:3] print(list02) # [True, 'Big', 'Holy', 'Bajie'] # [True, 'a', 'b', 'Bajie'] list02[1:3] = ["a", "b"] # [True, 'Bajie'] # list02[1:3] = [] print(list02) # traverse the list # Get all elements in the list for item in list02: print(item) # Get all elements in reverse order # Not recommended # list02[::-1] takes elements by slicing and will recreate a new list. # for item in list02[::-1]: # print(item) # 3 2 1 0 for i in range(len(list02) - 1, -1, -1): print(list02[i]) # -1 -2 -3 -4 for i in range(-1, -len(list02) - 1, -1): print(list02[i])
P54 Python Basics-5.5 List Exercises
1. Exercise 1
""" Exercise 1: Enter in the console, your favorite characters in Journey to the West. Enter an empty string, print(A row)all characters. """
list_person = [] # entry process while True: str_input = input("Enter your favorite characters in Journey to the West:") if str_input == "": break list_person.append(str_input) # output process for item in list_person: print(item)
2. Exercise 2
''' # Exercise: Enter in the console, all student grades. # Enter an empty string to print (one per line) all grades. # Print the highest score, print the lowest score, and print the average score. '''
list_score = [] # entry process while True: str_score = input("Please enter grades:") if str_score == "": break list_score.append(int(str_score)) # output process for item in list_score: print(item) print("Highest score:" + str(max(list_score))) print("Lowest score:" + str(min(list_score))) print("The average score:" + str(sum(list_score) / len(list_score)))
P55 Python basics-5.6 practice of entering student names (debugging code)
1. Practice (debugging code)
""" # Exercise 3: # Enter in the console, the names of all students. # If the name is repeated, it will prompt "the name already exists" and will not be added to the list. # If an empty string is entered, all students are printed in reverse. """
list_name = [] while True: name = input("Please type in your name:") if name == "": break # Check if variable exists in list if name not in list_name: list_name.append(name) else: print("name already exists") # -1 -2 -3 # 2 1 0 for item in range(-1, -len(list_name) - 1, -1): print(list_name[item])
P56 Python Basics-5.7 List Memory Map
memory map 1
list01 = ["Zhang Wuji","Zhao Min"] list02 = list01 # Modifies the first element of the list list01[0] = "Mowgli" print(list02[0])
memory map 2
list01 = ["Zhang Wuji","Zhao Min"] list02 = list01 # The modified list01 variable list01 = ["Mowgli"] print(list02[0])#Zhang Wuji
Memory Figure 3
list01 = [800,1000] # Getting elements by slice creates a new list. list02 = list01[:] list01[0] = 900 print(list02[0])#?800 list01 = [500] print(list02[0])#?800
Memory Figure 4
# list of lists list01 = [800,[1000,500]] list02 = list01 list01[1][0] = 900 print(list02[1][0])#?900
Memory Figure 5 (shallow copy case of list)
# list of lists list01 = [800,[1000,500]] list02 = list01[:] list01[1][0] = 900 print(list02[1][0])#?900
P57 Python Basics-5.8 Deep Copy and Shallow Copy
1. Deep copy and shallow copy
Shallow copy: During the copying process, only one layer of variables is copied, and the copying process of objects bound to deep variables will not be copied.
Deep copy: Copy the entire dependent variable.
shallow copy
list01 = [800,[1000,500]] # shallow copy # list02 = list01[:] list02 = list01.copy() #Equivalent to the slice from the previous line list01[1][0] = 900 print(list02[1][0])#?900
deep copy
import copy list01 = [800,[1000,500]] # deep copy list02 =copy.deepcopy(list01) list01[1][0] = 900 print(list02[1][0])#?
Deep copy memory map
P58 Python Basics-5.9 List memory graph exercise
1. Exercise 1
""" Exercise 1: will list[54,25,12,42,35,17]middle, Numbers greater than 30 are stored in another list. and draw a memory map. """ # Exercise 1: list01 = [54, 25, 12, 42, 35, 17] list02 = [] for item in list01: if item > 30: list02.append(item) print(list02)
memory map
2. Exercise 2
""" Exercise 2: Enter 5 numbers in the console, Print the maximum value (not applicable max). """ # Exercise 2: # assumed maximum max_value = 0 for item in range(5): number = int(input("Please enter the No.%d numbers:" % (item + 1))) if max_value < number: max_value = number print(max_value)
P59 Python Basics-5.10 Exercises for calculating the maximum value and deleting elements
1. Calculate the maximum value
Sample code (bubble sort idea)
# Exercise 3: # In the list [54, 25, 12, 42, 35, 17], pick the largest value (max is not used). list01 = [54, 25, 12, 42, 100, 17] # Assuming the first is the largest max_value = list01[0] # Compare with the following (starting from the second) element # 1 2 3 4 5 for i in range(1, len(list01)): if max_value < list01[i]: # If a larger one is found, replace the assumed one. max_value = list01[i] print(max_value)
2. Delete elements
Exercise 4: In the list [9, 25, 12, 8], delete numbers greater than 10.
Principle of deletion
wrong way to delete
list01 = [9, 25, 12, 8] for item in list01: if item > 10: list01.remove(item) print(list01) ''' The result is [9, 12, 8],12 not deleted The reason is that when deleting from left to right, the position of the deleted element will be filled by the following element, so that the filled element will not be traversed The purpose of doing this for memory is to improve memory utilization, otherwise there will be no shit in the latrine '''
remove() deletes the principle memory map
The correct way to delete: from right to left (from the end to the beginning)
list01 = [9, 25, 12, 8] #3 2 1 0 #-1 -2 -3 -4 for i in range(len(list01)-1,-1,-1): if list01[i] > 10: list01.remove(list01[i]) print(list01)
P60 Python Basics-5.11 List and String Comparison and Homework Assignment
1. List VS String
- Both lists and strings are sequences, and there is an order relationship between elements.
- Strings are immutable sequences and lists are mutable sequences.
- Each element in a string can only store characters, while a list can store any type.
- Both lists and strings are iterable objects.
- function:
Concatenates multiple strings into one.
result = "connector".join( list)
Split a string into multiples.
list = "a-b-c-d".split("separator")
2. String splicing optimization scheme
''' Requirements: According toxxlogic, splicing a string. "0123456789" '''
''' Method 1: String addition Disadvantage: Each loop forms (+=)a new string object,Replace variable references result. ''' result = "" for item in range(10): #"" #"0" #"01" #"012" result = result + str(item)
''' Method 2: list, join() Advantages: Each loop only adds strings to the list, and does not create a list object. ''' list_temp = [] for item in range(10): list_temp.append(str(item)) # join : list --> str result = " ".join(list_temp) print(type(result)) print(result)
exercise 1
practise:Loop through input strings in the console,Stop if the input is empty. Finally print everything (spliced string).
list_result = [] while True: str_input = input("please enter:") if str_input == "": break list_result.append(str_input) str_result = "".join(list_result) print(str_result)
4. String splitting (str–>list)
str01 = "Zhang Wuji-Zhao Min-Zhou Zhiruo" list_result = str01.split("-") print(list_result)
exercise 2
practise:english word flip "How are you" -->"you are How"
str01 = "How are you" list_temp = str01.split(" ") str_result = " ".join(list_temp[::-1]) print(str_result)