Learn about Python Variables and Control Flow

Sat Sep 3, 2016 - 1000 Words

Today we’re going to continue to our series on Python. We’re going to learn how to name data using variables, and how to make our programs behave differently based on the values in that are passed in.

Goal for this Tutorial:

  • Learn how to use variables to name data.
  • Learn how to use if/else for control flow.
  • Learn how to take user input from the command line in our scripts.

Today’s tutorial is going to take place almost exclusively in a script file, so have your favorite text editor handy and lets make sure we have a container created that we can run our script in.

$ docker run --rm -it -v $PWD:/usr/src/python -w /usr/src/python python:3.5 bash

We’re going to create a script that will allow the user to input a string and it will output whether or not the string is a palindrome (a word or phrase that reads the same in both directions excluding spaces and punctuation, examples: “radar” or “nurses run”). Here are the steps that we’re going to take to accomplish this:

  1. Store user’s input into a variable, I’m going to call it “phrase”.
  2. Create another string by removing spaces from “phrase” so that we give the proper response for phrases like “nurses run”. We’ll call this one “sanitized_phrase”.
  3. Compare “sanitized_phrase” with “sanitized_phrase” backwards. If they are the same then output that the phrase was a palindrome, otherwise output that the phrase isn’t that exciting.

Naming Data with Variables

Up to this point in our exploration of Python, we’ve run each line as though it wasn’t connected to any of the code around it, but today we’re going to learn to how to keep a piece of data around for awhile so that we can do change it and use it in comparisons before completing our program. Let’s look at how to create a variable in the Python REPL.

>>> my_var = "This is my var"

You’ll notice that it didn’t output anything because nothing was returned or written to the screen. If we enter my_var by itself we can see the string we entered.

>>> my_var
'This is my var'

Anytime we use my_var it will give us this value, until we set a different value for that variable.

Accepting User Input

Now to start our palindrome checker script, open up palindrome.py. The first step in our process is to take in user input so that we can see if it’s a palindrome. Let’s learn how to do do that now.


phrase = input("Enter a phrase: ")
print("Your phrase was '%s'" % phrase)

Before we talk about what we just wrote let’s run it:

$ python palindrome.py
Enter a phrase: This is my phrase
Your phrase was 'This is my phrase'

Our first line creates a prompt and waits for the user to hit the return key. Additionally, input also returns the text that was entered before the return key was hit. We then echo that back out to the screen just to make sure that it worked.

Removing Spaces

Up to this point we’ve only used functions that we pass data into, types have functions that are tied to them known as methods and we get to use some of those now. To remove the spaces from the string we’re going to use the method replace the type string has. We will be replacing spaces with empty strings, which causes them to be removed.


phrase = input("Enter a phrase: ")
sanitized_phrase = phrase.replace(" ", "")
print("The phrase without spaces '%s'" % sanitized_phrase)

Reversing a String

Reversing a string in Python is pretty interesting, but it’s not the most intuitive. Strings are essentially groups of characters and we can break them into smaller groups by slicing them. I’ll explain slices a little more when we talk about Arrays, but for now we’re going to go straight to reversing a string.


phrase = input("Enter a phrase: ")
sanitized_phrase = phrase.replace(" ", "")


The [::-1] means we want the string starting from the beginning, going all the way to the end, but we want to step through them backwards (that’s the -1 in action).

If palindrome then …

We’re to the final step of our first script. We have our sanitized_phrase and we know how to reverse it, and now we just need to compare it to it’s reversed self. We’ll make our comparison with the == operator, but that doesn’t get us 100% of the way to printing out different messages. Of that we need if and else.


phrase = input("Enter a phrase: ")
sanitized_phrase = phrase.replace(" ", "")

if sanitized_phrase == sanitized_phrase[::-1]:
    print("'%s' is a palindrome!" % phrase)
    print("'%s' isn't that exciting." % phrase)

A few things to note here: 1. if and else both need to be followed by a : 2. The code inside of each conditional branch needs to be indented 4 more spaces than the if/else.

This is the first time that we’ve seen the whitespace dependency of Python. Indenting is how we separate code groups into different levels.

If we run our script now and use a phrase like nurses run we should see “‘nurses run’ is a palindrome!”. If we use a phrase like “bananas” then we’ll see “‘bananas’ isn’t that exciting.”


Today we wrote our first more involved program. This script required us to use variables, explore the methods in Python, and use if/else to do different things based on the string that was input from outside of the program. This is just the beginning of our programming adventure, and I hope this has sparked your curiosity to write other little tools. Let me know what you’re building with what you’re learning.