Learning Python Programming - Part 4 - Program Flow

in #programming8 years ago

Welcome to the 4th part of an ongoing series, Learning Python!

Today we will be learning about program flow and the different features that make the code jump around.


source

First, what is program flow? and what can affect it?

Program flow is simply what directions the code can go while it runs.
Many things can affect program flow including:

  • function calls
  • if statements
  • loops

Function calls

What happens when you call a function? The code jumps to the function code and runs it before it returns to where it was called. This is the finest example of program flow; where the code jumps from one part to another. This can be really helpful in the case of running the same length of code over and over without typing it out every time.


source

Here's an example:

def print_greeting():    #1
    print("Hello")
    print("Goodbye")
print_greeting()    #2
print_greeting()    #3
print_greeting()    #4
print_greeting()    #5
print_greeting()    #6

This example code goes down the line, first defining the function print_greeting at number 1. This is a simple function definition like we learned in the previous lesson. Numbers 2 through 6 all call the function print_greeting causing the code to jump to the definition of the function, and run it, each time it is called. What would the output of this "program" be?

Hello
Goodbye
Hello
Goodbye
Hello
Goodbye
Hello
Goodbye
Hello
Goodbye

Simple right?

Boolean Expressions

To affect the flow of the code further, we need to tell Python an effective yes or no. The way to code this is with booleans and boolean expressions. A boolean expression is nothing too special; it is simply a line of code that evaluates to a True or a False. To write a boolean expression, you can use one of the comparing operators or any keywords comparing two booleans.

Comparing operators

  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to
  • == equal
  • != not equal
Some of these may be very familiar to you, as they are used in math also. In computer science these comparing operators take the value to the left and compare it to the value on the right. The first four comparing operators are strictly for numbers, but the last two can compare any valid variable type to any other valid variable type. The == operator asks, "Are these two values exactly the same?" whereas the != operator asks the opposite, "Are these two values different in any way?" The exclamation mark is a common operator for not.

Keywords for booleans

  • and
  • or
  • is
  • not
  • in
The first keywords are pretty self explanatory. But for those who need it: the and keyword only returns True if the values on either side of it are both True, the or keyword returns True if either value are True, the keyword is is the same as equals, and the not keyword reverses the value given just after it to be opposite of what it is. The in key word requires the second variable to be a list, tuple, or dict type, and will return True if the second value contains the first value.

Order of precedence


source

To write a long chain of arguments, Python needs to know which one to do first so that every time this chain is evaluated, Python gets the same answer. To do this Python uses an order of precedence to tell it which operations to do first, second, third, and so on.

  1. lambda
  2. if-else
  3. or
  4. and
  5. not
  6. in, not in, is, is not, and comparing operators
  7. | bitwise OR
  8. ^ bitwise XOR
  9. & bitwise AND
  10. <<, >> Shifts
  11. +, -
  12. *, @, /, //, %
  13. +x, -x, ~x positive, negitive and bitwise NOT
  14. ** exponents
  15. await
  16. indexes and attribute reference
  17. list, tuple, dictionary, and set display

