Python for Humans · Draft v · · Draft position: chapter 1
Let's Write Some Python
- You'll build
- Your first conversation with Python, and your first error on purpose.
ready = input("Ready for Chapter 1? (yes/no) ") if ready == "yes": print("Let's go!") else: print("No rush. We'll be here when you're ready.")
Welcome to your first Python lesson! In the introduction, you ran a single line of Python code that printed "Hello, World!" to the screen. Not bad for a start.
Now let's take things a little further. By the end of this chapter, you'll have built a program that can have a conversation with you, create silly stories, and even remember things you tell it.
Don't worry about memorizing everything. The best way to learn programming is to experiment, make mistakes, and see what happens. You can't break anything here, so have fun with it!
Make Python Talk
Let's start with something familiar. Here's how to display a message in Python:
print("Hello, World!")
Go ahead and click Run to see the result.
The print() command tells Python to display something on the screen. In this case, it's the text Hello, World!.
Notice a few things about this line of code:
print is the name of a built-in Python function, which is a reusable set of instructions.
The parentheses () contain the information we want to display.
The quotation marks "" tell Python that Hello, World! is text rather than Python code.
In programming, a piece of text is called a string. You'll encounter strings all the time, whether you're working with names, messages, or entire paragraphs.
Let's try something more interesting:
print("Hello! I'm a very small robot.") print("I have three things to tell you.") print("One: I like Python.") print("Two: I like pizza.") print("Three: I am not actually a robot.")
Click Run and notice how each message appears on a separate line.
Python executes these instructions in order, starting at the top and moving down. When it reaches a print() function, it displays the text and moves on to the next instruction.
That's programming in its simplest form: giving a computer a sequence of instructions to follow.
Try it yourself: Change the messages to say whatever you like. Add another print() line. What happens if you remove the quotation marks around one of the messages?
If you get an error, don't worry! Python is telling you that something about your instructions doesn't make sense. Errors are a normal part of programming, and learning to understand them is an important skill.
Have a Conversation
So far, our programs can talk to us, but wouldn't it be more interesting if we could talk back?
Python has another built-in function called input() that lets us ask the user a question and wait for a response.
Try running this code:
name = input("What's your name?") print("Nice to meet you,", name)
When you run the program, Python asks for your name. Type it in and submit your answer.
You should see a personalized greeting!
How does this work?
Let's look at the first line:
name = input("What's your name?")
The input() function displays the question and waits for you to type an answer. But instead of just displaying your answer, we want to save it so we can use it later.
That's what name does.
In Python, a variable is a name that refers to a value. You can think of it as a label attached to a piece of information that your program wants to remember.
The equals sign = assigns a value to a variable. In this case, we're telling Python to take whatever the user types and store it under the name name.
Then, on the next line:
name = "Ada" print("Nice to meet you,", name)
Python displays our message followed by the value stored in name. The comma tells print() to display both pieces of information, separated by a space.
Notice that name doesn't have quotation marks around it. That's because we want Python to use the value of the variable, rather than display the literal word "name".
If we had written "name" instead, Python would have displayed exactly that word!
Give Your Robot a Personality
Now let's expand our program to ask more questions.
print("Hello! I'm a very small robot.") name = input("What's your name?") print("Nice to meet you,", name) food = input("What's your favorite food?") print("Thanks for telling me!") print("Your name is", name) print("Your favorite food is", food)
Try running it a few times with different answers.
Notice something interesting: Python remembers your name even after asking about your favorite food.
That's because we've stored two separate pieces of information in two variables: name and food.
You can create as many variables as you need, and you get to choose their names. It's a good idea to make those names descriptive so you can remember what they're used for.
For example, favorite_food is a perfectly valid variable name in Python. We use underscores to separate words because Python variable names can't contain spaces.
Try it yourself: Add a third question to your robot. Maybe ask for someone's favorite color, animal, or place to visit. Save the answer in a new variable and display it using print().
Congratulations! You've just created a program that can have a simple conversation with someone.
Build a Mad Lib
Now that we know how to ask questions and remember the answers, let's build something fun.
Have you ever played Mad Libs? It's a word game where you provide a few words without knowing how they'll be used in a story. The results are often ridiculous.
We can build our own version with Python.
Let's start by asking for three pieces of information:
person = input("Name a famous person: ") animal = input("Name an animal: ") place = input("Name a place: ")
So far, this is just like our previous program. We're asking questions and storing the answers in variables.
But now we'll use those answers to create a story.
person = input("Name a famous person: ") animal = input("Name an animal: ") place = input("Name a place: ") print(f"One day, {person} met a talking {animal} in {place}.") print(f"The {animal} announced that {place} was in terrible danger.") print(f"Luckily, {person} knew exactly what to do: order pizza.")
Run the code and enter your answers.
You might end up with something like this:
One day, Taylor Swift met a talking penguin in Paris. The penguin announced that Paris was in terrible danger. Luckily, Taylor Swift knew exactly what to do: order pizza.
Your results will depend on what you typed!
Introducing f-Strings
There's one new piece of syntax in our program. Look at this line:
person = "Taylor Swift" animal = "penguin" place = "Paris" print(f"One day, {person} met a talking {animal} in {place}.")
Notice the f before the opening quotation mark and the curly braces {} around our variables.
This is called an f-string, short for formatted string. It's a convenient way to combine regular text with values from variables.
The f tells Python that it should look for expressions inside curly braces and replace them with their values.
For example, if animal refers to the string "penguin", then {animal} becomes penguin when the program runs.
F-strings are incredibly useful, and you'll see them throughout this course.
Make It Your Own
Now it's your turn to get creative.
Try making the story longer by adding another line of dialogue or an unexpected plot twist.
Or add another question:
food = input("Name a food: ")
Then work that answer into the story using {food}.
You can turn this into a mystery, an adventure, or a ridiculous comedy. There are no wrong answers.
And the best part? Once you've written the program, you can run it as many times as you want to generate entirely different stories.
That's the power of reusable instructions!
Give Your Program a Memory
Our programs can now ask questions, remember answers, and use those answers to create stories.
But what happens when we want to change something the program remembers?
Let's find out.
print("I'm a robot with a very small memory.") name = input("What's your name? ") food = input("What's your favorite food? ") print(f"Got it! {name} likes {food}.") food = input("Actually, what food should I remember instead? ") print(f"Updated! {name} now likes {food}.")
Try running this program.
First, it asks for your name and favorite food. Then it asks you to change your favorite food.
Notice that the program still remembers your name, but it now uses the new food instead of the original one.
How does that work?
Take another look at these two lines:
food = input("What's your favorite food? ") food = input("Actually, what food should I remember instead? ")
Both lines assign a value to the same variable, food.
The first assignment gives food its initial value. The second assignment replaces that value with whatever you type next.
Variables are called variables because the values they refer to can vary, or change, while a program is running.
This might seem simple, but it's one of the most important ideas in programming.
What Is State?
At any given moment, a program has information that it is working with. In our robot example, that includes the values stored in name and food.
This information is part of the program's state.
When we change the value of food, we're changing the state of the program.
Think about a video game. Your character might have 100 health points at the start, lose 20 points when attacked, and gain 10 points after finding a health potion. The game keeps track of these changing values as you play.
Or consider an online shopping cart. As you add and remove items, the contents of the cart change. That's another example of state.
Our tiny robot uses the same basic idea, just on a much smaller scale.
There's one important limitation, though: our robot only remembers things while the program is running.
If you run the program again, it starts fresh and asks the same questions all over again.
Later in this course, we'll learn how programs can save information to files or databases so they can remember things even after they've stopped running.
For now, variables give us everything we need.
Your Turn: Build a Personal Assistant
Let's put everything together with one final challenge.
Create a program that acts like a personal assistant. It should:
Introduce itself with print().
Ask for your name using input().
Ask at least two more questions about you.
Remember your answers using variables.
Display a personalized summary using f-strings.
Ask you to update one of your answers and display the new information.
For example, your assistant might ask for your name, favorite hobby, and dream vacation destination.
After answering the questions, it could display something like:
Hello, Alex! Your favorite hobby is playing tennis. Your dream vacation is to visit Japan. Thanks for chatting with me!
Then it could ask whether you'd like to change your destination and display an updated summary.
Try building this without copying the earlier examples exactly. Look back at them whenever you need help, and don't be afraid to experiment.
Programming is a creative activity, and there's rarely only one way to solve a problem.
What You've Learned
You've written several Python programs, and along the way you've learned some of the most important building blocks of programming:
print() displays information on the screen.
input() asks the user for information and waits for a response.
Strings represent text in Python.
Variables let us give names to values so we can use them later.
F-strings make it easy to combine text and variables.
State describes information a program keeps track of as it runs.
More importantly, you've learned that programming isn't just about writing mysterious commands. It's about taking small pieces of logic and combining them to create something useful or interesting.
All of our programs so far have followed instructions from top to bottom. But what if we wanted our robot to make decisions? What if it could respond differently depending on what you typed?
That's what we'll explore next.