Concise Python tutorial --- 6. Control Flow
In python, there are three control flow statements: if, for, and while.
If statement
The IF statement is used to detect a condition. If the condition is true, the program jumps to execute a statement block (called the if statement block ), otherwise, the program will jump to execute another statement block (else statement block ). Else clauses are optional.
Num1 = 1;
Num2 = 2;
If num1> num2:
Print (u'num1 is greater than num2. ');
Elif num1 = num2:
Print (u'num1 equals num2. ');
Else:
Print (u'num1 is smaller than num2. ');
Print U "program execution ends. ";
Note that Elif and else are optional. The simplest if statement is as follows:
If true:
Print 'true ';
You can also use the if statement in the IF statement block. This internal if statement is called a nested if statement.
Num1 = 1;
Num2 = 2;
If num1 <num2:
If num2 = 2:
Print u'num2 is equal to 2. ';
Else:
Print u'haha. ';
Note: Python does not have the switch statements in C/C ++, Java, and C #. You can use the IF-Elif-else statement to indirectly implement the switch function.
While statement
The while statement allows you to execute a piece of code repeatedly. This is similar to the while in C/C ++, Java, and C. The difference is that the while statement of python can have an optional else clause.
Num = 10;
While num> 0:
Print "num =", num;
Num = num-1;
Else:
Print U "num is less than or equal to 0. ";
For statement
Num = 1;
For I in range (1, 5 ):
Print "I =", I;
I = I + 1;
Else:
Print "over ";
Note: In the for and while loops of Python, The else statements (as long as there are else statements) after the loops exit ).
Break and continue statements
Similar to C/C ++, Java, and C #, Python also contains the break and continue statements, which are used to forcibly end loop execution.