Quick Start with Python Programming

References

1. Environment configuration

2. Variables and simple data types

2.1 Variables

  • A variable called message is added. Each variable points to a value: the information associated with that variable is the pointed-to values ​​are the texts "Hello Python world!" and "Hello Python Crash Course world!"
    • The value of the variable can be modified at any time in the program, and Python will always record the latest value of the variable
    message = "Hello Python world!"
    print(message)
    
    message = "Hello Python Crash Course world!"
    print(message)
    
    Hello Python world!
    Hello Python Crash Course world!
    

2.1.1 Naming and using variables

  • Variable names can only contain letters, numbers, and underscores . Variable names can start with a letter or an underscore, but not a number
    • For example, you can name a variable message_1 but not 1_message
  • Variable names cannot contain spaces, but underscores can be used to separate words
    • For example, the variable name greeting_message works, but the variable name greeting message throws an error
  • Don't use Python keywords and function names as variable names
    • i.e. don't use words that Python reserves for special purposes like print
  • Variable names should be short and descriptive
    • For example, name is better than n, student_name is better than s_n, name_length is better than length_of_persons_name
  • Use the lowercase l and uppercase O sparingly , as they can be mistaken for the numbers 1 and 0
  • It is recommended to use lowercase Python variable names instead of uppercase letters

2.2 Strings

  • A string is simply a sequence of characters. In Python, all strings are enclosed in quotation marks , and the quotation marks can be single quotation marks or double quotation marks
    "This is a string."
    'This is also a string.'
    
    'I told my friend, "Python is my favorite language!"'
    "The language 'Python' is named after Monty Python, not the snake."
    

2.2.1 Use the method to modify the case of the string

  • One of the simplest things you can do with strings is to change the case of words in them
    • Many times the user cannot be relied upon to provide the correct case, so strings need to be converted to lowercase before storing them. When you need to display this information later, convert it to the most appropriate case
    name = "Ada Lovelace"
    
    print(name.title())  # 单词首字母大写
    print(name.upper())
    print(name.lower())
    
    Ada Lovelace
    ADA LOVELACE
    ada lovelace
    

2.2.2 Using variables in strings

  • Use the variable's value in a string. For example, use two variables for first name and last name, then combine the two values ​​to display the first name
    • To insert the value of a variable in a string, you can add the letter f before the quotation marks, and then put the variable to be inserted in curly braces. This kind of string is called an f string, and f is short for format (setting format)
    first_name = "ada"
    last_name = "lovelace"
    full_name = f"{
            
            first_name} {
            
            last_name}"
    
    message = f"Hello, {
            
            full_name.title()}!"
    
    print(message)
    
    Hello, Ada Lovelace!
    

2.2.3 Using tabs or newlines to add white space

  • Whitespace refers to any non-printing characters such as spaces, tabs, and newlines
    • To add a tab character to a string, use the character combination \t
    • To add a newline to a string, use the character combination \n
    print("\tPython")
    print("Languages:\nPython\nC\nJavaScript")
    
    	Python
    Languages:
    Python
    C
    JavaScript
    

2.2.4 Delete blanks

  • Python can find extra whitespace at the beginning and end of strings. To ensure that there are no blanks at the end of the string, you can use the method rstrip(). To permanently delete blanks in this string, you must associate the result of the deletion operation with a variable
    • You can also remove the blanks at the beginning of the string, or remove the blanks on both sides of the string at the same time, using the methods lstrip() and strip() respectively
    favorite_language = 'python '
    print(favorite_language)
    
    favorite_language = favorite_language.rstrip()
    print(favorite_language)
    
    'python '
    'python'
    

2.3 Number

2.3.1 Integers

  • In Python, integers can be added (+), subtracted (-), multiplied (*) and divided (/)
  • Python uses two multiplication signs to represent power operations
  • In a terminal session, Python directly returns the result of the operation
    print(2 + 3, 3 - 2, 2 * 3, 3 / 2, 3 ** 2, (2 + 3) * 4)
    
    5 1 6 1.5 9 20
    

2.3.2 Floating point numbers

  • Python refers to all numbers with a decimal point as floating point numbers
    print(0.1 + 0.1, 2 * 0.1, 0.2 + 0.1, 3 * 0.1)
    
    # 结果包含的小数位数可能是不确定的
    0.2 0.2 0.30000000000000004 0.30000000000000004
    

2.3.3 Integers and floating point numbers

  • When dividing any two numbers, the result is always a floating-point number, even if both numbers are integers and divisible evenly
  • If one operand is an integer and the other operand is a floating point number, the result is always a floating point number
    print(4 / 2, 1 + 2.0, 2 * 3.0, 3.0 ** 2)
    
    2.0 3.0 6.0 9.0
    

2.3.4 Underscores in numbers

  • When writing a large number, you can use underscores to group the numbers in it to make it easier to read. When printing such a number defined with underscores, Python will not print the underscores
    universe_age = 14_000_000_000
    print(universe_age)
    
    14000000000
    

2.3.5 Assigning values ​​to multiple variables at the same time

  • Multiple variables can be assigned values ​​in one line of code, which helps to shorten programs and improve their readability. This practice is most commonly used to assign a series of numbers to a set of variables. As long as there are the same number of variables and values, Python correctly associates them
    x, y, z = 0, 0, 0
    

2.3.6 Constants

  • Constants are similar to variables, but their values ​​remain the same throughout the life of the program. Python doesn't have a built-in constant type, but Python programmers use all-caps to indicate that a variable should be treated as a constant whose value should never change
    MAX_CONNECTIONS = 5000
    print(MAX_CONNECTIONS)
    

2.4 Notes

  • In Python, comments are identified with a pound sign (#). Anything after the pound sign will be ignored by the Python interpreter
    # 向大家问好。
    print("Hello Python people!")
    
    Hello Python people!
    

3. List Introduction

3.1 What is a list

  • A list consists of a series of elements arranged in a specific order

    • You can create lists containing all the letters of the alphabet, the numbers 0-9, or the names of all family members, or you can add anything to the list without any relationship between the elements
    • Lists usually contain multiple elements, so a list can be assigned a plural name (letters, digits, or names)
  • In Python, lists are denoted by square brackets ([]) and comma-separated elements

    bicycles = ['trek', 'cannondale', 'redline', 'specialized']
    print(bicycles)
    
    ['trek', 'cannondale', 'redline', 'specialized']
    

3.1.1 Accessing List Elements

  • Lists are ordered collections, so to access any element of a list, just tell Python the position (index) of that element
    bicycles = ['trek', 'cannondale', 'redline', 'specialized']
    print(bicycles[0])
    print(bicycles[0].title())
    
    trek
    Trek
    

3.1.2 Indexes start at 0 instead of 1

  • In Python, the index of the first list element is 0, not 1
  • Python provides a special syntax for accessing the last list element. By specifying the index as -1
    bicycles = ['trek', 'cannondale', 'redline', 'specialized']
    
    print(bicycles[1])    # 访问第 2 个元素
    print(bicycles[3])    # 访问第 4 个元素
    print(bicycles[-1])   # 访问最后一个元素
    

3.1.3 Using individual values ​​in a list

  • Use each value in the list like any other variable. For example, use f-strings to create messages from values ​​in a list
    bicycles = ['trek', 'cannondale', 'redline', 'specialized']
    message = f"My first bicycle was a {
            
            bicycles[0].title()}."
    
    print(message)
    
    My first bicycle was a Trek.
    

3.2 Modifying, adding and deleting elements

3.2.1 Modify list elements

  • Suppose there is a list of motorcycles, the first element of which is 'honda', how to modify its value?
    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    
    motorcycles[0] = 'ducati'
    print(motorcycles)
    
    ['honda', 'yamaha', 'suzuki']
    ['ducati', 'yamaha', 'suzuki']
    

3.2.2 Adding elements to a list

  • Add element at the end of the list

    • When adding a new element to a list, the easiest way is to append the element to the list
    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    
    motorcycles.append('ducati')
    print(motorcycles)
    
    ['honda', 'yamaha', 'suzuki']
    ['honda', 'yamaha', 'suzuki', 'ducati']
    
    • The method append() makes it easy to create lists dynamically. For example, you can create an empty list and then use a series of function calls to append() to add elements
    motorcycles = []
    motorcycles.append('honda')
    motorcycles.append('yamaha')
    motorcycles.append('suzuki')
    
    print(motorcycles)
    
    ['honda', 'yamaha', 'suzuki']
    
  • insert elements into the list

    • Use the method insert() to add new elements anywhere in the list
    motorcycles = ['honda', 'yamaha', 'suzuki']
    motorcycles.insert(0, 'ducati')
    
    print(motorcycles)
    
    ['ducati', 'honda', 'yamaha', 'suzuki']
    

3.2.3 Removing an element from a list

  • Delete elements using the del statement

    • If you know the position of the element to be deleted in the list, you can use the del statement
    • Once a value is removed from a list using the del statement, it can no longer be accessed
    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    del motorcycles[0]
    
    print(motorcycles)
    
    ['honda', 'yamaha', 'suzuki']
    ['yamaha', 'suzuki']
    
  • Use the method pop() to remove an element

    • The method pop() removes the element at the end of the list and can then use it . The term pop comes from the analogy that a list is like a stack, and removing an element at the end of the list is equivalent to popping the top element of the stack
    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    
    popped_motorcycle = motorcycles.pop()
    
    print(motorcycles)
    print(popped_motorcycle)
    
    ['honda', 'yamaha', 'suzuki']
    ['honda', 'yamaha']
    suzuki
    
  • element at any position in the popup list

    • You can use pop() to delete elements anywhere in the list, just specify the index of the element to be deleted in parentheses
    • Whenever pop() is used, the popped element is no longer in the list
    motorcycles = ['honda', 'yamaha', 'suzuki']
    first_owned = motorcycles.pop(1)
    
    print(f"The first motorcycle I owned was a {
            
            first_owned.title()}.")
    
    The first motorcycle I owned was a Yamaha.
    
  • remove element by value

    • It is not known where the value to be removed from the list resides. And only know the value of the element to be removed, you can use the method remove()
    • When using remove() to remove an element from a list, its value can then also be used
    • The method remove() removes only the first specified value. If the value to be removed may appear multiple times in the list, a loop is needed to ensure that each value is removed
    motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
    print(motorcycles)
    
    motorcycles.remove('ducati')
    
    print(motorcycles)
    
    ['honda', 'yamaha', 'suzuki', 'ducati']
    ['honda', 'yamaha', 'suzuki']
    

