Python programming from introduction to practice_ Basic knowledge summary

Posted by jerastraub on Thu, 03 Mar 2022 16:03:20 +0100

1. Variables and simple data types

1.1 string

A string is a series of characters. In Python, strings are enclosed in quotation marks, which can be single quotation marks or double quotation marks, as shown below:

"This is a string."
'This is also a string.'

This flexibility allows you to include quotation marks and apostrophes in strings:

'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
"One of Python's strengths is its diverse and supportive community."

Modifying the case of strings

  • title() method

The method title() displays each word in uppercase, that is, the first letter of each word is changed to uppercase

name = "ada lovelace"
print(name.title())

The output of the code is as follows:

Ada Lovelace
  • upper() and lower() methods

Change string to all uppercase: upper()
Change the string to all lowercase: lower()

To change the string to all uppercase or all lowercase, do the following:

name = "Ada Lovelace"
print(name.upper())
print(name.lower())

The output of these codes is as follows:

ADA LOVELACE
ada lovelace

1.1.2 using variables in strings

In some cases, you may want to use the value of a variable in a string. For example, you might want to use two variables to represent first name and last name respectively, and then combine the two values to display the name:

first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)

To insert the value of a variable into a string, add the letter f before the first quotation mark, and then put the variable to be inserted in curly braces. In this way, when Python displays a string, it will replace each variable with its value

The output of the above code is as follows:

ada lovelace

1.1.3 delete blank

  • Remove whitespace at the end of string: rstrip()

To ensure that there is no whitespace at the end of the string, use the method rstrip().

>>> favorite_language = 'python '
>>> favorite_language
  'python '
>>> favorite_language.rstrip()
  'python'
  • Delete blank space at the beginning of string: lstrip()
>>> favorite_language = ' python '
>>> favorite_language.lstrip()
  'python '
  • Delete the blank space on both sides of the string: strip()
>>> favorite_language = ' python '
>>> favorite_language.strip()
  'python'

1.2 number

1.2.1 integer

In Python, you can add (+) subtract (-) multiply (*) divide (/) integers.

>>> 2 + 3
5
>>> 3 - 2
1
>>> 2 * 3
6
>>> 3 / 2
1.5

In a terminal session, python returns the operation result directly. Python uses two multiplier signs to represent a power operation:

>>> 3 ** 2
9
>>> 3 ** 3
27
>>> 10 ** 6
1000000

When writing large numbers, you can use underline to group the numbers (it doesn't matter how many digits are in a group) to make them clearer and easier to read:

>>> universe_age = 14_000_000_000

When you print a number defined with underscores, Python does not print the underscores:

>>> print(universe_age)
14000000000

1.2.2 floating point number

Python calls all numbers with decimal points floating point numbers.

  • When you divide any two numbers, the result is always a floating-point number, even if both numbers are integers and Divisible:
>>> 4/2
2.0
  • In any other operation, if one operand is an integer and the other operand is a floating-point number, the result is always a floating-point number:
>>> 1 + 2.0
3.0
>>> 2 * 3.0
6.0
>>> 3.0 ** 2
9.0

No matter what kind of operation, as long as any operand is a floating-point number, Python will always get a floating-point number by default, even if the result is originally an integer

1.2.3 supplementary knowledge

  • notes

In Python, comments are identified by pound signs (#). The contents after the pound sign will be ignored by the Python interpreter, as shown below:

# Say hello to everyone.
print("Hello Python people!")

The Python interpreter will ignore the first line and execute only the second line.

Hello Python people!
  • Assign values to multiple variables at the same time

You can assign values to multiple variables in one line of code. When doing so, you need to separate the variable names with commas; For the value to be assigned to the variable, the same processing is required:

>>> x, y, z = 0, 0, 0
  • constant

Constants are similar to variables, but their values remain unchanged throughout the life cycle of the program. Constant names are generally capitalized:

MAX_CONNECTIONS = 5000

2. List

2.1 list basis

A list consists of a series of elements arranged in a specific order. A list allows you to store groups of information in one place. It can contain only a few elements or millions of elements. You can add anything to the list, and there can be no relationship between the elements

In Python, the list is represented by square brackets [] and the elements are separated by commas

give an example:

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

Output:

['trek', 'cannondale', 'redline', 'specialized']

2.2 accessing, modifying, adding and deleting elements

2.2.1 accessing list elements

A list is an ordered collection. To access list elements, you can point out the name of the list, then point out the index of the element, and put the latter in square brackets []:

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

output:

trek

Python provides a special syntax for accessing the last few list elements. By specifying the index as - 1, python can return the last list element, index - 2 returns the penultimate list element, index - 3 returns the penultimate list element, and so on:

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

output:

specialized

2.2.2 modifying list elements

The syntax for modifying list elements is similar to that for accessing list elements. To modify a list element, specify the list name and the index of the element to be modified, and then specify the new value of the element

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)

output:

['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']

2.2.3 adding elements to the 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. When you attach an element to a list, it is added to the end of the list

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)

