python loop basic syntax

Posted by robinhood on Mon, 17 Jan 2022 18:50:57 +0100

loop

1. Loop nesting

1. Implementation principle of loop nesting

One external circulation and one complete internal circulation

for x in range(5):
    for y in range(2, 5):
        print(x, y)
'''
x Value range: 0, 1, 2, 3, 4
 for the first time: x = 0 :Execute the corresponding of the loop body for loop,y The range of values is:2,3,4,
              for the first time: y=2:print(x, y) -> print(0,2)
              Second cycle y = 3:print(x ,y) -> print(0, 3)
              Third cycle y = 4:print(x ,y) -> print(0, 4)

The second time:x = 1 :Execute the corresponding of the outer loop for loop,y The value range of is:2,3,4
             for the first time: y=2:print(x,y) x The value range of is 2,3,4
'''

2. Add - add element

1. Add a single element
'''
list.append(element)    -   Add an element at the end of the list
 list.insert(Subscript, element) - Inserts the specified element before the element corresponding to the specified subscript
'''

movise = ['Fifty or sixty degree grey', 'Godzilla vs. King Kong', 'Peach blossom Man vs chrysanthemum monster']
print(movise)       # ['fifty or sixty degrees grey', 'Godzilla vs. King Kong', 'Peach Blossom man vs. chrysanthemum monster']


movise.append('Xiao Shengke's redemption')
print(movise)       # ['fifty or sixty degrees grey', 'Godzilla vs. King Kong', 'Peach Blossom man vs. chrysanthemum monster', 'Xiao Shengke's redemption']

movise.insert(2, 'Silent lamb')
print(movise)		# ['fifty or sixty degrees grey', 'Godzilla vs. King Kong', 'Silent Lamb', 'Peach Blossom man vs. chrysanthemum monster', 'Xiao Shengke's redemption']
2. Batch add

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

movise.extend(['Pleasant goat and grey wolf', 'Out of reach', 'V Word vendetta team'])
print(movise)		#['fifty or sixty degrees grey', 'Godzilla vs. King Kong', 'Silent Lamb', 'Peach Blossom man vs. chrysanthemum monster', 'Redemption of Shaw', 'pleasant goat and grey wolf', 'out of reach', 'V-word revenge team']

Exercise: extract all passing scores from scores

scores = [89, 67, 56, 90, 98, 30, 78, 51, 99]
scores1 = []		# Create a new list
for x in scores:
    if x >= 60: 		 # Statistics on the number of qualified persons
        scores1.append(x)   # Put the number of passes into the new list
print(scores1)  # Print new list

3. Awareness list

1. What is a list

Element: each independent data in the container is an element

Basic characteristics of a container: the data type of a container can store multiple other data at the same time

'''
1)What does the list look like:The list is a container type(sequence),take[]Mark as container,Multiple elements are separated by commas[Element 1, Element 2, Element 3,....]
2)List features:The list is variable(Number of elements,Variable values and order) - increase,Delete,change,check:The list is ordered,Subscript operation is supported
3)List requirements for elements:No requirement(Any data type can be used as an element of a list)
'''

Empty list

list1 = []
list2 = [ ]
print(type(list1), type(list2))  # <class 'list'> <class 'list'>
print(bool(list1), bool(list2))  # False False

print(len(list1), len(list2))    # 0 0

The list can save multiple data at the same time

list3 = [90, 89, 79, 69, 59]
print(list3)

list4 = ['King', 90, 'Hello', 1000, True]
print(list4)
2. Query - get elements

The query is divided into three cases: obtaining a single element, slicing, and traversal (traversal = extraction one by one)

Get a single element

'''
grammar:list(subscript)
function:Gets the element corresponding to the specified subscript in the list
 explain:
list - Any result is a list representation,such as:Save list variables,Specific list values
[]   -  Fixed writing of list
 subscript -  Subscripts are also called indexes,Is the position information of elements in an ordered sequence
		python Each element in an ordered sequence has two sets of subscript values.namely:Subscript value incremented from 0 from front to back
		And from back to front,from-1 Subscript value to begin decrement
 be careful:Subscript cannot be out of range,Out of range error
'''
list3 = [98, 90, 20, 40, 59]
# list3 [subscript]
names = ['Zhen Ji', 'army officer's hat ornaments', 'Han Xin', 'Lv Bu', 'Zhao Yun', 'offspring', 'Luban', 'Di Renjie']
print(names[1])
print(names[-1])
print(names[3])
print(names[-2])

ergodic

'''
Mode 1: Get each element in the list directly
for variable in list:
    Circulatory body
    
Mode 2:Line gets the subscript value of each element,Then get the element by subscript
for element in range(len(list)):
    Circulatory body 
    
for subscript in range(-1, -len(list)-1, -1):
    Circulatory body
    
range(len(list))==range(Number of elements in the list)

Method 3 :At the same time, obtain the subscript corresponding to each element and element in the list
for subscript,element in enumerate(list);
    Circulatory body

'''
print('====================Split line==========================')
for x in names:
    print(x)

print('====================Split line==========================')
for index in range(len(names)):
    print(index, names[index])

print('====================Split line==========================')
for index, item in enumerate(names):
    print(index, item)

practice:

# Exercise 1: count the number of failed students
scores = [89, 67, 56, 90, 98, 30, 78, 51, 99]
num = 0
for x in scores:
    if x < 60:        # If the element in the list is less than 60
        num += 1
print('Number of failed', num)


# Exercise 2: count the number of integers in the list
list7 = [89, 9.9, 'abc', True, 'abc', '10', 81, 90, 23]
num1 = 0
for x in list7:
    y = type(x)     # Judge element type
    if y == int:    # Determine whether the element is an integer
        num1 += 1    # If it is an integer, add 1
print('Count the number of integers in the list', num1)

# Exercise 3: sum all even numbers in nums
nums = [89, 67, 56, 90, 98, 30, 78, 51, 99]
num2 = 0       # Define a variable to hold the even sum of elements
for x in nums:
    if x % 2 == 0:  # Find the sum of all even numbers in the list
        num2 += x   # The even number is x, so num2 needs + = X
print('Sum of all even numbers', num2)

First week assignment

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','uo!')
    
  2. Write code and print 5 times on the console you see, one day!

    x = you see see, one day day!
    print(x)
    print(x)
    print(x)
    print(x)
    print(x)
    
    
    
  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, end=' ')
    
  5. Write code and print numbers: 10, 9, 8, 7, 6, 5

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

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

  8. num = 0
    for x in range(0, 101, 2):
        num += x
    print(num)
    
  9. Write code to count the number of 3 in 100 ~ 200

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

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

    num = int(input('Enter a number:'))
    while True:
            if num % 2 == 0:
                print('even numbers')
                break
            else:
                print('Odd number')
                break
    
  12. Count the number of numbers within 1000 that can be divided by 3 but cannot be divided by 5.

    for x in range(0, 1000, 3):
        if x % 5 != 0:
            print(x)
    

Number, otherwise print odd`

```python
num = int(input('Enter a number:'))
while True:
        if num % 2 == 0:
            print('even numbers')
            break
        else:
            print('Odd number')
            break
```
  1. Count the number of numbers within 1000 that can be divided by 3 but cannot be divided by 5.

    for x in range(0, 1000, 3):
        if x % 5 != 0:
            print(x)
    

Topics: Python