3.3 Organization List

3.3.1 Using sort() to permanently sort a list

  • The Python method sort() makes it relatively easy to sort a list. Suppose you have a list of cars and want to sort the cars in alphabetical order

    • The method sort() permanently modifies the sort order of the list elements. Cars are now in alphabetical order and can never be returned to their original order
    cars = ['bmw', 'audi', 'toyota', 'subaru']
    cars.sort()
    
    print(cars)
    
    ['audi', 'bmw', 'subaru', 'toyota']
    
  • You can also arrange the list elements in reverse alphabetical order

    cars = ['bmw', 'audi', 'toyota', 'subaru']
    cars.sort(reverse = True)
    
    print(cars)
    
    ['toyota', 'subaru', 'bmw', 'audi']
    

3.3.2 Use sorted() to temporarily sort the list

  • To preserve the original sorting order of the list elements while presenting them in a specific order, use the function sorted()
    cars = ['bmw', 'audi', 'toyota', 'subaru']
    
    print("Here is the original list:", cars)
    print("Here is the sorted list:", sorted(cars))
    print("Here is the original list again:", cars)
    
    Here is the original list: ['bmw', 'audi', 'toyota', 'subaru']
    Here is the sorted list: ['audi', 'bmw', 'subaru', 'toyota']
    Here is the original list again: ['bmw', 'audi', 'toyota', 'subaru']
    

3.3.3 Print the list backwards

  • To reverse the sort order of list elements, use the method reverse(). Assuming the list of cars is ordered by time of purchase, it's easy to sort the cars in it in reverse order
    • reverse() does not sort the list elements in reverse alphabetical order, but just reverses the order in which the list elements are sorted
    • reverse() permanently modifies the order of the list elements, but can be restored to the original order at any time by calling reverse() on the list again
    cars = ['bmw', 'audi', 'toyota', 'subaru']
    print(cars)
    
    cars.reverse()
    print(cars)
    
    ['bmw', 'audi', 'toyota', 'subaru']
    ['subaru', 'toyota', 'audi', 'bmw']
    

3.3.4 Determining the length of the list

  • Use the function len() to quickly know the length of the list. In the example below, the list contains four elements, so its length is 4
    cars = ['bmw', 'audi', 'toyota', 'subaru']
    print(len(cars))
    

3.4 Avoid indexing errors when using lists

  • There is a common error encountered when working with lists. Suppose you have a list with three elements and ask for the fourth element
    • Whenever you need to access the last list element, you can use index -1 , this way of accessing the last element will cause an error only if the list is empty
    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles[3])
    
    Traceback (most recent call last):
        File "motorcycles.py", line 2, in <module>
            print(motorcycles[3])
    IndexError: list index out of range
    

4. Operation list

4.1 Traversing the entire list

  • Suppose there is a list of magicians, and the name of each magician needs to be printed out. The following uses a for loop to print all the names in the list of magicians
    magicians = ['alice', 'david', 'carolina'] 
    for magician in magicians: 
        print(f"{
            
            magician.title()}, that was a great trick!")
        print(f"I can't wait to see your next trick, {
            
            magician.title()}.\n")
        
    print("Thank you, everyone. That was a great magic show!")
    
    Alice, that was a great trick!
    I can't wait to see your next trick, Alice.
    
    David, that was a great trick!
    I can't wait to see your next trick, David.
    
    Carolina, that was a great trick!
    I can't wait to see your next trick, Carolina.
    
    Thank you, everyone. That was a great magic show!
    

4.2 Avoiding indentation errors

4.2.1 Forgetting to indent

  • Be sure to indent the lines of code that follow the for statement and are part of the loop . If you forget to indent, Python will remind you
    magicians = ['alice', 'david', 'carolina']
    for magician in magicians:
    print(magician)
    
    File "magicians.py", line 3
        print(magician)
        ^
    IndentationError: expected an indented block
    

4.2.2 Forgetting to indent extra lines of code

  • The following is a logical error. From a syntactic point of view, the code is legal, but due to the logical error, the result is not as expected
    magicians = ['alice', 'david', 'carolina']
    for magician in magicians:
        print(f"{
            
            magician.title()}, that was a great trick!")
    print(f"I can't wait to see your next trick, {
            
            magician.title()}.\n")
    
    Alice, that was a great trick!
    David, that was a great trick!
    Carolina, that was a great trick!
    I can't wait to see your next trick, Carolina.
    

4.2.3 Unnecessary indentation

  • If you accidentally indent a line of code that doesn't need to be indented, Python will point this out
    • The function call print() does not need to be indented because it is not part of the loop
    message = "Hello Python world!"
        print(message)
    
    File "hello_world.py", line 2
        print(message)
        ^
    IndentationError: unexpected indent
    

4.3 Create a list of values

4.3.1 Using the function range()

  • The Python function range() can easily generate a range of numbers
    for value in range(1, 5):
        print(value)
    
    1
    2
    3
    4
    

4.3.2 Using range() to create a list of numbers

  • To create a list of numbers, use the function list() to convert the result of range() directly into a list. If range() is given as an argument to list(), the output will be a list of numbers

    numbers = list(range(1, 6))
    print(numbers)
    
    [1, 2, 3, 4, 5]
    
  • When using the function range(), the step size can also be specified. To do this, you can specify a third parameter to this function, and Python will generate numbers according to this step

    even_numbers = list(range(2, 11, 2)) 
    print(even_numbers)
    
    [2, 4, 6, 8, 10]
    
  • Add the squares of the first 10 integers to a list

    squares = []
    for value in range(1,11):
        squares.append(value**2)  # 计算每个值的平方,并立即将结果附加到列表 squares 的末尾
    
    print(squares)
    
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    

4.3.3 Performing simple statistical calculations on lists of numbers

  • There are several Python functions specifically for manipulating lists of numbers Finding the maximum, minimum and sum of lists of numbers
    digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    
    print(min(digits), max(digits), sum(digits))
    
    0 9 45
    

4.3.4 List Comprehensions

  • The method of generating the list squares described above contains three or four lines of code, and list comprehension allows only one line of code to generate such a list
    • A list comprehension combines the for loop and the code for creating a new element into one line, and appends the new element automatically
    # for 循环将值 1~10 提供给表达式 value**2,此处无冒号
    squares = [value**2 for value in range(1, 11)]
    print(squares)
    
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    

4.4 Using part of a list

4.4.1 Slicing

  • To create a slice, specify the index of the first and last element to use . Like the function range(), Python stops after reaching the element before the second index. To output the first three elements in the list, you need to specify the indices 0 and 3, which will return the elements with indices 0, 1 and 2

    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    
    print(players[0:3])
    
    ['charles', 'martina', 'michael']
    
  • If no first index is specified, Python will automatically start at the beginning of the list

    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print(players[:4])
    
    ['charles', 'martina', 'michael', 'florence']
    
  • To make the slice terminate at the end of the list

    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print(players[2:])
    
    ['michael', 'florence', 'eli']
    
  • Negative indices return elements at the corresponding distance from the end of the list , so arbitrary slices of the end of the list can be output. For example, if you want to output the last three players on the list

    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print(players[-3:])
    
    ['michael', 'florence', 'eli']
    

4.4.2 Traversing slices

  • If you want to iterate over some elements of a list, you can use slices in a for loop. The following example loops through the first three players and prints their names
    players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
    
    print("Here are the first three players on my team:")
    for player in players[:3]:
        print(player.title())
    
    Here are the first three players on my team:
    Charles
    Martina
    Michael
    

4.4.3 Copy list

  • To copy a list, create a slice containing the entire list by omitting both the start and end indexes ([:]). This tells Python to create a slice starting at the first element and ending at the last element, i.e. a copy of the entire list
    my_foods = ['pizza', 'falafel', 'carrot cake'] 
    friend_foods = my_foods[:]  # 将 my_foods 的元素复制到新列表 friend_foods 中  
    # 如果只是将 my_foods 赋给 friend_foods ,就不能得到两个列表
    # friend_foods = my_foods
    
    # 在每个列表中都添加一种食品
    my_foods.append('cannoli')
    friend_foods.append('ice cream')
    
    print("My favorite foods are:")
    print(my_foods)
    
    print("\nMy friend's favorite foods are:")
    print(friend_foods)
    
    My favorite foods are:
    ['pizza', 'falafel', 'carrot cake', 'cannoli']
    
    My friend's favorite foods are:
    ['pizza', 'falafel', 'carrot cake', 'ice cream']
    

4.5 tuples

  • Lists are very suitable for storing data sets that may change during program execution. Lists can be modified. However, sometimes it is necessary to create a series of unmodifiable elements. Tuples can meet this demand
    • Python calls immutable values ​​immutable and immutable lists tuples

4.5.1 Defining tuples

  • Tuples look a lot like lists, but are identified using parentheses rather than square brackets . Once a tuple is defined, its elements can be accessed using an index, just like list elements
    • For example, if you have a rectangle whose size should not change, you can store its length and width in a tuple, thus ensuring that they cannot be modified
    dimensions = (200, 50)
    
    print(dimensions[0])
    print(dimensions[1])
    
    200
    50
    

4.5.2 Iterating over all values ​​in a tuple

  • Like a list, a for loop can also be used to iterate over all the values ​​in a tuple
    dimensions = (200, 50)
    for dimension in dimensions:
        print(dimension)
    
    200
    50
    

