Chapter 2 Conditional and Loop Statements

Keywords: PHP

I. if conditional statement

Basic Grammar 1:

if C1:
    pass1
else:
    pass2

When condition C1 is satisfied, the pass1 part is executed.
When the condition does not satisfy C1, execute the pass2 part

Basic grammar 2:

if C1:
    pass1
#  elif It's a branch statement. It's unlimited in number. It can have more than one statement.
elif C2: 
    pass3
else:
    pass2

Exercise: Generate a number at random. Guess what it is.

To generate random numbers, you need to import random first to use random module.

Randint (0,100): Generate random integers in the range of 0,100

import random
score = random.randint(0,10)
data = int(input("Please enter a 0~10 Numbers,I'm bigger than you.\n"))
if score == data:
    print("Congratulations, you guessed right.")
elif score > data:
    print("Haha, your guess is small. My number is ____________.{},Your guess is{}".format(score,data))
else:
    print("You guessed a little bigger.,My number is{},Your guess is{}".format(score,data))

bool() function: judge whether the value is True or False

It can be assumed that all empty values are false
# All empty values are faise: 0,None,"",(),{},[],False,
print(bool(0))
print(bool(""))
print(bool({}))
print(bool(()))
print(bool([]))
print(bool(None))
print(bool(False))

#The non-empty value is TRUE
print(bool(" "))  # Blank space
print(bool("0.0"))


#output
False
False
False
False
False
False
False
True
True

The function of boo() function:

1. Whether the judgement value is true or false

2. When the conditional statement is not executed as you expected, you can add a bool() function before it and print it out to see if the value of the expression is satisfied.

import random
score = random.randint(0,10)
data = int(input("Please enter a 0~10 Numbers,I'm bigger than you.\n"))

print(bool(score == data))
print(bool(score > data))

if score == data:
    print("Congratulations, you guessed right.")
elif score > data:
    print("Haha, your guess is small. My number is ____________.{},Your guess is{}".format(score,data))
else:
    print("You guessed a little bigger.,My number is{},Your guess is{}".format(score,data))
# Practice
'''
//Students with academic achievement >= 90 points are represented by A, 60-89 points by B, and below 60 points by C.
'''

score = float(input("Please enter your score:"))
if score >89:
    print("A")
elif 60<=score<=89:
    print("B")
else:
    print("C")

'''
//Individual income tax
'''

salary = float(input("Please enter your salary:"))
taxPay = salary - 3500

if taxPay <= 1500:
    print("The amount of tax payable is{}".format(taxPay*0.03 - 0))
elif  1500<taxPay<=4500:
    print("The amount of tax payable is{}".format(taxPay*0.1 - 105))
elif  4500<taxPay<=9000:
    print("The amount of tax payable is{}".format(taxPay*0.2 - 555))
elif  9000<taxPay<=35000:
    print("The amount of tax payable is{}".format(taxPay*0.25 - 1005))
elif  35000<taxPay<=55000:
    print("The amount of tax payable is{}".format(taxPay*0.3 - 2755))
elif  55000<taxPay<=80000:
    print("The amount of tax payable is{}".format(taxPay*0.35 - 5505))
elif  80000<taxPay:
    print("The amount of tax payable is{}".format(taxPay*0.45 - 13505))

 

II. Loop Statements

Key words: while... else...; for... esle...; break; continue;

1. while loop

Basic Grammar 1

while contition:
    statement1

Basic grammar 2: while loops add an else, which is different from other languages

while contition:
    statement1

else:
    statement2

The conditions for the exit of the while loop are:

1. When the conditional expression after while is false, it exits

2. There is a break in the loop statement block and it exits when the break condition is satisfied.

while contition:
    statement1
    break
# Input a random number, guess the number, stop if you guess right, guess right all the time.
# Mode 1
while True: score = random.randint(0, 10) data = int(input("Please enter a 0~10 Numbers,I'm bigger than you.\n")) if score == data: print("Congratulations, you guessed right.") break elif score > data: print("Haha, your guess is small. My number is ____________.{},Your guess is{}".format(score,data)) else: print("You guessed a little bigger.,My number is{},Your guess is{}".format(score,data))
# Mode 2
import random

while True:
    score = random.randint(0, 10)
    data = int(input("Please enter a 0~10 Numbers,I'm bigger than you.\n"))
    if score == data:
        print("Congratulations, you guessed right.")
        break
    else:
        print("My number is{},Your guess is{}".format(score,data))

While... Other... sentence exercise

1. Always execute the else statement with no break in the loop

count = 0

while count < 10:
    count +=1   # count = count + 
print(count)

else:
print("Here is else Sentence:{}".format(count))

# output
1
2
3
4
5
6
7
8
9
10
//Here is the else statement:10
# print Different positions of sentences lead to different results.

count = 0

while count < 10:
    print(count)
    count +=1   # count = count + 1
else:
    print("Here is else Sentence:{}".format(count))

# output
0
1
2
3
4
5
6
7
8
9
//Here is the else statement:10

2. Do not execute the else statement, after the loop is interrupted by break, no longer execute else.

Both of the above examples execute the else statement, so when won't you walk into the else statement?

# When will it not arrive? else What's in the sentence?
count = 0

