Previous Lesson: Lesson 4. Printing Strings and Variables in Python
In this lesson, we’ll discuss the two different ways of having variables inside strings using formatting and what happens when we use both.
After learning what strings and variables are in the previous lesson, we’ll now talk about something that we can do with strings. Additionally, we’ll do something awesome with variables. For now, let’s make a new file with the name ex3.py. After creating a new file, let’s have some variables and assign a value to each one of these:
Don’t forget to save this code (this will be the last time that I’ll tell you to save your code using Ctrl + S or Command + S). Do you still remember how to activate our Terminal? (Hit Command + Ctrl + `) Now, let’s run this on our Terminal. Enter python3 ex3.py:
ENTER:
Good. Our code worked!
Formatting #1: The “f “
Now, add this on Line 5:
Press UP ARROW. Then press ENTER:
What? How did that happen? We just had variables inside strings. Don’t worry. We’ll break it down. On our code, you may notice that we put an f before our string. The f just means format. Now, we had put the variables between some curly braces ({}). This is one way to put the value of a variable inside our strings.
Remember: If there was an error and you didn’t have the same results like mine, that’s okay. Everyone makes mistakes, even the most experienced programmers. Double check!
Try this: Remove the f before the string and the curly braces. Leave name and age out. See what happens. I’m not going to show it to you. You do it on your own and find out why we need these curly braces and f here.
Formatting #2: The “.format( )”
Earlier, I’ve said that having that f and curly braces is just a way. What I’m about to show you is another way to have the same output. Let’s do it! Remove Line 5. Next, type these in:
This time, we’ve removed the variables name and age from the string. But note that we’e left the curly braces ({}). However, we added something new to our code–the .format(). And we’ve placed the variables inside the parentheses after it. Let’s try running this:
Tada! Did it work? Yes, it did! The output was the same because it was suppose to be that way. But how about we change the values of our variables? This time, type in whatever you’d want:
Then run it:
Nice.
Using both formatting
Are excited to try this one out? Then let’s do it! I’ve typed my name back. In your case, type in your name. Let’s type both the first Line 5 with the f and the one with the .format():
Let’s see what this will look like:
Cool! After learning all this, I wanna ask you something: “Did you get all this?” If you don’t, then that’s good because you’ve got help–you’ve got us. So if you have a question, type it down on the Comments section.
In the meantime, keep on experimenting and trying things that crosses your mind with this; make more errors and learn from them; get familiar and have fun! See you on the next lesson!