4.5.3 Modifying tuple variables

  • Although you cannot modify the elements of the tuple, you can assign values ​​​​to the variables that store the tuple
    dimensions = (200, 50)
    print("Original dimensions:")
    for dimension in dimensions:
        print(dimension)
    
    dimensions = (400, 100)
    print("\nModified dimensions:")
    for dimension in dimensions:
        print(dimension)
    
    Original dimensions:
    200
    50
    
    Modified dimensions:
    400
    100
    

5. if statement

5.1 A simple example

  • Suppose you have a list of cars and want to print the name of each car in it. For most cars, the name should be printed in initial capitals, but for the car name 'bmw', it should be printed in all caps. The following code iterates through the list and prints the names of the cars in it with the first letter capitalized, but for 'bmw', it is printed in all uppercase
    cars = ['audi', 'bmw', 'subaru', 'toyota']
    
    for car in cars:
        if car == 'bmw':
            print(car.upper())
        else:
            print(car.title())
    
    Audi
    BMW
    Subaru
    Toyota
    

5.2 Conditional testing

  • At the heart of every if statement is an expression that evaluates to True or False, known as a conditional test. Python decides whether to execute the code in the if statement based on whether the value of the conditional test is True or False

5.2.1 Checking for equality

  • The simplest condition test: check if the value of a variable is equal to a specific value
    car = 'bmw'
    
    print(car == 'bmw')
    print(car == 'audi')
    
    True
    False
    

5.2.2 Checking for inequality

  • To determine whether two values ​​are not equal, combine an exclamation point with an equal sign (!=)
  • Let's use another if statement to demonstrate how to use the inequality operator. will assign the requested pizza topping to a variable, and print a message indicating whether the topping requested by the customer is anchovies
    requested_topping = 'mushrooms'
    
    if requested_topping != 'anchovies':
        print("Hold the anchovies!")
    
    Hold the anchovies!
    

5.2.3 Numerical comparison

  • The value of answer (17) is not 42, so the indented code block is executed
    • Conditional statements can contain various mathematical comparisons, such as less than, less than or equal to, greater than, greater than or equal to
    answer = 17
    
    if answer != 42:
        print("That is not the correct answer. Please try again!")
    
    print(answer < 21, answer > 21, answer >= 21, answer <= 21)
    
    That is not the correct answer. Please try again!
    True False False True
    

5.2.4 Checking multiple conditions

  • You may want to check multiple conditions at the same time. For example, sometimes it is necessary to perform the corresponding operation when both conditions are true, and sometimes only one condition is required to be true

  • Use and to check multiple conditions

    • To check whether both conditions are true, use the keyword and to combine the two conditional tests into one. The entire expression is True if every test passes; the entire expression is False if at least one test fails
    age_0 = 22
    age_1 = 18
    
    print((age_0 >= 21) and (age_1 >= 21))
    
    False
    
  • Use or to check multiple conditions

    • The or keyword also lets you check for multiple conditions, but only if at least one of the conditions is met will the entire test pass. Expressions using or are False only if neither test passes
    age_0 = 22
    age_1 = 18
    
    print((age_0 >= 21) or (age_1 >= 21))
    
    True
    

5.2.5 Checking whether a specific value is contained in a list

  • To determine whether a specific value is included in the list, use the keyword in
  • To determine whether a specific value is not included in the list, use the keyword not in
    available_toppings = ['mushrooms', 'olives', 'green peppers',
                          'pepperoni', 'pineapple', 'extra cheese']
    
    requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
    
    for requested_topping in requested_toppings:
        if requested_topping not in available_toppings:
            print(f"Adding {
            
            requested_topping}.")
        else:
            print(f"Sorry, we don't have {
            
            requested_topping}.")
            
    print("\nFinished making your pizza!")
    
    Sorry, we don't have mushrooms.
    Adding french fries.
    Sorry, we don't have extra cheese.
    
    Finished making your pizza!
    

5.2.6 Boolean expressions

  • Boolean expressions are an alias for conditional tests. Like conditional expressions, Boolean expressions evaluate to either True or False

5.3 if statement

5.3.1 Simple if statement

  • Suppose there is a variable representing someone's age, and you want to know whether this person is of age to vote
    age = 19
    if age >= 18:
        print("You are old enough to vote!")
    
    You are old enough to vote!
    

5.3.2 if-else statement

  • If you need to perform one operation when the conditional test is passed, and another operation when it is not passed, you can use the if-else statement
    age = 17
    if age >= 18:
        print("You are old enough to vote!")
        print("Have you registered to vote yet?")
    else:
        print("Sorry, you are too young to vote.")
        print("Please register to vote as soon as you turn 18!")
    
    Sorry, you are too young to vote.
    Please register to vote as soon as you turn 18!
    

5.3.3 if-elif-else structure

  • It is often necessary to check more than two situations , for which the if-elif-else structure provided by Python can be used
    age = 12
    
    if age < 4:
        price = 0
    elif age < 18:
        price = 25
    else:
        price = 40
    
    print(f"Your admission cost is ${
            
            price}.")
    
    Your admission cost is $25.
    

5.3.4 Using multiple elif blocks

  • Use as many elif blocks as you want. For example, assuming that the aforementioned playground wants to offer discounts to the elderly, a conditional test can be added to determine whether the customer is eligible for the discount. The following assumes that for seniors over 65 years old (inclusive), tickets can be purchased at half price
    age = 66
    
    if age < 4:
        price = 0
    elif age < 18:
        price = 25
    elif age < 65:
        price = 40
    elif age >= 65:
        price = 20
    # Python 并不要求 if-elif 结构后面必须有 else 代码块
    
    print(f"Your admission cost is ${
            
            price}.")
    
    Your admission cost is $20.
    

5.3.5 Testing multiple conditions

  • If you want to execute only one block of code, use if-elif-else structure, if you want to execute multiple blocks of code, use a series of independent if statements
    requested_toppings = ['mushrooms', 'extra cheese']
    if 'mushrooms' in requested_toppings:
        print("Adding mushrooms.")
    if 'pepperoni' in requested_toppings:
        print("Adding pepperoni.")
    if 'extra cheese' in requested_toppings:
        print("Adding extra cheese.")
    
    print("\nFinished making your pizza!")
    
    Adding mushrooms.
    Adding extra cheese.
    
    Finished making your pizza!
    

5.4 Processing lists with if statements

5.4.1 Checking for special elements

  • Continuing with the previous pizzeria example. This pizzeria prints a message for every topping added to its pizza. By creating a list with the toppings the customer ordered and using a loop to indicate which toppings to add to the pizza
  • However, if the pizzeria runs out of green peppers, you can include an if statement in the for loop
    requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
    
    for requested_topping in requested_toppings:
        if requested_topping == 'green peppers':
            print("Sorry, we are out of green peppers right now.")
        else:
            print(f"Adding {
            
            requested_topping}.")
    
    print("\nFinished making your pizza!")
    
    Adding mushrooms.
    Sorry, we are out of green peppers right now.
    Adding extra cheese.
    
    Finished making your pizza!
    

5.4.2 Using multiple lists

  • The following example defines two lists, where the first list contains the toppings that the pizzeria serves and the second list contains the toppings that customers order. This time for each element in requested_toppings, check to see if it is a topping that the pizzeria serves, and then decide whether to add it to the pizza
    available_toppings = ['mushrooms', 'olives', 'green peppers',
                          'pepperoni', 'pineapple', 'extra cheese']
    
    requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
    
    for requested_topping in requested_toppings:
        if requested_topping in available_toppings:
            print(f"Adding {
            
            requested_topping}.")
        else:
            print(f"Sorry, we don't have {
            
            requested_topping}.")
            
    print("\nFinished making your pizza!")
    
    
    Adding mushrooms.
    Sorry, we don't have french fries.
    Adding extra cheese.
    
    Finished making your pizza!
    

6. Dictionary

6.1 Using dictionaries

  • In Python, a dictionary is a sequence of key-value pairs . Each key is associated with a value, and the associated value can be accessed using the key. The value associated with the key can be a number, string, list or even a dictionary, any Python object can be used as the value in the dictionary
  • In Python, a dictionary is represented by a series of key-value pairs enclosed in curly braces ({})
    • Keys and values ​​are separated by colons, and key-value pairs are separated by commas
    • In a dictionary, you can store as many key-value pairs as you want
    alien_0 = {
          
          'color' : 'green', 'points' : 5}
    

6.1.1 Accessing values ​​in a dictionary

  • To get the value associated with a key, specify the dictionary name followed by the key enclosed in square brackets
    alien_0 = {
          
          'color': 'green'}
    print(alien_0['color'])
    
    green
    
    alien_0 = {
          
          'color': 'green', 'points': 5}
    new_points = alien_0['points']
    
    print(f"You just earned {
            
            new_points} points!")
    
    You just earned 5 points!
    

