Jesse Lawson

buy me a coffee ☕ / home / blog / tutorials / portfolio / contact

Feb 13, 2020 - Tutorials Python

Python Lecture Notes: Strings & Conditionals

We already know that we can use variables to represent different mathematical types, like integers and floats. This is fine for when we want to make, say, a shipping costs calculator, but what happens when we start adding words and sentences into our program requirements?

A string variable is a string of characters. For example, given the following code:

my_name = "Professor Lawson"

The variable my_name is a string variable, and the = operator assigns the value of the string literal "Professor Lawson" to the variable my_name.

We use the term string literal to mean a static piece of memory that has been carved out specifically for our string. In other words, Python doesn’t have you create an empty variable and then move the value "Professor Lawson" into it; you create a variable that points to a string literal’s address in memory. (This will become very important as you venture off into more systems-level languages like C/C++ and Rust).

Printing Strings

You’re already familiar with how to print strings to the console window with the print() function:

print(my_name) # outputs "Professor Lawson"

That would result in the following:

Professor Lawson

But let’s say I wanted to modify the output a bit so that the result reads like this instead:

Hello, my name is Professor Lawson.

To do this, we include the value of what the variable my_name points to by wrapping it in curly brackets, like this:

{my_name}

This allows me to use the variable inside a f-string, which is short for formatted string, a type of string literal. An f at the beginning of the string tells Python to interpret anything wrapped in brackets as a variable name.

An f-string is just like a normal string, except with one difference: there is an f before the leading double quote:

f"Like this. Note the lowercase f at the beginning."

The f-string format has been available since Python 3.6.

Printing Variables in Strings

We will use f-strings to print some variables.

Let’s say we own a trucking company and we want a daily morning report that tells us how many trucks are running, how many are in the shop, and how many total packages are being delivered:

num_running_trucks = 45
num_trucks_in_shop = 7
total_packages_for_today = 3300

print("Morning Report:")
printf(f"There are {num_running_trucks} trucks running;")
printf(f"There are {num_trucks_in_shop} in the shop;")
printf(f"We have {total_packages_for_today} packages out on delivery.")

This would result in:

Morning Report: 
There are 45 trucks running; 
There are 7 in the shop; 
We have 3300 packages out on delivery.

The variable inside the brackets are being evaluated as expressions. That means you can put different kinds of expressions in there, like mathematical ones:

print(f"Total trucks owned: {num_running_trucks + num_trucks_in_shop}")

Accessing Characters in a String

Strings are technically a string of characters. The string part refers to how the characters are strung together in memory. That means that, if you know what a particular character’s index is, you can pull it out of a string:

my_name = "Professor Lawson"

the_space = my_name[9]
the_word_professor = my_name[:9]
the_word_lawson = my_name[10:]

In Python, this technique is called slicing.

We access individual letters with just the ordered number of their position in the string. That ordered number position is called the index. In most languages, Python included, arrays are zero-indexed. That means the first element in the array is number 0, not 1.

The colon : in the straight brackets helps is fine tune what we are slicing. If, say, we wanted to slice out my name from a party invitation, we would do it like this:


message = "Party Invites go to Sarah, Doug, Maya, Will, Jesse, and Amit."
#                                                       ^     ^
#                                                       |     |
#                                                      45    51

part1 = message[:44]
part2 = message[52:]

new_message = part1 + part2

print(new_message)

The above code would yield:

Party Invites go to Sarah, Doug, Maya, Will, and Amit.

Neat! Well, except for the not getting invited part. Oh well!

There’s a lot more that strings can do than this:

Conditionals

Conditionals are ways of controlling program flow, just like how they control thought flow in conversation. For example:

If you are less than five feet tall, you cannot ride the rollercoaster. If you are more than eight feet tall, you cannot ride the rollercoaster.

These two statements are both conditional statements. They put a condition on the outcome–which, in this case, is riding a rollercoaster.

We can think about these conditions for riding a rollercoaster in Python by first writing them in something called pseudocode, which is just pretend-code that helps us explain things. Pseudocode is not real; you cannot compile it or interpret it. It’s purely meant to help explain things to other programmers. Think of it like writing a sentence in a special language so that programmers can understand it easier.

There are no right or wrong ways of writing pseudocode since it’s not real, so don’t pay attention to my syntax too much:

if height is less than five feet:
    rollercoaster = False
if height is greater than eight feet:
    rollercoaster = False

You can see that, sometimes, pseudocode might contain valid Python syntax. That’s okay. Remember: pseudocode is only used to help explain something to another programmer, and can be as syntactically or not syntactically sound as you want.

Now that we have used pseudocode to express our intent, let’s talk about how we can write this in Python.

Let’s say we have a variable height and it holds the height of a rollercoaster rider in feet, and a variable rollercoaster which is True if the rider can ride, and False if the rider cannot ride.

We can use Python’s if keyword to set rollercoaster to False for any condition that might make it so that a rider cannot ride the rollercoaster.

The syntax is as follows:

if <expression>:
    <statement>

Let’s take a look at it in action:

1
2
3
4
5
6
7
8
height = 10 # This is a tall person!
rollercoaster = True # We will assume anyone can ride unless they match one of 
the criteria below

if height < 5: 
    rollercoaster = False
if height > 10:
    rollercoaster = False

As you can see, we can use the conditional keyword if to run code inside the if block only if the condition is satisfied. The condition is the expression between the word if and the colon : sign.

Since we have two conditions that each produce the same result, we can refactor this solution to make it more efficient:

if height < 5 or height > 10: 
    rollercoaster = False

The above code will check if height is less than 5 OR greater than 10, and if either of those are true, it will execute the statements within the scope of that if-block.

We can add different conditions right along the height requirements, too. For example, let’s say we have height requirements AND a requirement that no one can ride if they just ate lunch:

1
2
3
4
5
6
height = 6
just_had_lunch = True
rollercoaster = False

if height < 5 or height > 10 or just_had_lunch:
    rollercoaster = False

Note how I didn’t have to say or just_had_lunch == True, since just_had_lunch evaluates to True (because that’s what we assigned its value).

But what if we had a third condition, one in which a mechanic can ride the rollercoaster regardless of whether she had lunch or how tall she was? Well, we might add it like so:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
height = 6
just_had_lunch = True
is_mechanic = True
rollercoaster = False

if is_mechanic:
    rollercoaster = True
else: 
    if (height > 5 and height < 10) and not just_had_lunch:
        rollercoaster = True

Now that’s a lot of new stuff!

I’ve used two new keywords here: else, and not.

In an if-else block, the syntax goes like this: if expression then statement, else statement. Another way to think of it is like this:

if <condition>:
    <statement>
else:
    <some other statement>

The keyword else is like saying “otherwise;” if the condition next to if is not true, then the else block will trigger.

Speaking of the else block, notice how I put a if statement inside the else block. This is called nesting–which is when you nest statements inside one another.

So the if-else block lets us do something if some condition is met, otherwise (else) do something else.

Head over to this interactive example for a more interactive walkthrough.

There is one more keyword I want you to know about: elif, which is short for else if.

They go in the middle of the if-else blocks, like this:

1
2
3
4
5
6
7
8
9
you_are_confused = False
you_would_like_to_know_more = True

if you_are_confused: 
    print("Try one of the tutorials")
elif you_would_like_to_know_more:
    print("Great! Try one of the tutorials!")
else: 
    print("This would trigger if you_are_confused is false AND you_would_like_to_know_more is false.")

Notice what I wrote in the print() statements. Using elif is a way to help control flow within the if-else blocks.

Explore on your Own

Pro-tip: Don’t skip over these!