while count < 10:
    print(count)
    count +=1   # count = count + 1
    if count > 6:
        break
else:
    print("Here is else Sentence:{}".format(count))

#output
0
1
2
3
4
5
6

 

2. for cycle

The difference between for loop and while loop:

1. The while cycle can continue as long as the condition is satisfied.

2. for loops, the traversal mechanism is adopted, and the loops are repeated as many times as the conditions are satisfied.

Basic Grammar 1:

for data in iterator:
    statement1

 

Basic grammar 2:

for data in iterator:
    statement1
    
else:
    statement2

Basic Grammar 3:

for data in iterator:
    statement1
    break

# for There are break,If the condition is satisfied, it will not be implemented. else Part of it.
else:
    statement2

range() function:

print(list(range(3)))        # The first parameter is not specified. The default is 0.
print(list(range(1,10)))     # The last 10 is not counted.
print(list(range(1,10,2)))   # 2 Represents step size, i.e. taking a number every two bits

# output
[0, 1, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]

Exercise: Change the while loop above to the for loop

1. Execute the else statement

count = 0

for count in  range(5):
    print(count)
    count +=1   # count = count + 1
else:
    print("Here is else Sentence:{}".format(count))

# output
0
1
2
3
4
//Here is the else statement:5

2. After the break statement is satisfied in the for loop, the else statement is not executed.

count = 0

for count in  range(5):
    print(count)
    count +=1   # count = count + 1
    if count > 4:
        break
else:
    print("Here is else Sentence:{}".format(count))

#output
0
1
2
3
4

3. Continue

When continue is executed, it goes directly to the next loop, and the logic that follows will not be executed again.

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

# Interpretation
'''
When i=0, the remainder of 0 divided by 2 is 0, which satisfies the if statement. The logic in the if statement is continue, so the next loop is performed directly instead of the print statement.
When i=1, the remainder of 1 divided by 2 is 1. If statement is not satisfied, logic in if statement is not executed, print statement is executed, print 1 is printed.
When i=2, the remainder of 2 divided by 2 is 0, which satisfies the if statement. The logic in the if statement is continue, so the next loop is directly performed instead of the print statement.
... ''' # Output 1 3 5 7 9

Circulation exercises

1. With 1, 2, 3, 4 digits, how many different and non-repetitive three digits can be formed? How many are they?

count = 0
for baiwei in range(1,5):
    for shiwei in range(1,5):
        for gewei in range(1,5):
            if baiwei == shiwei or baiwei == gewei or shiwei == gewei:
                continue
            count +=1
            print("{0}{1}{2}".format(baiwei,shiwei,gewei))

print("There are no duplicate figures in common{}individual".format(count))

2. There is a fractional sequence: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13.... Find out the sum of the first 20 terms of this sequence.

Aspect 1: By means of intermediate variables

fenzi,fenmu = 2,1
result = 0
for i in range(1,21):
    result += fenzi/fenmu
    # Here we need to use a temporary variable to temporarily save the molecule of the previous fraction.
    temp = fenzi
    fenzi = fenzi+fenmu  # If there is no temporary variable storage above, the value of the molecule will be changed here, and the denominator of the next data will not be the molecule of the previous number.
    fenmu = temp
print(result)

Method 2: The way without intermediate variables

result,fenzi,fenmu = 0, 2, 1
for i  in range(20):
    result += fenzi/fenmu
    # Write them in one line, and here they are assigned at the same time.
    fenzi,fenmu  = fenzi+fenmu,fenzi
print(result)

 

3. Enter a string to determine whether it is palindrome or not.

Method 1: for...else...

'''
//Solution ideas:
1. Firstly, the length of the string is calculated. len()
2. Take the first letter of the string and compare it with the last letter once.
3. If all strings are the same, they are aligned all the time, and the loop alignment is finished, and they are not executed. if If you go into a block of sentences, it's palindrome, otherwise it's not palindrome.
4. Strings are fetched from forward to backward, starting from index 0, and from backward to forward, from index.-1 Beginning

'''
data = input("Please enter an English string below.:\n")
for i in range(len(data)):
    if data[i] != data[-(i+1)]:  # The difficulty here is how to retrieve the letters of the string from the back to the front.
        print("This is not a palindrome")
        break
else:
    print("This is palindrome")

Method 2: Inversion of slices

Basic knowledge of slicing

data = "abcdefghigk"

print(data[0:5])  # abcde  Order to the fifth
print(data[0:5:2]) # ace   Take it every other two times
print(data[:5:2]) # ace   Do not write at the beginning. The default is to start with index 0 and take it every other two times.
print(data[::2]) # acegik   Neither the beginning nor the end is written. The default is to start with index 0, take the last one, and take it every two times.
print(data[::-1]) # kgihgfedcba   Neither at the beginning nor at the end. The default is from the index.-1 Start moving forward.It's equivalent to flipping a string.

print(data[5:0:-1]) # fedcb   Starting with the fifth, cut off to zero.-1 What stands for is taking the opposite direction.
data = input("Please enter an English string below.:\n")

if data == data[::-1]:
    print("It's palindrome")
else:
    print("Not palindrome")

Posted by slicer123 on Sat, 27 Jul 2019 03:51:54 -0700