6.1.2 Add key-value pairs

  • A dictionary is a dynamic structure where key-value pairs can be added at any time
    • To add a key-value pair, specify the dictionary name, the key enclosed in square brackets, and the associated value
    • Add two pieces of information to dictionary alien_0: alien xxx coordinate andyyThe y coordinate, which can display the alien at a specific position on the screen
    alien_0 = {
          
          'color': 'green', 'points': 5}
    print(alien_0)
    
    alien_0['x_position'] = 0
    alien_0['y_position'] = 25
    print(alien_0)
    
    {
          
          'color': 'green', 'points': 5}
    {
          
          'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}
    

6.1.3 Create an empty dictionary first

  • You can use a pair of empty curly braces to define a dictionary first, and then add each key-value pair separately
    • When using a dictionary to store user-supplied data or writing code that automatically generates a large number of key-value pairs, it is usually necessary to define an empty dictionary first
    alien_0 = {
          
          }
    alien_0['color'] = 'green'
    alien_0['points'] = 5
    
    print(alien_0)
    
    {
          
          'color': 'green', 'points': 5}
    

6.1.4 Modify the value in the dictionary

  • To modify a value in a dictionary, specify the dictionary name, the key enclosed in square brackets, and the new value associated with that key
    alien_0 = {
          
          'color': 'green'}
    print(f"The alien is {
            
            alien_0['color']}.")
    
    alien_0['color'] = 'yellow'
    print(f"The alien is now {
            
            alien_0['color']}.")
    
    The alien is green.
    The alien is now yellow.
    

6.1.5 Delete key-value pairs

  • For information that is no longer needed in the dictionary, you can use the del statement to completely delete the corresponding key-value pair. When using the del statement, you must specify the dictionary name and the key to delete
    alien_0 = {
          
          'color': 'green', 'points': 5}
    print(alien_0)
    
    del alien_0['points']
    print(alien_0)
    
    {
          
          'color': 'green', 'points': 5}
    {
          
          'color': 'green'}
    

6.1.6 Dictionaries of similar objects

  • In the previous example, the dictionary stores multiple information about one object (an alien in the game), but it is also possible to use a dictionary to store the same information about many objects
    favorite_languages = {
          
          
        'jen': 'python',
        'sarah': 'c',
        'edward': 'ruby',
        'phil': 'python',
        }
    
    language = favorite_languages['sarah'].title()
    print(f"Sarah's favorite language is {
            
            language}.")
    
    Sarah's favorite language is C.
    

6.1.7 Using get() to access values

  • This can cause problems when retrieving a value of interest from a dictionary with a key enclosed in square brackets: an error occurs if the specified key does not exist
    • You can avoid such errors by using the method get() to return a default value if the specified key does not exist
    • The first parameter of the method get() is used to specify the key, which is essential; the second parameter is the value to be returned when the specified key does not exist, and is optional
    alien_0 = {
          
          'color': 'green', 'speed': 'slow'}
    point_value = alien_0.get('points', 'No point value assigned.')
    
    print(point_value)
    
    No point value assigned.
    

6.2 Traversing the dictionary

6.2.1 Traverse all key-value pairs

  • What if you want to know all the information in the user dictionary? This dictionary can be traversed using a for loop
    user_0 = {
          
          
        'username': 'efermi',
        'first': 'enrico',
        'last': 'fermi',
        }
    
    # items() 返回一个键值对列表
    for key, value in user_0.items():
        print(f"\nKey: {
            
            key}")
        print(f"Value: {
            
            value}")
    
    Key: username
    Value: efermi
    
    Key: first
    Value: enrico
    
    Key: last
    Value: fermi
    

6.2.2 Iterating over all keys in a dictionary

  • When you don't need to use the values ​​in the dictionary, the method keys() can traverse all the keys in the dictionary

    favorite_languages = {
          
          
        'jen': 'python',
        'sarah': 'c',
        'edward': 'ruby',
        'phil': 'python',
        }
    for name in favorite_languages.keys():
        print(name.title())
    
    Jen
    Sarah
    Edward
    Phil
    
  • You can also use the method keys() to determine whether a person has accepted a survey. The following code determines if Erin is surveyed

    favorite_languages = {
          
          
        'jen': 'python',
        'sarah': 'c',
        'edward': 'ruby',
        'phil': 'python',
        }
    if 'erin' not in favorite_languages.keys():
        print("Erin, please take our poll!")
    
    Erin, please take our poll!
    

6.2.3 Iterating over all keys in a dictionary in a specific order

  • One way to return elements in a specific order is to sort the returned keys in a for loop. To do this, use the function sorted() to obtain a copy of the list of keys in a specific order
    favorite_languages = {
          
          
        'jen': 'python',
        'sarah': 'c',
        'edward': 'ruby',
        'phil': 'python',
        }
    # 列出字典中的所有键,并在遍历前对这个列表进行排序
    for name in sorted(favorite_languages.keys()):
        print(f"{
            
            name.title()}, thank you for taking the poll.")
    
    Edward, thank you for taking the poll.
    Jen, thank you for taking the poll.
    Phil, thank you for taking the poll.
    Sarah, thank you for taking the poll.
    

6.2.4 Iterating over all values ​​in the dictionary

  • If you are mainly interested in the values ​​contained in the dictionary, you can use the method values() to return a list of values, without any keys
    favorite_languages = {
          
          
        'jen': 'python',
        'sarah': 'c',
        'edward': 'ruby',
        'phil': 'python',
        }
    print("The following languages have been mentioned:")
    for language in favorite_languages.values():
        print(language.title())
    
    The following languages have been mentioned:
    Python
    C
    Ruby
    Python
    
  • The above approach extracts all the values ​​​​in the dictionary without considering whether they are repeated
    • This may not be a problem when few values ​​are involved, but if there are many respondents the resulting list may contain a lot of duplicates
    • To remove duplicates, you can use a collection (set) , each element in the collection must be unique
    ...
    for language in set(favorite_languages.values()):
        print(language.title())
    ...
    
    The following languages have been mentioned:
    Ruby
    C
    Python
    

Collections can be created directly using a pair of curly braces, where elements are separated by commas

  • Sets and dictionaries are easily confused because they are both defined with a pair of curly braces
  • When there are no key-value pairs in the curly braces, the definition is likely to be a collection
  • Unlike lists and dictionaries, sets do not store elements in a specific order

6.3 Nesting

  • Sometimes it is necessary to store a sequence of dictionaries in a list , or a list as a value in a dictionary , this is called nesting

6.3.1 List of dictionaries

  • The dictionary alien_0 contains various information about one alien, but cannot store information about a second alien. How to manage hordes of aliens? One approach is to create a list of aliens, where each alien is a dictionary containing various information about that alien
    # 创建一个用于存储外星人的空列表
    aliens = []
    
    # 创建 30 个绿色的外星人
    for alien_number in range(30):
        new_alien = {
          
          'color': 'green', 'points': 5, 'speed': 'slow'}
        aliens.append(new_alien)
    
    # 使用 for 循环和 if 语句来修改部分外形人的颜色
    for alien in aliens[:3]:
        if alien['color'] == 'green':
            alien['color'] = 'yellow'
            alien['speed'] = 'medium'
            alien['points'] = 10
        
    # 使用一个切片来打印前 5 个外星人
    for alien in aliens[:5]:
        print(alien)
    print("...")
    print(f"Total number of aliens: {
            
            len(aliens)}")
    
    {
          
          'color': 'yellow', 'points': 10, 'speed': 'medium'}
    {
          
          'color': 'yellow', 'points': 10, 'speed': 'medium'}
    {
          
          'color': 'yellow', 'points': 10, 'speed': 'medium'}
    {
          
          'color': 'green', 'points': 5, 'speed': 'slow'}
    {
          
          'color': 'green', 'points': 5, 'speed': 'slow'}
    ...
    Total number of aliens: 30
    

6.3.2 Storing lists in dictionaries

  • Sometimes, it is desirable to store lists in dictionaries rather than dictionaries in lists
    • For example, how would you describe the pizza a customer ordered? If you use a list, you can only store the pizza toppings to be added; but if you use a dictionary, you can contain not only the list of toppings, but also other descriptions of the pizza
    # 创建一个字典,存储所点比萨的信息
    pizza = {
          
          
        'crust': 'thick',
        # 与 toppings 相关联的值是一个列表
        'toppings': ['mushrooms', 'extra cheese'],
        }
    
    # 如果函数调用 print() 中的字符串很长,可以在合适的位置分行
    # 只需要在每行末尾都加上引号,同时对于除第一行外的其他各行,都在行首加上引号并缩进
    print(f"You ordered a {
            
            pizza['crust']}-crust pizza "
        "with the following toppings:")
    
    # 从字典中提取配料列表
    for topping in pizza['toppings']:
        print("\t" + topping)
    
    You ordered a thick-crust pizza with the following toppings:
        mushrooms
        extra cheese
    
  • Whenever you need to associate a key to multiple values ​​in a dictionary, you can nest a list in the dictionary
    • In the previous example of favorite programming languages, if everyone's responses were stored in a list, respondents could choose from multiple favorite languages
    • In this case, when iterating over the dictionary, each respondent is associated with a list of languages, not a single language
    • Therefore, within the for loop that iterates over the dictionary, another for loop is needed to iterate through the list of languages ​​associated with the respondent
    favorite_languages = {
          
          
        'jen': ['python', 'ruby'],
        'sarah': ['c'],
        'edward': ['ruby', 'go'],
        'phil': ['python', 'haskell'],
        }
    
    for name, languages in favorite_languages.items():
        print(f"\n{
            
            name.title()}'s favorite languages are:")
        for language in languages:
            print(f"\t{
            
            language.title()}")
    
    Jen's favorite languages are:
        Python
        Ruby
    
    Sarah's favorite languages are:
        C
    
    Edward's favorite languages are:
        Ruby
        Go
    
    Phil's favorite languages are:
        Python
        Haskell
    

6.3.3 Storing dictionaries within dictionaries

  • Dictionaries can be nested within dictionaries, but code can quickly become complex when doing so
  • In the following program, three pieces of information are stored for each user: first name, last name, and place of residence. To access this information, loop through all usernames and access the info dictionary associated with each username
    # 字典 users 中包含两个键:用户名 'aeinstein' 和 'mcurie' 
    # 与每个键相关联的值都是一个字典,其中包含用户的名、姓和居住地
    users = {
          
          
        'aeinstein': {
          
          
            'first': 'albert',
            'last': 'einstein',
            'location': 'princeton',
            },
    
        'mcurie': {
          
          
            'first': 'marie',
            'last': 'curie',
            'location': 'paris',
            },
        }
    
    for username, user_info in users.items():
        print(f"\nUsername: {
            
            username}")
        # 开始访问内部的字典。变量 user_info 包含用户信息字典
        # 而该字典包含三个键:'first'、'last' 和 'location' 
        full_name = f"{
            
            user_info['first']} {
            
            user_info['last']}"
        location = user_info['location']
    
        print(f"\tFull name: {
            
            full_name.title()}")
        print(f"\tLocation: {
            
            location.title()}")
    
    Username: aeinstein
    	Full name: Albert Einstein
    	Location: Princeton
    
    Username: mcurie
    	Full name: Marie Curie
    	Location: Paris
    

