Python Series Part 4: Flow Control

Jarret B

Well-Known Member
Staff member
Joined
May 22, 2017
Messages
368
Reaction score
423
Credits
13,526
In this article, we will discuss the methods of managing the flow of statements in a program. These methods include:
  • If
  • For
  • While
We will also cover two items that are used to exit these flow control items or to bypass an iteration of a loop.
  • Continue
  • Break
If Statement

An 'if' statement is used to test information and determine what to do depending on the outcome of the test.

The standard syntax is: 'if (condition):'.

For instance, we can test if a value is within a certain range. Let's assume we want to test if a value is over 1000 and then increment another value. We will assume we have a variable named 'score' and if it is greater than 1000, we will increase the level and reduce the score value by 1000.

Code:
if (score > 1000):
     level = level +1
     score = score - 1000

You can see that any lines to be included in the 'if' statement you indent. Once we do not indent any lines, we are out of the 'if' section.

We can also have an 'if-else' statement. We perform the 'if' check like before, but instead of performing code when the statement is true, we can also have a section to manage when the statement is false.

Let's assume we have a Number Guessing game. The program generates a random number into a variable named 'num'. We input a guess from the user that we compare to the random number. We place the guessed number in a variable named 'guess'.

Code:
if (guess > num):
     print ("Your guess is too high, try lower.")
else:
     print ("Your guess is too low, try higher.")

This gives you a basic idea, but we are missing the check to see if the guessed number is equal to the 'num'. The example is only to give you a taste of how flow control works. I'll include the code for a number guessing game towards the end of the article.

But what if we have multiple options to test? Let's look at the previous example and add in the option that the guess is correct.

Code:
if (guess > num):
     print ("Your guess is too high, try lower.")
elif (guess < num):
     print ("Your guess is too low, try higher.")
else:
     print("You guessed the number!")

Here, you can initially test to see if our guess is greater than the random number. If the guess is greater, then we give a message that the guess was too great.

The second 'if' statement, an 'elif' statement, is testing if the guess is less than the random number. If this is true, we print a statement that the guess was too low.

The 'else' statement here will leave the only other option that the user guessed the number correctly.

For Statement

A 'for-loop' is used to run through a loop of code a specific number of times.

Let's assume we have a game that has five levels. We can determine the level the user is on by testing the score. The values for the levels are 1000 increments. We will start at 5000 and go to 1000. Initially, we will set the value if the 'level' variable to '0'.

Code:
level = 0
a=[5000, 4000, 3000, 2000, 1000]
for value in a:
     if (score > value):
          level = (value / 1000)

There are a few things going on here that we need to cover.

In the second line, we set the variable 'a' to the values for the level (5000, 4000, 3000, 2000, 1000). The term for this is a list. We assign a 'list' of numbers to the variable and we will access them one at a time.

The third line shows that we are using a 'for' loop and assigning an entry in the list of 'a' to the variable 'value'.

The fourth line is an 'if' statement to test if the 'score' is greater than the 'value' from the list. If the score is greater, then we set the 'level' to the value divided by 1000. The program changes the 'level' variable from '0' to '1', '2', '3', '4' or '5'. We assume that at level 5, we win the game.

After we set the value of 'level', we will have more code.

While Loop

A 'while-loop' is used to perform a section of code an indeterminate amount of times.

Let's assume we have a game that we want to start out by playing a game and when done, ask the user if they want to play again. If the answer is yes, we will play again. We do not know how many games the user may want to play.

The code would be like:

Code:
play = 0
while (play == 0):
     # The game code goes here
     again = "a"
     while ((again != "y") and (again != "n")):
          again = input ("Do you want to play again? (y/n) ")
     if (again == "n"):
          play=1
print ("Thanks for playing.")

We start out by setting the variable 'play' to '0'. We execute the game code while the variable 'play' is '0'. Once the user completes the game, we set a variable called 'again' to 'a'. While the variable is not 'y' and 'n', we ask the user to enter whether they want to play again. If the user does not enter 'y' or 'n', then a prompt appears for an answer. If the user enters a 'y', then the loop performed again, and the user plays again. Should the user enter 'n', then the variable 'play' has a value of '1' and the loop ends. The program prints a message thanking them for playing and the code ends.

The 'while' statement can also use an 'else' since we are testing for a condition. It is the same as an 'if-else' statement in function.

Break

If we are inside one of the flow control methods, we can use 'break' to get out of the current method.

Just keep in mind the indenting for the methods. The 'break' command will exit the current indentation that contains the method that put the execution into that indent.

If we look at the number guessing game, we can use the 'if' statement to see if the number is too high, too low or correct. If the guess is correct, then we need to exit the 'if' statement:

Code:
     else:
          print ("You guessed the number!")
          win = 1
          break

The 'break' will exit the initial 'if' statement that the 'else' is connected to in the code.

Continue

Instead of leaving a method, we can use 'continue' to skip the flow in the loop.

Let's say we have a 'for-loop' and we go through the code to increment a number when some condition is true.

If we hit the condition that is false, or it could be true depending on the code, we want to skip the loop and not perform the code. We test for the condition, and if needed, we issue the command 'continue' to go to the end of the loop and do the next iteration.

We can look back at a previous example and make a few changes:

Code:
level = 0
a=[5000, 4000, 3000, 2000, 1000]
for value in a:
     if (score <= value):
          continue:
     if (score > value):
          level = (value / 1000)

For entries that are less than or equal to the score, we can not even perform the remaining code.

Number Guessing Game

Here is the Number Guessing game. The only lines that you may not know is the generation of the random number that is placed into 'num'.

The line 'from random import randrange' is used to set a random number and import into 'randrange'. We then use 'randrange' to generate a number from 0 to 99. We then add 1 to make the range 1 to 100. The program places the random number into the variable 'num'.

Code:
play = 0
while (play == 0):
     from random import randrange
     num = (randrange(99) + 1)
     win = 0
          while (win == 0):
          guess = input("Enter your guess (1 to 100): ") 
          guess = int(guess)
          if (guess > num):
               print ("Your guess is too high, try lower.")
          elif (guess < num):
                print ("Your guess is too low, try higher.")
           else:
                print ("You guessed the number!")
                win = 1
                break
     again = "a"
     while ((again != "y") and (again != "n")):
           again = input ("Do you want to play again? (y/n) ")
      if (again == "n"):
          play=1
print ("Thanks for playing.")

Hopefully, this can help you use some of the flow control methods.

Conclusion

The flow control methods should help you use decision making and looping to create some code in Python.

Be familiar with the flow control methods, since these are very useful in coding.
 
Last edited:


And here I was, doing my flow control all wrong! I was just holding it all in until I peed my pants. Now it all makes sense. :)
 
while (no_coffee == true):
rage
Kill
while (coffee < 2)

I've been trying to convince family members and pets to use their pre_coffee voices, which is to say no voice at all. Apparently I have yet to explain the concept in sufficiently low level terms.
 

Members online


Top