A string variable is a string of characters – characters (like a
, b
,
and c
) literally strung along together in a sequence. We call that sequence of
characters a “string.”
In the following code snippet, username
is a string variable with the value "fred.rogers"
:
username = "fred.rogers"
Printing Strings
In computer programming, the term print is a verb that means to write something to the terminal window. It does not have anything to do with a printer that prints paper documents.
Print strings to the terminal window where your code is being executed with
the print()
function:
username = "fred.rogers"
print(username) # output: fred.rogers
That would result in the following:
fred.rogers
To include a string variable in a larger string, use an f-string, short for
formatted string. An f-string is declared just like a normal string (it’s still a sequence of
characters) with one exception: there’s an f
character in front, f"like this"
.
Additionally, variables can be included with curly brackets f"like this: {username}"
,
making f-strings the right choice whenever you want a convenient way to include
variables in your strings.
Following is an example of how to include the variable username
in an f-string:
# Create a new string variable called `username`:
username = "fred.rogers"
# Print friendly username message to terminal window using an f-string:
print(f"Account username: {username}")
The above would result in the following being printed to the terminal window:
Account username: fred.rogers
The f-string format has been available since Python 3.6.
Printing Variables in Strings
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:
username = "fred.rogers"
the_space = username[9]
the_word_professor = username[:9]
the_word_lawson = username[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:
- An Introduction to String Functions in Python 3 is a great overview of everything you can do with strings in Python. Study 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:
|
|
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:
|
|
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:
|
|
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:
|
|
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!
- In Python, the
and
andor
operators are called Short-Circuit Operators. This page in the Docs helps to illustrate how to use them, along with thenot
keyword. - A short conversation on why Python programmers use
if not
can be found here - How to Write Conditional Statements in Python
- Another Tutorial on Conditional Statements. For what it’s worth, I like this one the best.
- A technical crash course in Python strings. Good if you are familiar with another language.