7. User input and while loops

7.1 How the function input() works

  • The function input() pauses the program, waiting for the user to enter some text. After getting user input, Python assigns it to a variable for convenience
    • The function input() takes one parameter and the input is assigned to the variable message
    prompt = "\nTell me something, and I will repeat it back to you:"
    prompt += "\nEnter 'quit' to end the program. "
    
    active = True
    while active:
        message = input(prompt)
        
        if message == 'quit':
            active = False  # 退出循环
        else:
            print(message)
    
    Tell me something, and I will repeat it back to you:
    Enter 'quit' to end the program. Hello
    Hello
    

7.1.1 Using int() to get numeric input

  • The function int() converts the string representation of a number into a numeric representation
    height = input("How tall are you, in inches? ")
    height = int(height)
    
    if height >= 48:
        print("\nYou're tall enough to ride!")
    else:
        print("\nYou'll be able to ride when you're a little older.")
    
    How tall are you, in inches? 50
    
    You're tall enough to ride!
    

7.1.2 Modulo operator

  • The modulus operator (%) is a useful tool when dealing with numerical information, it divides two numbers and returns the remainder
  • The modulo operator doesn't tell how many times one number is another, only what the remainder is
    number = input("Enter a number, and I'll tell you if it's even or odd: ")
    number = int(number)
    
    if number % 2 == 0:
        print(f"\nThe number {
            
            number} is even.")
    else:
        print(f"\nThe number {
            
            number} is odd.")
    
    Enter a number, and I'll tell you if it's even or odd: 9
    
    The number 9 is odd.
    

7.2 Introduction to the while loop

  • A for loop is used to execute a block of code for each element in the collection, while a while loop runs until a specified condition is not met

7.2.1 Using while loops

  • You can use a while loop to count and print out the odd numbers from 1-10
    current_number = 0
    while current_number < 10:
        current_number += 1
        if current_number % 2 == 0:
            continue
        
        print(current_number)
    
    1
    3
    5
    7
    9
    

7.2.2 Use of flags

  • In a program that requires many conditions to be met before continuing to run, a variable can be defined to determine whether the entire program is active. This variable, called a flag , allows the program to continue running while the flag is True, and to stop the program if any event causes the flag to be False (see Section 7.1 for the code)

7.2.3 Use break to exit the loop

  • To exit a while loop, without running the rest of the code in the loop, regardless of the result of the conditional test, use the break statement
  • The break statement is used to control program flow and can be used to control which lines of code are executed and which are not
    prompt = "\nPlease enter the name of a city you have visited:"
    prompt += "\n(Enter 'quit' when you are finished.) "
    
    # 以 while True 打头的循环将不断运行,直到遇到 break 语句
    while True:
        city = input(prompt)
        
        if city == 'quit':
            break
        else:
            print(f"I'd love to go to {
            
            city.title()}!")
    
    Please enter the name of a city you have visited:
    (Enter 'quit' when you are finished.) Beijing
    I'd love to go to Beijing!
    
    Please enter the name of a city you have visited:
    (Enter 'quit' when you are finished.) quit
    
    Process finished with exit code 0
    

7.2.4 Using continue in a loop

  • To return to the beginning of the loop and decide whether to continue executing the loop according to the result of the condition test, you can use the continue statement, which does not execute the rest of the code and exit the entire loop like the break statement (see Section 7.2.1 for the code)

7.2.5 Avoiding infinite loops

  • Every while loop must have a way to stop running so that it doesn't execute endlessly
  • If the program gets stuck in an infinite loop, you can press Ctrl + C, or you can close the terminal window displaying the program's output
    • x has an initial value of 1, but doesn't change at all. So the conditional test x <= 5 is always True, causing the while loop to print 1 endlessly
    # 这个循环将没完没了地运行!
    x = 1
    while x <= 5:
        print(x)
    
    1
    1
    1
    ...
    

7.3 Using while loops to process lists and dictionaries

  • The above content only processes one piece of user information at a time: get the user's input, print the input or respond; when the loop runs again, learn another input value and respond. However, to log a large number of users and information, you need to use lists and dictionaries in the while loop
  • A for loop is an efficient way of traversing a list, but the list should not be modified within the for loop. To modify a list while iterating over it, use a while loop

7.3.1 Moving elements between lists

  • Suppose there is a list of newly registered but not yet authenticated website users. Once these users are authenticated, how do I move them to another list of authenticated users? One way is to use a while loop to extract the user from the list of unauthenticated users while the user is being authenticated, and add it to another list of authenticated users
    # 首先,创建一个待验证用户列表和一个用于存储已验证用户的空列表
    unconfirmed_users = ['alice', 'brian', 'candace']
    confirmed_users = []
    
    # 验证每个用户,直到列表 unconfirmed_users 变成空的
    while unconfirmed_users:
        # 从列表 unconfirmed_users 末尾删除未验证的用户
        current_user = unconfirmed_users.pop()
        
        print(f"Verifying user: {
            
            current_user.title()}")
        # 将每个经过验证的用户都移到已验证用户列表中
        confirmed_users.append(current_user)
        
    # 显示所有已验证的用户
    print("\nThe following users have been confirmed:")
    for confirmed_user in confirmed_users:
        print(confirmed_user.title())
    
    Verifying user: Candace
    Verifying user: Brian
    Verifying user: Alice
    
    The following users have been confirmed:
    Candace
    Brian
    Alice
    

7.3.2 Delete all list elements with a specific value

  • Suppose there is a list of pets, which contains multiple elements whose value is 'cat'. To remove all these elements, run a while loop until the value 'cat' is no longer in the list
    pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
    print(pets)
    
    while 'cat' in pets:
        pets.remove('cat')
        
    print(pets)
    
    ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
    ['dog', 'dog', 'goldfish', 'rabbit']
    

7.3.3 Populating a dictionary with user input

  • You can use a while loop to prompt the user for as much information as you like . The following creates a survey program in which the loop prompts for the respondent's name and answer each time it executes
    # 定义了一个空字典
    responses = {
          
          }
    
    # 设置一个标志,指出调查是否继续
    polling_active = True
    
    while polling_active:
        # 提示输入被调查者的名字和回答
        name = input("\nWhat is your name? ")
        response = input("Which mountain would you like to climb someday? ")
        
        # 将回答存储在字典中
        responses[name] = response
        
        # 看看是否还有人要参与调查
        repeat = input("Would you like to let another person respond? (yes/ no) ")
        if repeat == 'no':
            polling_active = False
            
    # 调查结束,显示结果
    print("\n--- Poll Results ---")
    for name, response in responses.items():
        print(f"{
            
            name} would like to climb {
            
            response}.")
    
    What is your name? Tom
    Which mountain would you like to climb someday? hah
    Would you like to let another person respond? (yes/ no) yes
    
    What is your name? Bob
    Which mountain would you like to climb someday? haha
    Would you like to let another person respond? (yes/ no) no
    
    --- Poll Results ---
    Tom would like to climb hah.
    Bob would like to climb haha.
    

8. Functions

8.1 Defining functions

8.1.1 Passing information to functions

  • Adding username allows the function to accept any value specified by username. Now, this function requires a value for username when it is called. When calling greet_user(), a name can be passed to it
    # 使用关键字 def 来告诉 Python 要定义一个函数
    # 紧跟在 def greet_user() 后面的所有缩进行构成了函数体
    # 文档字符串用三引号括起,Python 使用它们来生成有关程序中函数的文档
    def greet_user(username):
        """显示简单的问候语"""
        print(f"Hello, {
            
            username.title()}!")
    
    # 要调用函数,可依次指定函数名以及用圆括号括起的必要信息
    greet_user('jesse')
    
    Hello, Jesse!
    

8.1.2 Actual and formal parameters

  • In the definition of the function greet_user(), the variable username is a formal parameter (parameter), that is, the information that the function needs to do its job
  • In the code greet_user('jesse'), the value 'jesse' is an argument (argument), that is, the information passed to the function when calling it
  • In greet_user('jesse'), the actual parameter 'jesse' is passed to the function greet_user(), and this value is assigned to the formal parameter username

8.2 Passing arguments

  • A function definition may contain multiple formal parameters, so a function call may also contain multiple actual parameters. There are many ways to pass arguments to functions
    • Positional arguments can be used , which requires the order of the arguments to be the same as the order of the formal parameters
    • Keyword arguments are also available , where each argument consists of a variable name and a value
    • You can also use lists and dictionaries

8.2.1 Positional arguments

  • When calling a function, Python must associate each actual parameter in the function call with a formal parameter in the function definition. For this purpose, the simplest way of associating is based on the order of the actual parameters. positional arguments
    def describe_pet(animal_type, pet_name):
        """显示宠物的信息"""
        print(f"\nI have a {
            
            animal_type}.")
        print(f"My {
            
            animal_type}'s name is {
            
            pet_name.title()}.")
    
    describe_pet('hamster', 'harry')
    
    I have a hamster.
    My hamster's name is Harry.
    

8.2.2 Keyword arguments

  • Keyword arguments are name-value pairs passed to the function . Because the names and values ​​are associated directly in the arguments, there is no confusion when passing arguments to functions. Keyword arguments do not need to consider the order of arguments in the function call , and clearly indicate the purpose of each value in the function call
    def describe_pet(animal_type, pet_name):
        """显示宠物的信息"""
        print(f"\nI have a {
            
            animal_type}.")
        print(f"My {
            
            animal_type}'s name is {
            
            pet_name.title()}.")
    
    # 明确地指出了各个实参对应的形参
    # 关键字实参的顺序无关紧要,因为 Python 知道各个值该赋给哪个形参
    describe_pet(animal_type = 'hamster', pet_name = 'harry')
    
    I have a hamster.
    My hamster's name is Harry.
    