output:

['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']
  • Insert element in list

Use the insert() method to add a new element anywhere in the list. To do this, you need to specify the index and value of the new element:

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)

The method insert() adds space at index 0 and stores the value 'ducati' there. This operation moves each existing element in the list to the right one position:

['ducati', 'honda', 'yamaha', 'suzuki']

2.2.4 removing elements from the list

  • Delete the element with del statement, and the element can no longer be accessed after deletion

If you know the position of the element to be deleted in the list, you can use the del statement:

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)

The above code uses del to delete the first element 'honda' in the list of motorcycles:

['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']
  • Delete the element using the method pop()

The method pop() deletes the element at the end of the list and allows you to use it next:

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)

The output shows that the value 'suzuki' at the end of the list has been deleted and is now assigned to the variable popped_motorcycle:

['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
  • Pop up an element anywhere in the list

You can use pop() to delete an element anywhere in the list. Just specify the index of the element to be deleted in parentheses:

motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print(f"The first motorcycle I owned was a {first_owned.title()}.")

output:

The first motorcycle I owned was a Honda.
  • Delete element based on value

Sometimes you don't know where the value you want to delete from the list is. If you only know the value of the element to be deleted, you can use the method remove()

The method remove() deletes only the first specified value. If the value to be deleted may appear multiple times in the list, you need to use a loop to ensure that each value is deleted

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)

output:

['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

2.3 organization list

2.3.1 permanently sort the list using the method sort()

Suppose you have a list of cars in alphabetical order:

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

The method sort() permanently modifies the order in which the list elements are arranged. Now cars are arranged in alphabetical order and can no longer be restored to the original order:

['audi', 'bmw', 'subaru', 'toyota']

You can also arrange the list elements in reverse alphabetical order. Just pass the parameter reverse=True to the sort() method:

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

Similarly, changes to the order of the list elements are permanent:

['toyota', 'subaru', 'bmw', 'audi']

2.3.2 use the function sorted() to temporarily sort the list

To preserve the original order of the list elements and render them in a specific order, use the function sorted(). The function sorted () allows you to display list elements in a specific order without affecting their original order in the list

cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)

output:

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']

2.3.3 print list upside down

To reverse the order of the list elements, you can use the method reverse() method reverse() to permanently modify the order of the list elements, but you can restore the original order at any time by calling reverse() again on the list

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

Note that reverse() does not arrange the list elements in the reverse alphabetical order, but just reverses the order of the list elements:

['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

2.3.4 determine the length of the list

Use the function len() to quickly learn the length of the list

cars = ['bmw', 'audi', 'toyota', 'subaru']
len(cars)

Output: 4

3. Operation list

3.1 traverse the entire list

When you need to perform the same operation on each element in the list, you can use the for loop in Python

Next, use the for loop to print all the names in the magician list:

magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician)

Define a for loop. This line of code lets Python take a name from the list magicians and associate it with the variable magician. Finally, let Python print the name previously assigned to the variable magician, and the output is all the names in the list:

alice
david
carolina

You can include as many lines of code as you want in the for loop. After the code line formagic in magicians, each indented code line is part of a loop and will be executed once for each value in the list

After the for loop, the code without indentation is executed only once and will not be repeated

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!")

The first two function calls print() are repeated for each magician in the list. However, the third function call print() is not indented, so it is executed only once:

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!

Python uses indentation to determine the relationship between a line of code and the previous line of code. In the previous example, the lines of code that display messages to magicians are part of the for loop because they are indented

