In this chapter, you’ll see how you can use Python to
Visit a website, start up a game system, or open a mobile application, and it will probably ask you to enter a name and email address and create a password. These are all computer programs, and once you’re logged in, they may display special messages at the top of the screen saying things like “Welcome, Aaron” (or whatever your name is). Some programs are very sophisticated, remembering the games you’ve played, the badges you’ve earned, the balance in your account, or the products you’ve viewed.
iTunes, Netflix, Facebook, and Gmail are all sites that use computer programs that ask you for information, save information, and interact with you based on that information. In this chapter, you’ll see how to do this with Python by creating a ridiculously fun word game called Silly Sentence Generator 3000.
In Silly Sentence Generator 3000, the game player (that’ll be you) is asked to enter words such as nouns, verbs, adjectives, and so on. You’ll store the words as variables and then use them to create ridiculous, nonsensical sentences.[1] Figure 3.1 shows an example of what the finished program looks like.
This is similar to the game Mad Libs, if you’ve ever played it.
Think about the program like a machine that takes a set of inputs and then creates an output. You’re going to put together the machine by creating the instructions that drive it. Conceptually, this “machine” might look something like figure 3.2. Change the words you put in, and you’ll get a completely different result. That’s part of what makes games so much fun!
Let’s see how to create this game. Once you create it, you can change it and add to it however you like.
If you open a game, one of the first things you see is a main menu or title screen. Let’s use what you know about displaying text on the screen to make your program display a title for your game. You start by opening IDLE and creating a new program. Open IDLE for Python 3 by clicking the Menu button and selecting Programming > Python 3 on your Raspberry Pi’s desktop (see figure 3.3).
Give your Raspberry Pi a few seconds to open IDLE. After IDLE opens, you’ll see the Python Shell (see figure 3.4).
Press Ctrl-N or choose File > New Window to open the IDLE text editor. You’ll see a blank window, ready for you to start typing in your program (see figure 3.5).
Using the print function you learned about in chapter 2, let’s make a title screen:
print("*" * 48) print("* Welcome to the Silly Sentence Generator 3000 *") print("*" * 48)
Excellent. Feel free to elaborate on the welcome message and the artwork with different characters. Before you go much further, you should save the program.
Save the program by selecting File > Save or pressing Ctrl-S. This will open a window asking where you want to save the program and what to name it. Let’s name it SillySentence (see figure 3.6). By default, IDLE saves your file to your /home/pi folder. Let’s use that folder.
Click Save, and the file will be saved as SillySentence.py (the .py file extension is automatically appended by IDLE). After you save the file, the title at the top of the text editor window will show the filename and file location, as you can see in figure 3.7.
Guess the output. What do you think you’ll get when you run the program?
Let’s try it. Click Run > Run Module (or press the keyboard shortcut F5). Python will read each line of your program and execute the commands. The commands print a line of * characters, the welcome message, and another line of * characters to the screen (see figure 3.8).
Excellent! Now you have a proper welcome message for your game. The next thing you need to do is gather some input from your game player. Some games use button presses, but you’ll use the keyboard for this game.
Another way to run a program is from the Raspbian command line. You can access the command line using the Terminal application found under Menu-->Accessories. A window will open with this prompt:
pi@raspberrypi ~ $
To run the Silly Sentence program at the command line, enter
pi@raspberrypi ~ $ python3 SillySentence.py
The next figure shows this command and the result. Notice that you get the same output at the command line.
The command line is another option for running Python programs. In part 3 of this book, you’ll see that some programs require you to run them from the command line because you must run them as the superuser on your Raspberry Pi.
Imagine a comic book without words. You’d have a hard time understanding what was happening from just the pictures. Maybe you could figure it out if you studied the comic long enough, but words are important for understanding a story. Lines of code can be like a comic book without words: you know something is happening, but you might not be able to tell what without guessing.
That’s why programmers invented the idea of adding comments. Comments are notes in the code that explain what’s happening. They’re as much for you as for other people who may read your code. You can use comments to explain why you wrote the program and how parts of the program work.
You add a comment by starting the line with a hashtag (#) and a space and then typing in your comment text. Let’s add comments to the beginning of Silly Sentence Generator 3000 to explain the program’s title, its purpose, and who wrote it.
Comments are helpful to the humans reading the code. But Python ignores comments when it runs your program. You can check this by saving your program and running it again; you’ll see that you get the same result as before.
Python has a hidden surprise regarding Python style. In computer programs, these surprises are sometimes called Easter eggs. You can find the egg by typing import this in the Python Shell and pressing Enter. A beautiful poem called “The Zen of Python” will appear on your screen.
The poem emphasizes the philosophy of Python. Some of it talks about advanced topics, but many lines discuss a way of coding that is meant for anyone who uses Python. The seventh line captures a great idea in Python: “Readability counts.” It’s better to write programs using simple instructions that are easy to read than to try to mash together steps in complicated, long lines of code. Try taking some deep meditational Python breaths before getting back to your project.
Python’s creator, Guido van Rossum, said that code is read more often than it’s written.[2] Readability is an extremely important part of programming and is a guiding principle in the style of Python programs. Comments are an important way to keep your code easy to read and understand.
Check out the resource PEP 8—the Style Guide for Python, written by Python’s creators: http://legacy.python.org/dev/peps/pep-0008. A wonderful section called “A Foolish Consistency Is the Hobgoblin of Little Minds” talks about the importance of readable code.
Comments are your new friend, and they will make your code easy to read. You’ll keep using them to add notes to your code as you collect information from your game player (or user) and create a silly sentence.
To gather input from users, you can use the input function. Let’s add a line of code in your program that will ask the user for their information and store that information in a variable.
When you use the input function, it displays a prompt and awaits the user’s reply. After the user enters something and presses Enter, the information is stored in the variable on the left side of the equals sign.
In the IDLE editor, input shows up in purple highlighting, indicating that it’s the name of a function in Python. Let’s look closely at the input function to see how it works (see figure 3.9).
On the right side of the equals sign, the input function is called, and you open a set of parentheses. You can give the input function a string that acts as the prompt. This is the message that is displayed on the screen and that says to the user, “Hey you, please type something in”—only more nicely! Make sure your string starts and ends with quotation marks ("").
Run the program by pressing F5 or selecting Run > Run Module. The program displays the welcome message and then an input prompt with a blinking cursor. Python is waiting for your input: it needs you to type something in and press Enter.
On the left side of the equals sign is the name of a variable in which the information will be stored. When you type something in and press Enter, the value of what you typed is stored in the variable player_name as a string.
The input function was previously raw_input in Python 2.X.
As in other apps and websites, you want the user to feel welcome, so let’s use their name and give them a proper greeting. A nice message to display on the screen might be
"Hello, Ryan! Let's make a silly sentence!"
To create a personal feel, you’ll create just such a message that joins the user’s name with some words welcoming them. You use the plus (+) symbol to join strings:
message = "Hello, " + player_name + "! Let's make a silly sentence!"
If player_name equals “Melissa”, the message is equal to
"Hello, Melissa! Let's make a silly sentence!"
Add this to your program, and display the message to the screen using print.
The program has the user input their name, which is stored in the variable player_name. On the next line, a message is made by joining strings. The message is displayed on the screen to create a personalized start for the game.
To make life easier, Python includes some built-in tools for working with strings. These tools are similar to the functions you saw earlier, but they’re called methods. Here is an example of a method that capitalizes the first letter of a string:
"jOHn".capitalize()
The capitalize method converts “jOHn” to “John”.
Python has a whole set of built-in methods. One method for strings is the lower method, which converts a string to all lowercase:
"RABBIT".lower()
This makes “RABBIT” turn into “rabbit”.
Another method, upper, makes all the letters uppercase:
"king Arthur".upper()
The upper method is great for shouting things. It makes “king Arthur” into “KING ARTHUR”.
These methods can save you time[a] and make it easier for you to get things done.
You can learn more about the available string methods in the online Python documentation: http://mng.bz/9z49.
Methods vs. functions
Methods are a type of function, but they use dot notation. This means you put a period (.) after the item and then the name of the method. If your item was “John Cleese” and the method you wanted to use was lower, you’d write
"John Cleese".lower()
Parentheses go after the method name. You put in the parentheses any inputs required by the method. You can check the Python documentation online to see what is required.
Some methods don’t require any inputs, like the string methods capitalize, upper, and lower. But some methods, like count, require inputs. Imagine that you had a set of test answers with T for true and F for false, and you wanted to count the number of true answers. You could use count:
>>> TestAnswers = "TTTFFFTTTFTFFFFTTTFFTT" >>> TestAnswers.count("T") 12
There were 12 true answers on the test.
Let’s go further and add more inputs.
You have a wonderful start to your game. Now you need to gather multiple inputs from the player. Let’s start by asking the player for a noun—the name of a famous person:
famous_person = input("Enter the name of a famous person: ")
Next, you should get a few more words:
adjective1 = input("Enter an adjective: ") adjective2 = input("Enter another adjective: ") verb = input("Enter a verb ending in –ING: ")
With these multiple inputs, your code should now look like the following listing.
You use the input function multiple times to collect a set of words from the user. Each word is stored in a variable on the left side of the equals sign. Try to use names for variables that make sense; it’ll be easier to remember what you stored in them later.
Now let’s create the sentence for your Silly Sentence Generator 3000 by joining the words using +:
silly_sentence = ("The " + adjective1 + " " + player_name + " is " + verb + " the " + adjective2 + " " + famous_person)
Let’s take a closer look at this line of code in figure 3.10 to see what’s happening.
On the right side of the equals sign, the parentheses enclose the strings that are being joined to create a sentence. They’re joined (or concatenated) using the + operator. Because the line is so long, you can use a set of parentheses to break it over two lines. Python recommends limiting all lines to no longer than 79 characters so the code can be easily read. Looking at the left side of the equals sign, you’ll see that the resulting string is stored in a variable named silly_sentence.
What’s especially awesome is that this code will create a different sentence each time a user enters different words. Because you used variables and the variables are storing the input from the user, it’s truly a Silly Sentence Generator!
When typing code, it’s easy to make mistakes, called bugs. Boo to bugs. To track them down and fix them, you debug your code. Yay for debugging. You may forget to close a set of quotation marks, you may leave out a parenthesis, or you may misspell a word. Let’s look at some common errors you might make and how to fix them.
In the last section, you used the + to join strings and variables that were storing strings. Look at this code, which has an error:
silly_sentence = ("The + adjective1 + " " + player_name + " is " + verb + " the " + adjective2 + " " + famous_person)
Do you see the problem? The first string ("The) is missing the closing quotation mark ("The "). If you were to run this program, Python would output an error (see figure 3.11). Add the closing quotation mark to the string that is missing it, and then save your program and run it again.
Another common error you might make is to misspell the name of a variable or use different capitalization. Here’s the same line of code, but this time there is a misspelled variable and one variable with incorrect capitalization. Can you spot them?
silly_sentence = ("The " + adjectve1 + " " + player_name + " is " + verb + " the " + adjective2 + " " + Famous_person)
The first one is adjectve1, which should be adjective1 (the i is missing). The second error is Famous_person, which should be famous_person (the F should be lowercase). The error you’ll see if you run this program is shown in figure 3.12.
The spelling and capitalization of a variable must always be the same. If you call a variable my_number and then later type my_nomber or My_number, Python will give you an error.
Correct the error by fixing the spelling of adjectve1 so it’s adjective1. After fixing it, you’ll still receive an error, but this time because of the capitalization of Famous_person (NameError: name 'Famous_person' is not defined). Change the capitalization of Famous_person to famous_person. Once you’ve made the corrections, save the program and run it again.
You’ve debugged your program. Superb job!
You’ve made your silly sentence, and you want Python to show it to the player. Use the print statement to print it out, but like your welcome message, let’s add some pizzazz to it!
print("*" * 48) print(silly_sentence) print("*" * 48)
Guess what it does? It prints a row of * characters (asterisks) across the screen 48 times. Then it displays the sentence and prints another row of * symbols 48 times. Try other characters or patterns of characters to see what looks good to you!
It looks pretty good, but you can do a bit better. Test your program by running it, and you’ll notice the number of symbols doesn’t match the length of the sentence. You’ve programmed it to display exactly 48 asterisks—no more, no less. Instead, let’s update those lines to repeat the symbol to match the length of the silly sentence. You’ll use another built-in Python function called len, which calculates the length of a string and returns a number telling you the number of characters:
print("*" * len(silly_sentence)) print(silly_sentence) print("*" * len(silly_sentence))
That’s better! Let’s look at the code all together (see figure 3.13).
You’ve completed your program. Let’s do some final testing to see what it can do! See figure 3.14 for an example of the game’s output.
Fantastic! Feel free to update the code to add more adjectives, verbs, or nouns. You’ve learned how to get input from a computer user and interact with them by displaying a message to the screen.
In this Fruit Picker Extra, you’ll explore another unique feature of the Pi: it has its own version of Minecraft. Thanks to a collaboration between Mojang, the makers of Minecraft, and the Raspberry Pi Foundation, a free, slimmed-down version of Minecraft is available on the Raspberry Pi. Since September 2014, this version, called Minecraft Pi, is automatically installed with the Raspbian operating system.
Minecraft is a game that takes place in a 3D virtual world made of blocks. At the most basic level, you run around mining (digging blocks by hitting them) and crafting things (combining items in the game to make new items). You can also build things in this virtual world using different types of blocks.
Look for a Minecraft Pi icon under Menu > Games (see figure 3.15). If you got your Pi before September 2014, see the chapter 6 sidebar “Updating your Pi” to learn how to update Raspbian.
Click the Minecraft Pi icon to open the game. A Minecraft window will open (see figure 3.16). It’s a little quirky—you’ll see a black window behind the Minecraft window—but this is normal.
Click Start Game to begin to play. Next, click Create New to create a new world. After it’s done loading, you’ll find yourself in a blocky world (see figure 3.17). Each world is different, so you may see trees, water, dirt, or any number of environments.
In Minecraft, you’re a player who can walk around using the following controls:
In addition to the basics, here are some other moves you may need:
Once you get the hang of moving around, use the mouse left click to dig or break blocks. Use the mouse right click to place a block or use the tool in your hand. When you’re ready to leave, press Escape to exit the game.
To exit Minecraft Pi, press Escape > Quit to Title, and then click the X in the corner to close the window.
Minecraft Pi has a fun inventory of materials and tools—even a sword! What’s even better is that there is a Python programming interface for Minecraft Pi. Head over to the Raspberry Pi Foundation website to learn more about how to use Python to interact with Minecraft Pi.
Explore the world, dig an underground base, or build a tree house. What will you do?
Try these challenges to see if you can use the input function and strings to create something fun and interactive.
In this challenge, try to use what you’ve learned about input (gathering text) and output (displaying text) to create a Knight’s Tale Generator. Here is a story template for you to use:
There was a brave knight, [player_name], who was sent on a quest to vanquish the [adjective] evildoer, [famous_person]. Riding on his/her trusty [animal], the brave [player_name] traveled to the faraway land of [vacation_place]. [player_name] battled valiantly against [famous_person]’s army using his [sharp_thing] until he defeated them. Emerging victorious, [player_name] exclaimed, “[exclamation]!!!” I claim the land of [vacation_place] in the name of Python.
The words in brackets are meant to be variables that you’ll create in your program; you’ll need to have the player input those words. Remember to use + to join the strings to create a unique knight’s tale, and then print the tale to the screen. Good luck!
A subliminal message is a hidden message that tries to get people to think of something you want them to think about. Often used in TV commercials, it’s a great technique to try with friends and parents to get something you want.[3] In this challenge, try to create a message that is hidden in a large display of characters. The message should be constructed by asking for the person’s name, the name of something they want, and a pattern of letters, numbers, and symbols. In your program, you should create a message that says, “You really want to buy [player_name] a [thing]”, and hide it within a pattern of characters. Figure 3.18 shows an example.
Use subliminal messaging at your own risk (send Ryan pizza!). If people know you’re trying to manipulate their minds, they may retaliate with subliminal messaging of their own.
In this example, the hidden message is, “You really want to buy Ryan a burrito.” Be sneaky, and see if you can find a way to create and hide a subliminal message!
In this chapter, you learned how to write interactive programs that get information from a person and provide entertaining responses:
favorite_color = input("What is your favorite color?")
# A comment tells you about the code # They help you read the code, # but they are ignored by Python
name = input("What is your name?") favorite_color = input("What is your favorite color?") message = ("Your name is: " + name + " and your "+ "favorite color is: " + favorite_color)
The game you created uses the same ideas to collect information from users and interact with them in the same way they see every day on websites, mobile apps, and games.
13.59.231.155