8.2.3 Default values

  • When writing a function, you can assign default values ​​to each parameter. When an argument is given to a formal parameter in the calling function, Python will use the specified argument value; otherwise, the default value of the formal parameter will be used . Therefore, after specifying a default value for a formal parameter, the corresponding actual parameter can be omitted in the function call ( when specifying a default value for a formal parameter, there should be no spaces on both sides of the equal sign )
    # 将形参 animal_type 设置默认值为'dog'
    def describe_pet(pet_name, animal_type='dog'):
    """显示宠物的信息。"""
    print(f"\nI have a {
            
            animal_type}.")
    print(f"My {
            
            animal_type}'s name is {
            
            pet_name.title()}.")
    
    describe_pet(pet_name = 'willie')
    # 由于显式地给 animal_type 提供了实参,Python 将忽略这个形参的默认值
    # describe_pet(pet_name='harry', animal_type='hamster')
    
    I have a dog.
    My dog's name is Willie.
    

8.3 Return value

  • Instead of always displaying output directly, a function can also manipulate some data and return a value or set of values. The value returned by a function is called the return value . In a function, use the return statement to return a value to the line of code that called the function

8.3.1 Returning simple values

  • Let's look at a function that takes a first and last name and returns the tidy name
    def get_formatted_name(first_name, last_name):
        """返回整洁的姓名"""
        full_name = f"{
            
            first_name} {
            
            last_name}"
        return full_name.title()
    
    # 提供一个变量,以便将返回的值赋给它
    musician = get_formatted_name('jimi', 'hendrix')
    print(musician)
    
    Jimi Hendrix
    

8.3.2 Making arguments optional

  • Sometimes it is desirable to make arguments optional so that the user of the function can provide additional information only when necessary. Default values ​​can be used to make arguments optional
    # 为了让中间名变成可选的,可给形参 middle_name 指定一个空的默认值
    # 并在用户没有提供中间名时不使用这个形参
    def get_formatted_name(first_name, last_name, middle_name=''):
        if middle_name:
            full_name = f"{
            
            first_name} {
            
            middle_name} {
            
            last_name}"
        else:
            full_name = f"{
            
            first_name} {
            
            last_name}"
            return full_name.title()
    
    musician = get_formatted_name('jimi', 'hendrix')
    print(musician)
    
    musician = get_formatted_name('john', 'hooker', 'lee')
    print(musician)
    
    Jimi Hendrix
    John Lee Hooker
    

8.3.3 Returning a dictionary

  • Functions can return any type of value, including more complex data structures such as lists and dictionaries. For example, the function below takes the components of a name and returns a dictionary representing a person
    # 可将 None 视为占位值
    def build_person(first_name, last_name, age=None):
        """返回一个字典,其中包含有关一个人的信息"""
        person = {
          
          'first': first_name, 'last': last_name}
        if age:
            person['age'] = age
        return person
    
    musician = build_person('jimi', 'hendrix', age = 27)
    print(musician)
    
    {
          
          'first': 'jimi', 'last': 'hendrix', 'age': 27}
    

8.3.4 Using functions with while loops

def get_formatted_name(first_name, last_name):
    full_name = f"{
      
      first_name} {
      
      last_name}"
    return full_name.title()

# 这是一个无限循环!
while True:
    print("\nPlease tell me your name:")
    print("(enter 'q' at any time to quit)")

    f_name = input("First name: ")
    if f_name == 'q':
        break

    l_name = input("Last name: ")
    if l_name == 'q':
        break
    
    formatted_name = get_formatted_name(f_name, l_name)
    print(f"\nHello, {
      
      formatted_name}!")
Please tell me your name:
(enter 'q' at any time to quit)
First name: Tom
Last name: Bun

Hello, Tom Bun!
...

8.4 Passing Lists

  • Suppose you have a list of users and you want to greet each of them. The following example passes a list of names to a function called greet_users() that greets everyone in the list
    def greet_users(names):
        """向列表中的每位用户发出简单的问候"""
        for name in names:
            msg = f"Hello, {
            
            name.title()}!"
            print(msg)
    
    usernames = ['hannah', 'ty', 'margot']
    greet_users(usernames)
    
    Hello, Hannah!
    Hello, Ty!
    Hello, Margot!
    

8.4.1 Modifying lists in functions

  • Once a list is passed to a function, it can be modified by the function. Any modifications made to this list within the function are permanent
    • Meet a company that makes 3D printed models of user-submitted designs. Designs that need to be printed are stored in one list and will be moved to another list after printing
    # 包含两个形参:一个需要打印的设计列表和一个打印好的模型列表
    def print_models(unprinted_designs, completed_models):
        # 模拟打印每个设计,直到没有未打印的设计为止
        # 打印每个设计后,都将其移到列表 completed_models 中
        while unprinted_designs:
            current_design = unprinted_designs.pop()
            print(f"Printing model: {
            
            current_design}")
            completed_models.append(current_design)
          
    # 包含一个形参:打印好的模型列表  
    def show_completed_models(completed_models):
        # 显示打印好的所有模型
        print("\nThe following models have been printed:")
        for completed_model in completed_models:
            print(completed_model)
            
    unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
    completed_models = []
    
    print_models(unprinted_designs, completed_models)
    show_completed_models(completed_models)
    
    Printing model: dodecahedron
    Printing model: robot pendant
    Printing model: phone case
    
    The following models have been printed:
    dodecahedron
    robot pendant
    phone case
    

When writing a function, if you find that it performs too many tasks, try dividing the code into two functions. It is always possible to call a function within another function, which helps to divide complex tasks into a series of steps

8.4.2 Prohibited functions from modifying the list

  • Assuming that even if all the designs are printed, the original list of unprinted designs should be kept for filing. But since moving all designs out of unprinted_designs, the list became empty
    • To solve this problem, a copy of the list can be passed to the function instead of the original . This way, any modifications made by the function will only affect the copy, leaving the original untouched. To pass a copy of the list to the function, you can do it like this
    # 切片表示法[:] 创建列表的副本
    function_name(list_name_[:])
    
    # 在 8.4.1 中,如果不想清空未打印的设计列表,可像下面这样调用 print_models()
    print_models(unprinted_designs[:], completed_models)
    

8.5 Passing any number of arguments

  • It is not known in advance how many actual parameters the function needs to accept, Python allows functions to collect any number of actual parameters from the calling statement
  • Consider a function that makes a pizza that accepts many toppings, but cannot predetermine how many toppings the customer will order. The following function has only one formal parameter *toppings , but no matter how many actual parameters are provided by the calling statement, this formal parameter will include them all
    # 形参名 *toppings 中的星号让 Python 创建一个名为 toppings 的空元组
    # 并将收到的所有值都封装到这个元组中
    def make_pizza(*toppings):
        print("\nMaking a pizza with the following toppings:")
        for topping in toppings:
            print(f"- {
            
            topping}")
    
    # 不管收到一个值还是三个值,这个函数都能妥善处理   
    make_pizza('pepperoni')
    make_pizza('mushrooms', 'green peppers', 'extra cheese')
    
    Making a pizza with the following toppings:
    - pepperoni
    
    Making a pizza with the following toppings:
    - mushrooms
    - green peppers
    - extra cheese
    

8.5.1 Combining positional and arbitrary number arguments

  • If you want a function to accept arguments of different types, you must place the formal parameter that takes any number of arguments last in the function definition . Python matches positional and keyword arguments first, then collects the remaining arguments into the last formal parameter
    def make_pizza(size, *toppings):
        print(f"\nMaking a {
            
            size}-inch pizza with the following toppings:")
        for topping in toppings:
            print(f"- {
            
            topping}")
    
    make_pizza(16, 'pepperoni')
    make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
    
    Making a 16-inch pizza with the following toppings:
    - pepperoni
    
    Making a 12-inch pizza with the following toppings:
    - mushrooms
    - green peppers
    - extra cheese
    

It is common to see the generic parameter name *args , which also collects any number of positional arguments

