Python Flow Control
Conditionals / decision making - IF statement
- The if header line ends with a colon (:)
- The statement block must be indented.
- elif means “else if”,
- elif is followed by a colon(:)
- else: execute the final statements
This script uses the if -else statement, to decide if the value of x is greater than 5, then do this, otherwise(else) do that.
Loops
A loop is the iterative process of repeating of code lines. There are different types of loops such as the For
Loops, the While
Loops and the Nested Loops.
Example of For Loop:
This script uses the FOR statement to repeat each item that is within the range of 10. Starting from 0 and up to(but not including) the last number 10. The default incrementing step is 1.
It will print the value for x from 0 to 10 for each of these value.
thus the result will be 0, 1, 2, 3, 4, 5, 6, 7,8, 9
Example of While Loop:
This script uses the WHILE statement to repeat showing what the count is, and as long as the value of count is less than 9, it will show the count, then add one to count. Once count reaches 9, it will stop and do the next line, which is to show "Good bye!"
Example of Nested Loop:
This script uses a series of nested loops to find out all the numbers between 2 and 100 that is prime.
It has a double nested while loop with a double if statement in it.
Control Statements
Control statements are typically used together with the loops to complete
the loop.
•
Break statement – to exit the loop (Loop_ForBreak_Prime.py)
•
Continue statement – jump to the top of the loop
•
Else statement – execute when condition is
false.
•
Pass statement – command to do nothing.
No comments:
Post a Comment