2020_9_24_loop

There are two kinds of loops in python: for loop and while loop

1. for loop

Syntax:
for variable in sequence:
loop body

Description:
a. for/in-keyword; fixed writing
b. variable-can be any variable; generally write a new variable
c. sequence-container data type in python, for example: string, list, dictionary, tuple , Set, iterator, generator, range, etc.
d. Colon-fixed writing
e. Loop body-One or more statements that keep an indentation with for; the
loop body is the code block that needs to be executed repeatedly

Execution process:
Let the variables take values ​​in the sequence, take them one by one, until the end is taken; execute the loop body every time a value is taken.
(The number of loops in the for loop depends on the number of elements in the sequence)
for x in'abcyu':
print(x,'hello')

2. The usage of
range 1) range(N) -Generate a sequence of numbers from 0 to N-1: 0,1,2,3,4,...,N-1
(N must be a positive integer)
2) range(M, N)-Generate a sequence of numbers from M to N-1: M,M+1,M+2,...N-1
(M and N are both integers and M is less than N)
3) range(M, N, step)- Step controls the value to be increased each time (default is 1): M, M+step, M+2*step,…

for x in range(10):
print(‘x:’, x)

for y in range(-10, 101):
print(‘y:’, y)

for z in range (0, 101, 2):
print ('z:', z)

for m in range(1, 100, 2):
print(‘m:’, m)

Exercise: Generate a sequence corresponding to all numbers from 100 to 1
for i in range(100, 0, -1):
print('i:', i)

Summation routine: calculate the sum of 1+2+3+…+100
sum1 = 0 # Define a variable to save the final sum
for num in range(1, 101):
sum1 = sum1 + num # is equivalent to: sum1 += num
print(sum1)

Count the number: count the number of even numbers from 0 to 100 that can be divisible by 3
Method 1:
count = 0 # Define a variable to save the final number
for num in range(101):
if num% 3 == 0 and num % 2 == 0:
count += 1
print(count)

方法二:
count = 0
for num in range(0, 101, 6):
count += 1
print(count)

Exercise 1: Find the sum of numbers within 1000 that are divisible by 7 but not divisible by 3
Method 1:
sum1 = 0
for x in range(1000):
if x% 7 == 0 and x% 3 != 0:
sum1 + = x
print(sum1)

Method two:
sum1 = 0
for x in range(0, 1000, 7):
if x% 3 != 0:
sum1 += x
print(sum1)

Exercise 2: Count the number of numbers whose sum of tens digits plus single digits equal to 5 within 1000
27348 -> 27348% 100 -> 48 // 10 -> 4
count = 0
for x in range(1000):
shi = x% 100 // 10
ge = x% 10
if shi + ge == 5:
count += 1
print(count)
syntax:

2.while loop

while conditional statement:
loop body

Explanation:
while-keyword; fixed writing
conditional statement-any expression except assignment statement
Colon-fixed writing
Loop body-one or more statements that keep the same indentation with while;
loop body is a code block that needs to be executed repeatedly

Execution process:
first judge whether the conditional statement is True,
execute the loop body if it is True, then judge whether the conditional statement is True after executing the loop body, then execute the loop body if it is True,
…and so on, until the result of the conditional statement is False. The cycle is over.

While the routine of controlling the number of times:
variable = 0
while variable <times:
the operation
that needs to be repeated variable += 1

num = 0
while num <5:
print('============')
num += 1
print(num)
execution process

num = 0; num < 5 -> True -> print(’’); num += 1;
num = 1; num < 5 -> True -> print(’
’); num += 1;
num = 2; num < 5 -> True -> print(’’); num += 1;
num = 3; num < 5 -> True -> print(’
'); num += 1;
num = 4; num <5 -> True -> print('============'); num += 1;
num = 5; num <5 -> False (end of loop)

2. The choice of
for loop and while When to use for loop:
1) Traverse the sequence (take out the elements in the sequence one by one)
2) Determine the number of loops

When to use while loop
1) Infinite loop
2) The number of loops is uncertain
while True:
pass
Practice: Write a program to continuously input data until the input content is 0
Please enter: abc
Please enter: 123
Please enter: ah is
please enter : 0

Input content = 1
while input content is not equal to 0:
input content = input('Please input:')

value = 1
while value != ‘0’:
value = input(‘请输入:’)

3.continue和break

continue and break can only be used in the loop body
1.continue-end a loop
If continue is encountered when the loop body is executed, then the next loop will go directly to the next loop when the loop ends
for x in range(5):
print('= =====')
continue
print('++++++')

count = 0
for x in range(10):
if x % 3 == 0:
continue
count += 1
print(count)

count = 0
x = 0: if 0 % 3 == 0 -> True: continue
x = 1: if 1 % 3 == 0 -> False; count += 1 -> count = 1
x = 2: if 2 % 3 == 0 -> False; count += 1 -> count = 2
x = 3: if 3 % 3 == 0 -> True: continue
x = 4: if 4 % 3 == 0 -> False; count += 1 -> count = 3

2.break-end the entire loop
If break is encountered when executing the loop body, then the entire loop ends directly
num = 0
while num <5:
print('=======')
break
print('++++ +++')
num += 1
print('end')

num = 0
sum1 = 0
while True:
sum1 += num
if sum1 > 1000:
break
num += 1
print(num-1, sum1-num)

3. Usage of while loop

while True:
The operation that needs to be repeated
if the loop ends:
break
"""
Guess the number game:
"""
randomly generate a number from 0 to 100: num, the user keeps inputting the number until the input value is equal to the random number generated End
num = 35 (assuming)
Please enter an integer (0~100): 50 is
big, please guess again!
Please enter an integer (0~100): 49 is
big, please guess again!
Please enter an integer (0 ~100): 20 is
small, please guess again!
Please enter an integer (0~100): 25 is
small, please guess again!
Please enter an integer (0~100): 35
Congratulations! You guessed it
randint(M, N)-Generate a random integer
from M to N from random import randint
num = randint(0, 100)
while True:
value = int(input('Please enter an integer (0~100): '))
if value == num:
print('Congratulations! You guessed it!')
break
elif value> num:
print('It's big, please guess again!')
else:
print('Small, please guess again!')

4.else

1. Complete for loop and while loop
for variable in sequence:
loop body
else:
code block

while conditional statement:
loop body
else:
code block

The else does not affect the execution of the original loop; the code block after the else will be executed when the loop ends normally.
If the loop ends because of encountering a break, the code block after the else will not be executed.

for x in range(5):
if x == 3:
break
print(’======’)
else:
print(‘else!’)

Guess you like

Origin blog.csdn.net/xdhmanan/article/details/108781105