Challenges
Mad Libs in code
If you've gotten a programming environment set up from our last post, you're ready to write some actual code! For today, we are going to focus on the most basic concept in computer science: input and output. The program receives inputs, acts on them, and then returns an output. Absolutely every piece of code you write will follow this format (peep the banner image at the top of this post!).
Cooking is a good analogy. When you make lunch, you begin with ingredients (the input), rearrange them (algorithms), and finally produce a tasty meal (the output). Take a calculator for example. What are the inputs? What are the algorithms? What are the outputs?
We can apply this structure to the simplest Python program in the book: Hello, World:
print("Hello, World!")
Yep, that's it. If your editor is working, that line should print the phrase "Hello, World!" to the screen (don't forget the quotation marks!). It isn't much, but there's a lot going on here. We give a phrase (the input) to a print statement (the algorithms) and then that phrase is printed on the screen (the outputs). We don't have to print directly either, we can also store the phrase we want to print in a variable and then print the variable.
phrase = "Hello, World!"
print(phrase)
Nothing should be different about the output of these two programs. However, by storing the phrase we want in a variable, we can do some extra things with it.
phrase = "Hello, World!"
print(phrase)
print(phrase.lower())
print(phrase.replace("World", "Universe"))
Don't worry about what the last two print statements are doing, we will get to that in the future. The important thing to note here is that by placing our message (the input) in a variable, we can make some changes to it (algorithms) to put several different messages (the outputs) on the screen. Variables give us ways to modify the inputs, make intermediate values, and keep our code organized. It'd be pretty painful if you had to type out every message you wanted printed!
Variables have some rules about what their names can be. Python reserves some variable names for its own functions (like print, sum, etc.), so it's a good idea to not use these for your own variable names. Also, variables names cannot start with a number, contain spaces, or contain special characters. If you don't follow these rules, Python will give you a syntax error indicating that it doesn't understand what you typed
# Valid variable names
data
player2
left_channel
camelCase
# Invalid variable names
2sided
right channel
up+down
inside.out
Input
So we can make our code output things, that's pretty cool. But it'd be nice if your programs could take input from the user as well. That way, we don't need to modify the code itself every time we want a different result. Fortunately, Python makes this easy. Along with the print function, we have an input function.
phrase = input()
print(phrase)
If you run that code, you'll notice that nothing happens. Nothing is wrong! Python is just waiting for you to type something into the console. Press enter, and whatever you typed will get printed to the screen. We can make things a little clearer by giving input a message to display:
phrase = input("Enter a message => ")
print(phrase)
Note that the text you give to input() does not get stored in the phrase. All that string does is show a message to the console so that it doesn't look like your program is stuck. Anyway, now we have a program that depends on user input to give an output. But, it doesn't really do much. Before we can learn more about modifying input, we need a brief discussion about what kinds of data Python understands.
Data Types
Up until this point, we have only been working with strings. Strings are used in Python to represent text. They are surrounded on both sides by quotes. They can contain spaces, special characters, etc. Python also has several other data types for you to play with:
my_int = 5 # Integers are whole numbers
my_float = 6.67 # Floats have numbers after the decimal
my_bool = True # Booleans can either be True or False, no other values are possible
my_str = ":)" # Strings contain characters and are surrounded by quotes.
Also, when a line starts with #, it's a comment. Python will simply ignore it. But, it's helpful for you to remind yourself and others what your code is doing. As we move through these posts, we will explore each of these data types in detail. For now, you just need to know that they exist.
Working with Strings
For the rest of this post we will look at operations we can do on strings. The most basic one is concatenation. You do this with the + sign and the result is to simply glue two strings together.
s1 = "The real "
s2 = "Slim Shady"
s3 = s1 + s2
print(s3)
Notice that you have to add a space between the two strings; Python won't put it there for you. Strings can also generate variations of themselves based off of case, since it's pretty painful to make things upper and lowercase manually.
small = s2.lower()
large = s2.upper()
print(small)
print(large)
You can replace sections of strings with another string using .replace().
sentence = "The quick brown fox jumped over the lazy dog"
print(sentence.replace(" ", "_")) # Replace spaces with underscores
Python has many string functions built in. For now, you only really need to know about concatenation and maybe upper/lowercase if you're feeling ambitious. If you're curious, you can see everything Python's strings have to offer on the official documentation. Before we get to the project, there's a few extra things to know about printing.
Fancy Output
When printing large amounts of text to the screen, it's helpful to keep things tidy so your code doesn't get overwhelming. To print several strings on one line, they can be separated by comments in the print statement. Meaningful variables names will remind you what different parts of the print statement correspond to.
city = "Seattle"
day = "Monday"
weather = "raining"
print("In", city, "on", day, "it was", weather)
That works pretty well, but it can get tedious to type all the commas and quotes so that Python will be happy with syntax. A possibly easier way is to use .format() with a string. The same print statement as above can be achieved like so:
print("In {} on {} it was {}.".format(city, day, weather))
The curly braces (above your quote key) make blanks where strings are inserted. Each string you want to insert goes inside of .format(), separated by commas, in the order you want them to appear. The .format() function is actually generating a string itself, so this method is also possible.
formatted = "In {} on {} it was {}.".format(city, day, weather)
print(formatted)
There's no best way to do printing like this, it's all about what is most clear and useful to you. Remember that you are writing code for yourself, future you, and other people. Making sure that future you and others understand your code is just as important as getting it to work!
Project: Mad Libs!
From here on out, these posts will include projects like this one for you to practice using the skills you've learned. If you're not familiar, Mad Libs are a party game where words you supply are written into a story. Since you don't know what the story is while thinking up words, usually it turns out pretty nonsensical. Before we get to coding, let's think about applying the input-algorithms-output format to Mad Libs. Words you think of (the inputs) are written into a story (algorithms) to generate a silly version of the story (output). This IAO format can tell us about how we would structure a program to make a Mad Libs story. Like how IAO has three phases, so does our program:
- Get words from the user with input()
- Insert them into the story in the right places.
- Output the final, silly story to the user.
For part 1, we know how to use input() to get words from the user. For part 2, we know how to use string concatenation or .format() to produce nicely formatted strings. And, for part 3, we know how to use print statements to show output to the user. There's plenty of Mad Libs templates for you to use. Or, you can make your own!
If you're having trouble getting started, here's some starter code. Every function you need to use is there, keep adding to the story until you get a fun final product.
If you'd like, send us what you come up with! Our email is at the bottom of the homepage. Happy coding!