Python makes code easier to read by using indentation. Simply put, it requires you to use indentation to keep your code neat and structured. In a longer Python program, you will see code blocks with different indentations, so you can have a general understanding of the organizational structure of the program.

3.2 creating a list of values

3.2.1 using the function range()

The Python function range () allows you to easily generate a series of numbers. For example, you can print a series of numbers using the function range() as follows:

for value in range(1, 5):
    print(value)

It seems that the above code should be printed 1 ~ 5, but in fact, it will not print 5, because the open set is on the right:

1
2
3
4

When calling the function range(), you can also specify only one parameter so that it will start at 0. For example, range(6) returns a number of 0 to 5

3.2.2 create a list of numbers using range()

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

numbers = list(range(1, 6))
print(numbers)

The results are as follows:

[1, 2, 3, 4, 5]

When using the function range(), you can also specify the step size. To do this, you can specify a third parameter to this function, and Python will generate numbers according to this step. The following code prints even numbers from 1 to 10:

even_numbers = list(range(2, 11, 2))
print(even_numbers)

The function range() starts from 2 and then continues to add 2 until it reaches or exceeds the final value (11), so the output is as follows:

[2, 4, 6, 8, 10]

3.2.3 perform simple statistical calculations on the list of numbers

Find the maximum, minimum and sum of the number list:

>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45

3.3 use part of the list

3.3.1 slicing, processing some elements of the list

To create a slice, specify the index of the first and last element to use. To output the first three elements in the list, you need to specify indexes 0 and 3, which returns elements with indexes 0, 1, and 2.

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

output:

['charles', 'martina', 'michael']

You can generate any subset of the list. For example, if you want to extract the second, third, and fourth elements of a list, you can specify the start index as 1 and the end index as 4:

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])

At this point, the slice starts with 'martina' and ends with 'florence':

['martina', 'michael', 'florence']

If the first index is not specified, Python automatically starts at the beginning of the list:

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

Since no starting index is specified, Python extracts from the beginning of the list:

['charles', 'martina', 'michael', 'florence']

Similarly, you can output elements from the specified position to the end of the list:

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

Python will return all elements from the third element to the end of the list:

['michael', 'florence', 'eli']

players [:] copy the whole list and return a copy of the list, which can be assigned to another list

In addition, you can specify a third value in square brackets representing slices. This value tells Python how many elements to extract in a specified range

3.3.2 traversal slice

Traverse the top three players and print 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())

Enter as follows:

Here are the first three players on my team:
Charles
Martina
Michael

3.3.3 copy list

To copy a list, create a slice that contains the entire list by omitting both the start index and the end index [:]. This allows Python to create a slice that starts with the first element and ends with the last element, a copy of the entire list

my_foods = ['pizza', 'falafel', 'carrot cake']
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)

The output is as follows:

My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']

If you just put my_ Give food to friends_ Foods, you can't get two lists:

my_foods = ['pizza', 'falafel', 'carrot cake']

# It won't work:
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)

The assignment syntax actually lets Python put the new variable friend_foods is associated with my_ The list associated with foods, so these two variables point to the same list, and the last two lists are the same:

My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']

3.4 tuples

The list is modifiable and is well suited for storing data sets that may change during the running of the program.

Sometimes you need to create a series of immutable elements, and tuples can meet this requirement. Tuples look like lists, but are identified by parentheses rather than brackets. Once a tuple is defined, its elements can be accessed using an index, just like a list element

dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])

The output is as follows:

200
50

If you want to define a tuple containing only one element, you must add a comma after the element, but creating a tuple containing only one element usually makes no sense:

my_t = (3,)

3.4.1 all values in the epoch group

Like a list, you can also use the for loop to traverse all values in a tuple:

imensions = (200, 50)
for dimension in dimensions:
    print(dimension)

The output is as follows:

200
50

3.4.2 modifying tuple variables

Although the element of the tuple cannot be modified, the variable storing the tuple can be re assigned.

dimensions = (200, 50)
print("Original dimensions:")
    for dimension in dimensions:
        print(dimension)

dimensions = (400, 100)
print("\nModified dimensions:")
    for dimension in dimensions:
        print(dimension)

By associating a new meta group to the variable dimensions, Python will not raise any errors, because it is legal to reassign tuple variables:

Original dimensions:
200
50

Modified dimensions:
400
100

Topics: Python