The For loop is used in the previous article, and this section describes the common if statement, the for statement, and the while statement.
1. If statement
Cars = ['BMW','Benz','BYD','Ford','Rowei'] forCarinchCars:ifCar = ='BMW': Print (Car.upper ())Else: Print (Car.title ())
The meaning is that if there is a car brand is BMW, the capital output.
Determines whether the code in the IF statement is executed based on the value of the condition test to TRUE or false
' BMW '
= is an assignment that assigns the right value to the variable car
' BMW '
= = is similar to constant equals, indicating whether the left and right sides are exactly equal. Returns true if equal, otherwise false. If TRUE indicates that a condition is met, the clause inside can be executed.
else indicates that the IF condition evaluates to false and executes an else branch.
1 if 2 : print (' not the right answer ')
Not the correct answer will be output,! = is not equal to, like a mathematical symbol.
Answer! = 2 results in True,if True to execute the following print function.
There are other symbols >=,<=,>,<.
Combination of multiple if condition statements
for inch Cars: if ' BMW ' : print (Car.upper ()) 'Ford': print (Car.upper ()) Else : print (Car.title ())
First determine whether the value of car is BMW, if not to judge whether it is Ford. is to capitalize the output, not jump to the else branch below. After the last else there is no conditional judgment, the default is true. In the if can not behind nothing, grammar rules that can't.
2. While loop
The For loop is used to have a block of code for each element in the collection, while the while loop continues to execute until the condition is not satisfied.
From the while loop from 1 to 5
1 while 5 : print (current_number) 1
When Current_number is increased to 6 o'clock, Current_number <= 5 is not satisfied, exiting while loop. If there is no exit condition, the while loop is executed until the program collapses or the system shuts down. Exit conditions are added in general programming.
In addition to judging the result of the statement after the while is false to end the loop, you can also break to jump out of the while loop, the above transformation
1 while True: if 5 : Break Print (current_number)
If more than 5 jump out of the loop, if you do not want to print when the value is 2, you can use the continue to end the cycle of the next cycle.
1 while True: if 2 : 1 Continue if 5 : Break Print (current_number) 1
Pupils learn Python (iv)