8.5.2 Using any number of keyword arguments

  • Sometimes it is necessary to accept an arbitrary number of arguments, but it is not known in advance what information will be passed to the function . In this case, the function can be written to accept any number of key-value pairs : as many as the calling statement provides
    # 形参 **user_info 中的两个星号让 Python 创建一个名为 user_info 的空字典
    # 并将收到的所有名称值对都放到这个字典中
    def build_profile(first, last, **user_info):
        """创建一个字典,其中包含知道的有关用户的一切"""
        user_info['first_name'] = first
        user_info['last_name'] = last
        return user_info
    
    user_profile = build_profile('albert', 'einstein',
                                 location='princeton',
                                 field='physics')
    print(user_profile)
    
    {
          
          'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}
    

8.6 Storing functions in modules

  • One of the advantages of using functions is that you can separate blocks of code from the main program. By giving the function a descriptive name, the main program is made much easier to understand. You can go a step further and store functions in separate files called modules , and then import the modules into the main program
    • The import statement allows code from a module to be used in the currently running program file

8.6.1 Importing entire modules

  • To make a function importable, a module must first be created. A module is a file with a .py extension that contains code to be imported into a program
    # pizza.py
    def make_pizza(size, *toppings):
        print(f"\nMaking a {
            
            size}-inch pizza with the following toppings:")
        for topping in toppings:
            print(f"- {
            
            topping}")
    
    # making_pizzas.py(与 pizza.py 处于同一目录)
    # 该行代码让 Python 打开文件 pizza.py,并将其中的所有函数都复制到这个程序中
    import pizza
    
    # 要调用被导入模块中的函数,可指定被导入模块的名称 pizza 和函数名 make_pizza(),并用句点分隔
    pizza.make_pizza(16, 'pepperoni')
    pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
    

8.6.2 Import specific functions

  • You can also import specific functions in a module. The syntax of this import method is as follows
    from module_name import function_name
    
  • Import as many functions as you want from a module by separating the function names with commas
    from module_name import function_0, function_1, function_2
    
  • For the previous making_pizzas.py example, if you only want to import the functions you want to use
    from pizza import make_pizza
    
    make_pizza(16, 'pepperoni')
    make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
    

8.6.3 Using as to assign an alias to a function

  • If the name of a function to be imported might conflict with an existing name in the program, or if the name of the function is too long, you can specify a short but unique alias: another name for the function, similar to a nickname . To give a function this special nickname, you need to specify it when importing it
    from pizza import make_pizza as mp
    mp(16, 'pepperoni')
    mp(12, 'mushrooms', 'green peppers', 'extra cheese')
    

8.6.4 Using as to assign an alias to a module

  • You can also specify an alias for a module. By assigning a short alias to the module (such as assigning the alias p to the module pizza)
    import pizza as p
    p.make_pizza(16, 'pepperoni')
    p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
    

8.6.5 Importing all functions in a module

  • Use the asterisk (*) operator to have Python import all functions in a module ( preferably not this way of importing )
    • May cause unexpected results if there are functions in the module with the same name as those used in the current project
    • Python may encounter multiple functions or variables with the same name and overwrite functions instead of importing all functions individually
    • Best practice: either import only the functions you need to use, or import the whole module and use period notation
    from pizza import *
    
    make_pizza(16, 'pepperoni')
    make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
    

9. class

9.1 Creating and using classes

  • Almost anything can be mocked using classes. Let's write a simple class Dog that represents a puppy, not a specific puppy, but any puppy
    • In Python, you can usually think of a capitalized name (such as Dog) to refer to the class, while a lowercase name (such as my_dog) refers to the instance created from the class, and the functions in the class are called methods.
    • __init__() is a special method that Python runs automatically whenever a new instance is created from the Dog class. In the name of this method, there are two underscores at the beginning and two at the end
    • self.age = age Variables accessible through instances like this are called properties
    class Dog:
        # 其中形参 self 必不可少,而且必须位于其他形参的前面
        # Python 调用这个方法来创建 Dog 实例时,将自动传入实参 self
        def __init__(self, name, age):
            """初始化属性 name 和 age"""
            # 以 self 为前缀的变量可供类中的所有方法使用,可以通过类的任何实例来访问
            self.name = name
            self.age = age
        
        # 每个与实例相关联的方法调用都自动传递实参 self 
        # 它是一个指向实例本身的引用,让实例能够访问类中的属性和方法
        def sit(self):
            """模拟小狗收到命令时蹲下"""
            print(f"{
            
            self.name} is now sitting.")
    
        def roll_over(self):
            """模拟小狗收到命令时打滚"""
            print(f"{
            
            self.name} rolled over!")
    
    # 创建表示特定小狗的实例
    my_dog = Dog('Willie', 6)
    your_dog = Dog('Lucy', 3)
    
    print(f"My dog's name is {
            
            my_dog.name}.")  # 要访问实例的属性,可使用句点表示法
    print(f"My dog is {
            
            my_dog.age} years old.")
    
    # 根据 Dog 类创建实例后,就能使用句点表示法来调用 Dog 类中定义的任何方法
    my_dog.sit()
    my_dog.roll_over()
    
    My dog's name is Willie.
    My dog is 6 years old.
    Willie is now sitting.
    Willie rolled over!
    

9.2 Working with classes and instances

  • Let's write a class that represents a car. It stores information about cars, and a method to aggregate this information
    class Car:
        def __init__(self, make, model, year):
            """初始化描述汽车的属性"""
            self.make = make
            self.model = model
            self.year = year
            # 创建实例时,有些属性无须通过形参来定义,可在方法 __init__() 中为其指定默认值
            self.odometer_reading = 0
            
        def get_descriptive_name(self):
            """返回整洁的描述性信息"""
            long_name = f"{
            
            self.year} {
            
            self.make} {
            
            self.model}"
            return long_name.title()
    
        def read_odometer(self):
            """打印一条指出汽车里程的消息"""
            print(f"This car has {
            
            self.odometer_reading} miles on it.")
    
        # 这个方法接受一个里程值,并将其赋给 self.odometer_reading
        def update_odometer(self, mileage):
            """将里程表读数设置为指定的值,禁止将里程表读数往回调"""
            if mileage >= self.odometer_reading:
                self.odometer_reading = mileage
            else:
                print("You can't roll back an odometer!")
    
        # 将属性值递增特定的量,而不是将其设置为全新的值
        def increment_odometer(self, miles):
            """将里程表读数增加指定的量"""
            self.odometer_reading += miles
        
    # 根据 Car 类创建了一个实例
    my_used_car = Car('subaru', 'outback', 2015)
    print(my_used_car.get_descriptive_name())
    
    my_used_car.update_odometer(23_500)
    my_used_car.read_odometer()
    
    my_used_car.increment_odometer(100)
    my_used_car.read_odometer()
    
    2015 Subaru Outback
    This car has 23500 miles on it.
    This car has 23600 miles on it.
    

9.3 Inheritance

  • If you want to write a class that is a special version of another existing class, you can use inheritance
    • When a class inherits another class, it will automatically get all the properties and methods of the other class
    • The original class is called the parent class, and the new class is called the subclass
    • The subclass inherits all the properties and methods of the parent class, and can also define its own properties and methods
    • For the method of the parent class, as long as it does not conform to the behavior of the object simulated by the subclass, it can be rewritten: a method with the same name as the parent class method to be rewritten can be defined in the subclass. In this way, Python will not consider this parent class method, but only focus on the corresponding method defined in the child class
    class Car:
        # 在既有类的基础上编写新类时,通常要调用父类的方法 __init__() 
        # 这将初始化在父类 __init__() 方法中定义的所有属性,从而让子类包含这些属性
        def __init__(self, make, model, year):
            self.make = make
            self.model = model
            self.year = year
            self.odometer_reading = 0
            
        def get_descriptive_name(self):
            long_name = f"{
            
            self.year} {
            
            self.make} {
            
            self.model}"
            return long_name.title()
        
        def read_odometer(self):
            print(f"This car has {
            
            self.odometer_reading} miles on it.")
            
        def update_odometer(self, mileage):
            if mileage >= self.odometer_reading:
                self.odometer_reading = mileage
            else:
                print("You can't roll back an odometer!")
        
        def increment_odometer(self, miles):
            self.odometer_reading += miles
    
    class Battery:
        def __init__(self, battery_size=75):
            """初始化电瓶的属性"""
            self.battery_size = battery_size
    
        def describe_battery(self):
            """打印一条描述电瓶容量的消息"""
            print(f"This car has a {
            
            self.battery_size}-kWh battery.")
    
        def get_range(self):
            """打印一条消息,指出电瓶的续航里程"""
            if self.battery_size == 75:
                range = 260
            elif self.battery_size == 100:
                range = 315
                
            print(f"This car can go about {
            
            range} miles on a full charge.")
    
    # 电动汽车是一种特殊的汽车,因此可在前面创建的 Car 类的基础上创建新类 ElectricCar
    # 定义子类时,必须在圆括号内指定父类的名称
    class ElectricCar(Car):
        """电动汽车的独特之处"""
        def __init__(self, make, model, year):
            """先初始化父类的属性,再初始化电动汽车特有的属性"""
            # 这行代码让 Python 调用 Car 类的方法 __init__()
            # 父类也称为超类(superclass),名称 super 由此而来
            super().__init__(make, model, year)
            self.battery = Battery()
    
        def describe_battery(self):
            """打印一条描述电瓶容量的消息"""
            print(f"This car has a {
            
            self.battery_size}-kWh battery.")
    
    my_tesla = ElectricCar('tesla', 'model s', 2019)
    print(my_tesla.get_descriptive_name())
    my_tesla.battery.describe_battery()
    my_tesla.battery.get_range()
    
    2019 Tesla Model S
    This car has a 75-kWh battery.
    This car can go about 260 miles on a full charge.
    

9.4 Importing classes

  • As functionality is added to classes, the file can become very long, even with proper use of inheritance. Python helps here by allowing classes to be stored in modules and then imported in the main program as needed

9.4.1 Importing a single class

  • Store the Car class in a module called car.py, and from now on, programs that use this module must use a more specific filename like my_car.py
    # car.py
    class Car:
        ...
    
    # my_car.py
    from car import Car
    
    my_new_car = Car('audi', 'a4', 2019)
    print(my_new_car.get_descriptive_name())
    ...
    

9.4.2 Storing multiple classes in a module

# car.py
class Car:
    ...
class Battery:
    ...
class ElectricCar(Car):
    ...
# my_electric_car.py
from car import ElectricCar

my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
...

9.4.3 Importing multiple classes from a module

  • You can import as many classes as you want in a program file. If you want to create a normal car and an electric car in the same program, you need to import both the Car class and the ElectricCar class
    # my_cars.py
    from car import Car, ElectricCar
    
    my_beetle = Car('volkswagen', 'beetle', 2019)
    print(my_beetle.get_descriptive_name())
    
    my_tesla = ElectricCar('tesla', 'roadster', 2019)
    print(my_tesla.get_descriptive_name())
    

9.4.4 Importing entire modules

# my_cars.py
import car

my_beetle = car.Car('volkswagen', 'beetle', 2019)
print(my_beetle.get_descriptive_name())

my_tesla = car.ElectricCar('tesla', 'roadster', 2019)
print(my_tesla.get_descriptive_name())

9.4.5 Using aliases

  • For example, to create a large number of electric car instances in the program, you need to repeatedly input ElectricCar, which is very cumbersome. To avoid this trouble, you can specify an alias for ElectricCar in the import statement
    from electric_car import ElectricCar as EC
    
    my_tesla = EC('tesla', 'roadster', 2019)  # 使用别名
    

