python learning notes 4: loop and list

Posted by nigel_belanger on Tue, 18 Jan 2022 00:15:24 +0100

Loops and lists

1, Loop nesting

The execution principle of loop nesting: the outer loop is once and the inner loop is complete

for x in range(5):
	for y in range(2, 8):
		print(x, y)

2, Recognition list

1. List

  • What does a list look like: a list is a container data type (sequence); Take [] as the flag of the container, in which multiple elements are separated by commas: [element 1, element 2, element 3,...]
  • Characteristics of list: the list is variable (the number, value and order of elements are variable) - add, delete and change; The list is ordered - subscript operations are supported
  • List requirements for elements: no requirements (no matter what type of data can be used as list elements)

(1) Empty list

Format: len (list) - get the number of elements in the list

list1 = []
list2 = [ ]
print(type(list1), type(list2))
print(bool(list1), bool(list2))
print(len(list1), len(list2))

(2) The list can save multiple data at the same time

list3 = [89, 90, 76, 99, 58]
print(list3)

list4 = ['abc', 18, 'male', 100, True]
print(list4)

list5 = [10,12.5,True,'abc',[1,0],{'a':10},(20,9),lambda x:x*2]
print(list5)

list6 = [[1,2,3],
         [4,5,6],
         [7,8,9]
]

print(len(list6))

2. Query - get elements

Query is divided into three cases: obtaining a single element, slicing, and traversal (one by one)

(1) Get a single element

  • Syntax: list [subscript]
  • Function: get the element corresponding to the specified subscript in the list
  • explain:
    List - any expression that results in a list, such as a variable that holds the list, a specific list value, and so on
    [] - Fixed writing
    Subscript - subscript, also known as index, is the position information of elements in an ordered sequence.
    Each element in the ordered sequence in python has two sets of subscript values, which are: the subscript value increasing from 0 from the front to the back; Subscript value decreasing from - 1 from back to front
  • Note: the subscript cannot be out of bounds

For example:

list3 = [89, 90, 76, 99, 58]
names = ['Zhen Ji','army officer's hat ornaments','Han Xin','Lv Bu','Zhao Yun','Hou Yi','Luban','Di Renjie']
print(names[1])
print(names[-1])
print(names[3])

(2) Traversal

  • Method 1 - get each element in the list directly
    for variable in list:
    Circulatory body
for x in names:
    print(x)
  • Method 2 - first obtain the subscript value of each element, and then obtain the element through the subscript
    for subscript in range (len):
    Circulatory body

    for subscript in range (- 1, - len (list) - 1, - 1):
    Circulatory body

    Range (len) = = range (number of elements in the list)

    for index in range(len(names)):
        print(index,names[index])
    
  • Method 3 - get the subscript corresponding to each element and element in the list at the same time
    for subscript, element in enumerate (list):
    Circulatory body

for index,item in enumerate(names):
print(index,item)
```

3, Add element

1. Add a single element

Format:

List Append - adds an element at the end of the list
List Insert (subscript, element) - inserts the specified element before the element corresponding to the specified subscript

For example:

movies = ['Fifty six degree grey','Godzilla vs. King Kong','Peach blossom Man vs chrysanthemum monster']
print(movies)

movies.append('The Shawshank Redemption')
print(movies)

movies.insert(2, 'Silent lamb')
print(movies)

2. Batch add

Format:

List 1 Extend (list 2) - adds all the elements of list 2 to the end of list 1

For example:

movies.extend(['Let the bullet fly','Out of reach','V Word revenge'])
print(movies)

Week 1 homework exercise:

1, Multiple choice questions

  1. Which of the following variable names is illegal? (C)

    A. abc

    B. Npc

    C. 1name

    D ab_cd

  2. Which of the following options is not a keyword? (B)

    A. and

    B. print

    C. True

    D. in

  3. Which of the following options corresponds to the correct code? (C)

    A.

    print('Python')
      print('Novice Village')
    

    B.

    print('Python') print('Novice Village')
    

    C.

    print('Python')
    print('Novice Village')
    

    D.

    print('Python''Novice Village')
    
  4. Which of the following options can print 50? B

    A.

    print('100 - 50')
    

    B.

    print(100 - 50)
    
  5. For quotation marks, what is the correct use of the following options? D

    A.

    print('hello)
    

    B.

    print("hello')
    

    C.

    print("hello")
    

    D.

    print("hello")
    

2, Programming problem

  1. Write code and print good study, day, day up on the console!

    print('good good study, day day up!')
    
  2. Write code and print 5 times on the console you see, one day!

    for x in range(5):
        print('you see see, one day day!')
    
  3. Write code and print numbers 11, 12, 13,... 21

    for x in range(11, 22):
        print(x)
    
  4. Write code and print numbers 11, 13, 15, 17,... 99

    for x in range(11, 100, 2):
        print(x)
    
  5. Write code and print numbers: 10, 9, 8, 7, 6, 5

    for x in range(10, 4, -1):
        print(x)
    
  6. Write code to calculate the sum of 1 + 2 + 3 + 4 +... + 20

    sum = 0
    for x in range(1, 21):
        sum += x
    print('and:',sum)
    
  7. Write code to calculate the sum of all even numbers within 100

    sum = 0
    for x in range(0, 99, 2):
        sum += x
    print('and:',sum)
    
  8. Write code to count the number of 3 in 100 ~ 200

    count = 0
    for x in range(103, 200, 10):
        count += 1
    print('number:', count)
    
  9. Write code to calculate 2 * 3 * 4 * 5 ** 9 results

    num = 1
    for x in range(2, 10):
        num *= x
    print('result:', num)
    
  10. Enter a number. If the number entered is an even number, print an even number. Otherwise, print an odd number

    n = int(input('Please enter:'))
    if n % 2 == 0:
        print('even numbers')
    else:
        print('Odd number')
    
  11. Count the number of numbers within 1000 that can be divided by 3 but cannot be divided by 5.

    num = 0
    for x in range(0, 1000, 3):
        if x % 5 != 0:
            num += 1
    print('number:', num)
    

Topics: Python