4 Strings and Booleans
In This Chapter
So far we have learned how to save and run our programs, get some input from the user, print text, and do math. We have also seen how to cast data types.
But before we can build software that actually makes decisions, we need to master how the computer handles text and logic. In this chapter, we will cover:
- F-Strings: The modern, clean way to format text and variables.
- String Methods: Built-in tools to clean up and modify text.
- Booleans: The data type of truth (
TrueandFalse). - Comparison Operators: Teaching the computer how to answer
TrueorFalsequestions. - Logical Operators: Combining questions using
and,or, andnot. - The Project: The Better Mad Libs generator using advanced formatting!
4.1 Strings (str)
Strings are just text. They are created by wrapping characters in quote marks (" " or ' ').
In normal English, we call it “text.” But a computer doesn’t know English, Spanish, or any other language. To a computer, text is just a sequence of individual characters (letters, numbers, spaces, and punctuation) lined up one after another like beads on necklace. That is why programmers call it a String of characters.
When you type the text directly into your code surrounded by quote marks (" " or ' '), it is called a String Literal. The quotes act as the start and end of the necklace, telling the computer exactly where the text begins and ends.
Formatting Text: F-Strings
We learned how to glue strings and variables together using the + operator (String Concatenation). While concatenation works, it gets incredibly messy when you have a lot of variables. You have to constantly open and close quote marks, remember to add spaces, and cast numbers to strings:
# Using string concatenation
print("Hello " + name + ", you have " + str(hp) + " health.")Python has a much better way to do this called an F-String (short for Format String).
To make an f-string, you simply place the letter f right before the opening quote mark. Inside the string, anytime you want to insert a variable, you just wrap the variable name in curly braces {}.
name = "Arthur"
hp = 100
# Using f-string
print(f"Hello {name}, you have {hp} health.")Notice that we didn’t even need to use str(hp)! F-strings are smart enough to automatically convert integers and floats into text for you. This makes writing dialogue and menus in your software incredibly fast and easy to read.
4.2 String Methods
Because users type unpredictable things into input(), programmers rely heavily on String Methods to clean up and format text. Here are the most common ones:
.lower() and .upper() These methods force a string to become entirely lowercase or entirely uppercase.
shout = "HELLO THERE"
whisper = shout.lower()
print(whisper)
# Output: hello there
print(shout)
# Output: HELLO THEREIn the example above, .lower() is a method attached to the string "HELLO THERE". It returns a new string that is all lowercase. The original string is unchanged.
.title() This method automatically capitalizes the first letter of every word. It is perfect for formatting names!
name = "arthur pendragon"
formatted_name = name.title()
print(formatted_name)
# Output: Arthur Pendragon.strip() This method scrubs away any invisible spaces at the very beginning or very end of a string. If a user accidentally hits the spacebar before typing their name, .strip() fixes it.
messy_input = " some words "
clean_input = messy_input.strip()
print(clean_input)
# Output: "some words"Chaining Methods
Because string methods spit out a new string, you can actually chain them together in a single line of code!
# Strips the spaces, then forces it to lowercase!
answer = " YES ".strip().lower()
print(answer)
# Output: yes4.3 Booleans: Truth and Logic
We know about Strings, Integers, and Floats. It is time to officially master the fourth major data type: the Boolean.
A Boolean (or bool for short) can only hold one of two values: True or False.
In Python, Booleans must always start with a capital letter, and they do not use quote marks.
game_is_running = True
is_poisoned = FalseBooleans are the foundation of computer logic. Every decision a computer ever makes boils down to a single True or False evaluation.
Comparison Operators
How do we generate Booleans? We ask the computer questions using Comparison Operators.
Just like math operators (+, -) evaluate down to a single number, comparison operators evaluate down to a single Boolean (True or False).
| Operator | Meaning | Example | Evaluates To |
|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 10 != 5 |
True |
< |
Less than | 3 < 2 |
False |
> |
Greater than | 10 > 5 |
True |
<= |
Less than or equal | 5 <= 5 |
True |
>= |
Greater than or equal | 2 >= 8 |
False |
Let’s test these in the IDLE Interactive Shell:
>>> 10 > 5
True
>>> 10 < 5
False
>>> 100 >= 100
TrueYou can even compare strings! The computer checks if the text matches exactly, character for character.
>>> "horse" == "horse"
True
>>> "Horse" == "horse"
FalseNotice that the second one is False! Python is case-sensitive, which means a capital H is a completely different character than a lowercase h to the computer. This is why we use .lower() to clean up player inputs!
A Common Mistake
Look closely at the “Equal to” operator in the table above. It is two equal signs (==).
Earlier, we learned that a single equal sign (=) is the Assignment Operator. It forces a value into a variable box.
score = 10means “Take the number 10 and put it into the score variable.”score == 10means “Computer, I am asking you a question: is the number inside the score box equal to 10?”
If you mix these up, your code will crash.
In the next chapter, we are going to use these Comparison Operators and Booleans to allow our program to make its own decisions!
4.4 Logical Operators: And, Or, Not
Sometimes, a single question isn’t enough. What if we need to check multiple conditions at the same time? Python gives us three Logical Operators to combine multiple Boolean expressions together: and, or, and not.
The ‘and’ Operator: Both sides must be True.
>>> (5 > 2) and (10 == 10)
True
>>> (5 > 2) and (10 == 99)
FalseThe ‘or’ Operator: Only one side needs to be True.
>>> (100 > 50) or (5 == 1)
True
>>> (5 > 10) or (5 == 1)
FalseThe ‘not’ Operator: This simply reverses whatever Boolean is next to it.
>>> not True
False
>>> not (5 == 5)
FalseYou can use parenthesis to make more complicated expressions:
>>> time_left = 45
>>> (time_left < 50) and (time_left > 10)
True
>>> hot = True
>>> raining = False
>>> (not hot) and raining
False
>>> not (hot and raining)
TrueIn the next chapter, we are going to use these Booleans to allow our program to make its own decisions!
4.5 The Project: Better Mad Libs
We are going to improve our Mad Libs program. It will ask the user for text, clean up their messy typing using String Methods, and use Type Casting and Advanced Math to calculate a ridiculous number to include in the story.
Most importantly, we are going to use F-Strings to print the story. Notice how much cleaner the print statements are compared to our old string concatenation! We will also add a final Boolean evaluation at the end to check if the player’s damage was an “Overkill”.
Type this code into a new file, save it as better_madlibs.py, and run it. Try typing your inputs with crazy capitalization and extra spaces to see how the code cleans it up!
# Use string multiplication to draw a cool border!
print("*" * 40)
print("STORY TIME")
print("*" * 40)
# Get string inputs and clean them up using chained methods
name = input("\nEnter a name: ").strip().title()
place = input("Enter a place: ").strip().title()
animal = input("Enter an animal: ").strip().lower()
adjective1 = input("Enter an adjective: ").strip().lower()
adjective2 = input("Enter another adjective: ").strip().lower()
adjective3 = input("Enter another adjective: ").strip().lower()
adjective4 = input("Enter another adjective: ").strip().lower()
noun = input("Enter a noun: ").strip().lower()
ing_verb = input("Enter a verb ending with 'ing': ").strip().lower()
# Get an integer input and cast it
number_text = input("Enter a number between 1 and 10: ")
number = int(number_text)
# Let's calculate a ridiculous number using exponents and modulo
calculated_stat = (number ** 3) + (number % 3)
# Evaluate a Boolean: Was this attack overkill?
is_overkill = calculated_stat > 150
# Print the final story using F-Strings
print("\n" + "~" * 40)
print("HERE IS YOUR STORY:")
print("~" * 40)
print(f"The {adjective1} gamer {name} logged into the virtual world of {place}")
print(f"to fight the ultimate boss: a giant, {adjective2} {animal}. Armed with")
print(f"nothing but a legendary weapon called the '{adjective3} {noun}', they")
print(f"prepared by {ing_verb} onto the battlefield. The boss dealt {number} points of")
print(f"damage right away. However, {name} unleashed their ultimate ability,")
print(f"dealing exactly {calculated_stat} points of {adjective4} damage to instantly win the match.")
print("\n" + "=" * 40)
print(f"OVERKILL ACHIEVED: {is_overkill}")
print("=" * 40)When you run it, it should look something like this:
****************************************
STORY TIME
****************************************
Enter a name: Bob
Enter a place: Ohio
Enter an animal: emu
Enter an adjective: slimy
Enter another adjective: twisty
Enter another adjective: fuzzy
Enter another adjective: cheap
Enter a noun: sandwich
Enter a verb ending with 'ing': burping
Enter a number between 1 and 10: 7
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HERE IS YOUR STORY:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The slimy gamer Bob logged into the virtual world of Ohio
to fight the ultimate boss: a giant, twisty emu. Armed with
nothing but a legendary weapon called the 'fuzzy sandwich', they
prepared by burping onto the battlefield. The boss dealt 7 points of
damage right away. However, Bob unleashed their ultimate ability,
dealing exactly 344 points of cheap damage to instantly win the match.
========================================
OVERKILL ACHIEVED: True
========================================