DAY03 branch and loop
I Process control
Control how the code is executed:
According to the different execution methods of the code, the code is divided into three structures:
1.1 sequence structure
Sequential structure (default) - code is executed sequentially from top to bottom, and each statement is executed only once
a = 10 print(a) print(10) print('10')
1.2 branch structure
Branch structure - select execution code according to conditions
age = 34 if age >= 18: print('adult') else: print('under age')
1.3 circulation structure
for, while - let the code execute repeatedly (the code is only written once and executed many times)
for x in range(5): print('hello world!')
II Branching structure
2.1 if single branch structure
If... Just
- Syntax:
if conditional statement:
Code snippet - explain:
1) if - keyword; Fixed writing
2) Conditional statement - any expression with results, such as specific data, variables that have been assigned, and the operation expression of some operation with results
3) : - Fixed writing method (must be colon under English input method)
4) Code segment - structurally, it is to keep one or more statements indented with if (at least one); Logically, it is code that will be executed only when conditions are met
# If num is an even Number, print 'even Number', no matter what the Number is, print 'Number' num = 20 if num % 2 == 0: print('even numbers') print('Number') # Exercise 1: print 'adult' based on age value age = int(input('Please enter age:')) if age >= 18: print('adult') # Exercise 2: if num can be divided by 4, print a multiple of '4' num = int(input('Please enter a number:')) if num % 4 == 0: print('4 Multiple of')
2.2 if double branch structure
If... Just... Otherwise
- Syntax:
if conditional statement:
Code segment 1 (code to be executed when the condition is true)
else:
Code segment 2 (code to be executed when the condition is not tenable)
# Exercise: print 'odd' or 'even' according to the parity of num # Method 1: num = int(input('Enter number:')) if num % 2 == 0: print('even numbers') else: print('Odd number') # Method 2: if num % 2: # Odd remainder 1, non-zero holds print('Odd number') else: print('even numbers') # If the string str1 is empty, print "empty string", otherwise print "non empty string" str1 = '' if str1: print('Non empty string') else: print('Empty string') # Exercise: print 'normal year' or 'leap year' according to the year corresponding to year year = 2001 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print('leap year') else: print('Ordinary year')
Add: when the conditional statement is not Boolean, whether the condition is true or not depends on whether the result of the conditional statement is true or False after being converted to Boolean
Boolean type conversion - all types of data can be converted to Boolean. When converting, all zero and null values will be converted to False, and others will be True
print(bool(0), bool(0.0), bool(None), bool(''), bool([]), bool(()), bool({})) print(bool(23), bool(-321), bool('abc'))
2.3 if multi branch structure
Do different things according to different conditions, if; If
Method 1: conditions are met: if one of the conditions is true, other conditions may also be true
if conditional statement 1:
Code snippet 1
if conditional statement 2:
Code snippet 2
if conditional statement 3:
Code snippet 3
...
score = 100 if score == 100: print('buy a car') if 90 <= score < 100: print('Buy a computer') if 80 <= score < 90: print('Buy shoes') if score < 80: print('Kill')
Method 2: satisfaction between conditions: if one of the conditions is true, the other conditions cannot be true
if conditional statement 1:
Code snippet 1
elif conditional statement 2:
Code snippet 2
elif conditional statement 3:
Code snippet 3
...
score = 100 if score == 100: print('buy a car') elif 90 <= score < 100: print('Buy a computer') elif 80 <= score < 90: print('Buy shoes') elif score < 80: print('Kill')
# Exercise: print according to the age range: children (0 ~ 3), teenagers (4 ~ 17), youth (18 ~ 38), middle age (39 ~ 69), old age (70 and above) age = int(input('Enter age:')) # if 0 <= age <= 3: if age <= 3: print('child') # elif 4 <= age <= 17: elif age <= 17: print('juvenile') # elif 18 <= age <= 38: elif age <= 38: print('youth') # elif 39 <= age <= 69: elif age <= 69: print('middle age') # elif score >= 70: else: print('old age')
2.4 if nesting
# Print 'even', 'odd' and 'multiple of 4' according to the value of num # For example: 1 - > 'odd', 2 - > 'even', 16 - > 'even', multiple of '4' num = int(input('Enter number:')) if num % 2: print('Odd number') else: print('even numbers') if not num % 4: print('4 Multiple of')
III for loop
3.1 for loop
Let the code execute repeatedly
-
Syntax:
for variable in sequence:
Circulatory body -
explain:
1) for, in - keywords; Fixed writing
2) Variable - (the requirement is the same as the specification) variable name (may not be defined)
3) Sequence - data of container data type, such as string, list, dictionary, tuple, set, iterator, generator, range
4) : - Fixed writing
5) Circulatory body-
Structurally, the loop body is one or more statements (at least one) that maintain an indentation with for
Logically, the code in the loop body is the code that needs to be executed repeatedly
-
Execution process:
Let the variables take values from the sequence one by one until they are finished. Each value is taken, the loop body is executed once. The number of cycles of the for loop is related to the number of elements in the sequence
for x in 'abc': print(x) print('hello world')
3.2 range function
- range(N) - generates an equal difference sequence of [0,N), and the difference is 1; for example, range(3) - 0,1,2
- range(M, N) - generates an equal difference sequence of [M, N), and the difference is 1; for example, range(2, 8) - 2, 3, 4, 5, 6,
- range(M, N, step) - generates an arithmetic sequence of [M, N); for example: range(1, 10, 3) - 1, 4, 7
for x in range(3): print(x) for x in range(3): print('hello world!') # Exercise: use the range function to generate a sequence of numbers: - 1, 1, 3, 5, 7 # Exercise: use the range function to generate a sequence of numbers: 0,1,2,3,4,5,6,7,8,9,10 # Exercise: use the range function to generate a sequence of numbers: 0,3,6,9,12,15 for x in range(-1, 8, 2): print(x, end=' ') print() for x in range(11): print(x, end=' ') print() for x in range(0, 16, 3): print(x, end=' ') print()
3.3 actual combat
# 1) Summation problem # Exercise 1: calculate with code: 1 + 2 + 3 ++ one hundred s = 0 for x in range(1, 101): s += x print(s) # Exercise 2: sum all elements in nums s = 0 nums = [10, 29, 30, 40] for x in nums: s += x print(s) # Exercise 3: sum all odd numbers up to 100 s = 0 for x in range(1, 100, 2): s += x print(s) # Exercise 4: sum all odd numbers in nums nums = [10, 29, 30, 25, 40, 8, 1] s = 0 for x in nums: if x % 2: s += x print(s) # Exercise 5: calculate the sum of all numbers within 100 that can be divided by 3 or 5 s = 0 for x in range(100): if x % 3 == 0 or x % 5 == 0: s += x print(s) # 2) Number of Statistics # Exercise 1: count the number of even numbers within 100 count = 0 for x in range(100): if not x % 2: count += 1 print(count) count = 0 for x in range(2, 99, 2): count += 1 print(count) # Exercise 2: count = 0 for x in range(1, 100): if x % 3 == 0 or x % 4 == 0: count += 1 print(count)