Note: I know we have not even begun to learn most of these different operations, but this is only part 4.
Python goes down this line of precedence on every calculation. If you want to get around it, you can use parenthesis to bring what's in the parenthesis to a higher level of precedence. When you are writing a long string of this and that or something else, you'll need to know which keyword will evaluate first to get an understanding of how your program works. (or doesn't work)
Basically, just know that this is a reference for the order of precedence and that or evaluates before and in your boolean expressions.

If statements

If statements affect program flow a bit more than function calls do. If statements have the power to ignore parts of the code.


source

An if statement looks for a boolean to tell it what to do. If it finds a True, it goes on to run the code under the True, but if it finds a False, it will skip the code under the True and move on.
The basic if statement only has one required part to it, and it looks like this:

if [expression]:
    [code]

An if statement can contain an elif, and an else, but they are not required. You can have as many elifs as you would like, but only a single else. A full skeleton of the if-elif-else code looks like this:

if [expression]:
    [code]
elif [expression]:
    [code]
else:
    [code]

I used [expression] and [code] in the examples to signify two different parts that can change with your use of the if statement. The [expression] part will hold a line of code that can return a boolean variable or a 0 or 1. This can be achieved by simply typing in a True, False, 0, 1, or any other boolean expression. The [code] part can hold any code that you want to run if the [expression] statement will give a True or a 1. If the [expression] on the first if statement evaluates to True, the [code] under the if will run and then Python will skip all further elifs or elses, but if the [expression] evaluates to False it will not run the [code] and it will look for an elif or an else. If an elif is present, it will evaluate it similar to another if statement, but if it finds an else, it will run the else. This is basic if statement operation. This can be illustrated with the examples below.

if True:
    [code] # this code will run because the expression was replaced with True.
elif [expression]: # The rest of this code will be skipped because the above code ran
    [code]
else:
    [code]

if False:
    # because this is false the code immediately below will not run and 
    # Python will look for an elif or an else
    [code]
elif True:
    # finding an elif, Python reads it as a new if statement.  
    # Because it evaluated to True, the code below will run
    [code]
else:
    [code]

if False:
    # the expression evaluated to false, so Python skips the below code
    [code]
else:
    # finding an else, Python runs this code
    [code]

Very simple operations, but the explanation of them can get hairy.

Loops

The operation of a loop is similar to the operation of an if statement. A loop will keep going round until the "if statement" inside of them is false. There are two types of loops in Python: for and while. The for loop goes for a set amount of times before it reaches its guaranteed stop. The while loop goes until the boolean expression you give it evaluates to False. A while loop can easily be made into an infinite loop.


source

For loop

The for loop in Python is mostly used, at least in my experience, to iterate through a list of elements and assign the temporary variable to each element to run the code contained with.
The for loop skeleton:

for var in lst:
    [code]

Where var is any valid temporary variable name and lst is any valid list, tuple, dict, or range.

This is a great time to learn about the range method. The range method is used to get a special list of numbers from the starting point you give it, default 0, to the ending point you give it minus one with an optional step argument that determines skipping numbers in this special list. This is very helpful if you wanted to use a list of numbers, like to count to ten, or do something fifty times.

# let's print a list to count to 10 with a for loop
for x in range(11):
    print(x)

In the example the temporary variable takes on the values 0 through 11 minus 1 and is printed each time.

While loop

The while loop is used to keep looping over and over until the boolean expression given is False. An easy way to make it never be False, is to just tell it True.

while(True):
    print("infinite loop")

The only way you can use a while(True) loop is if it contains a break statement. (explained in the loop keywords section below)
How can we effectively use a while loop?
One of the first ways to learn how to use a while loop is with the basic, initialization, control, and step, criteria.
Initialization:
To use the initialization you define a variable outside the while loop to be used like a counter.
Control:
The control part is the boolean expression of the while loop, and must contain the initialized variable.
Step:
Step is most likely just the initialized variable += 1, but you can use any number. It will only affect how many times the loop goes through.
Let's see it.

var = 0 # Initializing a variable called var
while (var <= 10): # starting the while loop with the control of while var is less than or equal to 10
    print(var) # printing the var variable to the console
    var += 1 # the step will increment the variable by one each time the loop goes through

What will this example output?

0
1
2
3
4
5
6
7
8
9
10

Pretty simple eh?

Loop keywords

Inside a loop you can use the keywords: continue and break. The continue keyword will skip the rest of that loop iteration and move onto the next one; a very helpful way to make your while loop skip certain iterations without terminating the loop with the boolean expression. The break keyword will terminate the loop. It will break the loop.
Star student question!

# what will this loop do?
while (True):
    break

If you said it will do nothing, you're correct!
But if you said it will be an infinite loop, you should re-read the loop keywords section.

Let's write a program!

For this program, let's make an overly complicated way to count to 10,000! For our program, we'll need to print out the words of each number that adds a new digit to our number. Our program will utilize a for or a while loop and a block of if statements.
For:
In our for loop, we can use the range method with base 1 and max 10000+1.
Our if statements will then ask if the number is a 1, a 10, a 100, a 1000, or a 10000.
Lastly, if the number wasn't printed, we need to print out the integer.
Together, this will look something like the example below.

While:
In our while loop, we need an initialize, a control, and a step.
The initialize will look something like var = 1, because we don't need a 0.
Then we will setup our while with the control of while the var is less than or equal to 10000.
Next we need our if statements to ask if the number is a 1, a 10, a 100, a 1000, or a 10000 and if it isn't we need to print the real number var contains.
Lastly, we need our step to increment the var for the next iteration. Because we don't want to skip numbers in this counter, we need to add 1 to the var.
This while loop will look something like this:

Coin Marketplace

STEEM 0.22
TRX 0.26
JST 0.040
BTC 96714.38
ETH 3411.05
USDT 1.00
SBD 3.17