9.5 Python Standard Library

  • The Python standard library is a set of modules, and any function and class in the standard library can be used by including a simple import statement at the beginning of the program. Let's take a look at the module random
    • In this module, an interesting function is randint(). It takes two integers as parameters and randomly returns an integer between (inclusive) the two integers. The following demonstrates generating a random integer between 1 and 6
    from random import randint
    
    print(randint(1, 6))
    
    1
    
    • In the module random, another useful function is choice(). It takes a list or tuple as an argument and returns an element at random
    from random import choice
    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    first_up = choice(players)
    
    print(first_up)
    
    michael
    

10. Documentation and exceptions

10.1 Reading data from a file

10.1.1 Reading the entire file

  • To read a file, a file containing a few lines of text is required. The following first creates a file that contains the pi value accurate to 30 decimal places, and wraps every 10 decimal places
    # pi_digits.txt
    3.1415926535
      8979323846
      2643383279
    
    # 函数 open() 接受一个参数:要打开的文件的名称
    # 关键字 with 在不再需要访问文件后将其关闭
    with open('pi_digits.txt') as file_object:
        # 使用方法 read() 读取这个文件的全部内容
        contents = file_object.read()
    
    # Python 方法 rstrip() 删除字符串末尾的空白
    print(contents.rstrip())
    
    3.1415926535
      8979323846
      2643383279
    

10.1.2 File path

# 到文件夹 python_work 下的文件夹 text_files 中去查找指定的 .txt 文件
with open('text_files/filename.txt') as file_object:

# 还可以将文件在计算机中的准确位置告诉 Python
# 这样就不用关心当前运行的程序存储在什么地方了,这称为绝对文件路径
file_path = '/home/ehmatthes/other_files/text_files/_filename_.txt'
with open(file_path) as file_object:

10.1.3 Create a list containing the contents of each line of the file

  • When reading a file, you often need to examine each line in it: you may want to find specific information in the file, or you may want to modify the text in the file in some way
  • When using the keyword with, the file object returned by open() is only available inside the with code block
    • If you want to access the contents of the file outside the with block, store the lines of the file in a list inside the with block and use that list outside the with block
    filename = 'pi_digits.txt'
    
    with open(filename) as file_object:
        # 方法 readlines() 从文件中读取每一行,并将其存储在一个列表中
        lines = file_object.readlines()
    
    # 列表 lines 的每个元素都对应于文件中的一行
    for line in lines:
        print(line.rstrip())
    
    3.1415926535
      8979323846
      2643383279
    

10.1.4 Using the contents of the file

  • Once the file is read into memory, the data can be used in any way. The following uses the value of pi in a simple way. First, create a string that contains all the numbers stored in the file without any spaces
  • When reading a text file, Python interprets all text in it as strings. If you read a number and want to use it as a numeric value, you must convert it to an integer using the function int() or convert it to a floating point number using the function float()
    filename = 'chapter_10/pi_digits.txt'
    
    with open(filename) as file_object:
        lines = file_object.readlines()
    
    pi_string = ''
    for line in lines:
        pi_string += line.strip()
    
    print(pi_string)
    print(len(pi_string))
    
    3.141592653589793238462643383279
    32
    

10.2 Writing to a file

  • One of the easiest ways to save data is to write it to a file . By writing the output to a file, the output persists even when the terminal window containing the program's output is closed

10.2.1 Writing to an empty file

  • To write text to a file, you need to provide another argument when calling open(), telling Python to write to the open file
  • When opening a file, you can specify read mode ('r'), write mode ('w'), append mode ('a'), or read-write mode ('r+'). If the mode argument is omitted, Python will open the file in the default read-only mode
  • If the file to be written does not exist, the function open() will automatically create it . However, be careful when opening files in write mode ('w'), because if the specified file already exists, Python will empty the contents of the file before returning the file object
    filename = 'programming.txt'
    
    # 第一个实参也是要打开的文件的名称
    # 第二个实参('w')表示要以写入模式打开这个文件
    with open(filename, 'w') as file_object:
        file_object.write("I love programming.")
    
    # programming.txt
    I love programming.
    

10.2.2 Appending to a file

  • If you want to add content to the file instead of overwriting the original content, you can open the file in append mode. When opening a file in append mode, Python does not empty the contents of the file before returning the file object, but instead appends the lines written to the file to the end of the file
    filename = 'programming.txt'
    
    with open(filename, 'a') as file_object:
        file_object.write("I also love finding meaning in large datasets.\n")
        file_object.write("I love creating apps that can run in a browser.\n")
    
    # programming.txt
    I love programming.
    I also love finding meaning in large datasets.
    I love creating apps that can run in a browser.
    

10.3 Exceptions

  • Python uses special objects called exceptions to manage errors that occur during program execution. Whenever an error occurs that overwhelms Python, it creates an exception object
  • Exceptions are handled using try-except code blocks. The try-except code block tells Python to perform the specified operation, and at the same time tells Python what to do when an exception occurs

10.3.1 Handling ZeroDivisionError exceptions

  • You probably know that you can't divide a number by 0, but let Python do it anyway
    print(5 / 0)
    
    Traceback (most recent call last):
      File "division_calculator.py", line 1, in <module>
        print(5/0)
    ZeroDivisionError: division by zero
    

10.3.2 Using try-except code blocks

  • Write a try-except code block to handle exceptions that may be thrown when you think an error may occur
  • If there is other code after the try-except code block, the program will continue to run , because Python has been told how to handle this kind of error
    try:
        print(5/0)
    except ZeroDivisionError:
        print("You can't divide by zero!")
    
    You can't divide by zero!
    

10.3.3 Using exceptions to avoid crashes

  • How the try-except-else code block works: Python tries to execute the code in the try code block, only the code that may throw an exception needs to be placed in the try statement. Sometimes, there is some code that needs to be run only if the try block executes successfully, which should be placed inside the else block
    print("Give me two numbers, and I'll divide them.")
    print("Enter 'q' to quit.")
    
    while True:
        first_number = input("\nFirst number: ")
        if first_number == 'q':
            break
        second_number = input("Second number: ")
        if second_number == 'q':
            break
        try:
            answer = int(first_number) / int(second_number)
        except ZeroDivisionError:
            print("You can't divide by 0!")
        else:
            print(answer)
    
    Give me two numbers, and I'll divide them.
    Enter 'q' to quit.
    
    First number: 2
    Second number: 6
    0.3333333333333333
    
    First number: q
    
    Process finished with exit code 0
    

10.3.4 Handling FileNotFoundError exceptions

  • When working with files, a common problem is that the file cannot be found: the file you are looking for may be elsewhere, the file name may be incorrect, or the file does not exist at all
    filename = 'alice.txt'
    
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print(f"Sorry, the file {
            
            filename} does not exist.")
    else:
        # Count the approximate number of words in the file.
        words = contents.split()
        num_words = len(words)
        print(f"The file {
            
            filename} has about {
            
            num_words} words.")
    
    Sorry, the file alice.txt does not exist.
    # The file alice.txt has about 29465 words.
    

10.3.5 Analyzing text

  • Use the method split(), which creates a list of words from a string (see 10.3.4)
    title = "Alice in Wonderland"
    
    print(title.split())
    
    ['Alice', 'in', 'Wonderland']
    

10.3.6 Silent failure

  • But it is not necessary to tell the user every time an exception is caught. Sometimes you want the program to remain silent when an exception occurs, and continue to run as if nothing happened. Can be achieved using the pass statement
def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        # pass 语句还充当了占位符,提醒在程序的某个地方什么都没做,并且以后也许要在这里做什么
        pass
    else:
        words = contents.split()
        num_words = len(words)
        print(f"The file {
      
      filename} has about {
      
      num_words} words.")

filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)
The file alice.txt has about 29465 words.
The file siddhartha.txt has about 42172 words.
The file moby_dick.txt has about 215830 words.
The file little_women.txt has about 189079 words.

10.4 Storing data

  • The module json is able to dump simple Python data structures to a file and load the data from that file when the program is run again. You can also use json to share data between Python programs
    • The JSON (JavaScript Object Notation) format was originally developed for JavaScript, but has since become a common format adopted by many languages ​​including Python

10.4.1 Using json.dump() and json.load()

  • Write a short program that stores a set of numbers, and another program that reads those numbers into memory. The first program will use json.dump() to store this set of numbers, while the second program will use json.load()
    import json
    
    numbers = [2, 3, 5, 7, 11, 13]
    
    filename = 'numbers.json'
    with open(filename, 'w') as f:
        # 使用函数 json.dump() 将数字列表存储到文件 numbers.json 中
        json.dump(numbers, f)
    
    # numbers.json
    [2, 3, 5, 7, 11, 13]
    
    import json
    
    filename = 'numbers.json'
    with open(filename) as f:
        # 使用函数 json.load() 加载存储在 numbers.json 中的信息
        numbers = json.load(f)
        
    print(numbers)
    
    [2, 3, 5, 7, 11, 13]
    

10.4.2 Refactoring

  • It's often the case that code works correctly, but can be improved by breaking it down into a series of functions that do a specific job, a process called refactoring . Refactoring makes code clearer, easier to understand, and easier to extend
    import json
    
    def get_stored_username():
        """如果存储了用户名,就获取它"""
        filename = 'username.json'
        try:
            with open(filename) as f:
                username = json.load(f)
        except FileNotFoundError:
            return None
        else:
            return username
    
    def get_new_username():
        """提示用户输入用户名"""
        username = input("What is your name? ")
        filename = 'username.json'
        with open(filename, 'w') as f:
            json.dump(username, f)
        return username
    
    def greet_user():
        """问候用户,并指出其名字"""
        username = get_stored_username()
        if username:
            print(f"Welcome back, {
            
            username}!")
        else:
            username = get_new_username()
            print(f"We'll remember you when you come back, {
            
            username}!")
    
    greet_user()
    
    Welcome back, eric!
    

Guess you like

Origin blog.csdn.net/qq_42994487/article/details/132396390