Python Programming: Variables
#
OverviewThis lesson introduces you to the concept of creating and assigning variables - numeric variables (including basic math functions / numerical operators) and string variables (including concatenation). There is a small section near the end on different ways to print these variables.
#
Lesson ObjectivesAfter this lesson, you will be able to...
- Create and re-assign numerical and string variables.
- Use numerical operators.
- Print complex variable structures.
#
Duration60 minutes
#
AgendaDuration | Activity |
---|---|
2 minutes | Overview |
3 minutes | Define “variable”. |
25 minutes | Use numerical and mathematical operators. |
20 minutes | Use string variables. |
5 minutes | Print complex variable structures. |
10 minutes | Q&A and transition. |
#
What's a Variable?Turn to the person next to you, and together come up with as many definitions for the word "variable" as you can.
Consider contexts such as mathematics, the sciences, weather, etc.
No cheating! Phones off and laptops closed. 3 MINUTES
Today, we are going to explore how variables are used in Python.
#
VariableVariables:
- Are boxes that can hold all kinds of information for you.
- Make it easier to store and re-use values.
- Are the most basic piece of code.
To use a variable, we simply announce that we want to use it (we declare it).
# I've eaten 3 cupcakescupcakes_ive_eaten = 3print(cupcakes_ive_eaten)# Prints 3
- Bring up a repl.it (you haven't seen an interpreter yet!) and run this. It's already written in here.
- Based on your knowledge from the prework, point out the print statement and comments.
- How about printing negatives and decimals?
Quick Checks:
- While variables can really be anything, we’ll keep it simple to start by looking at numerical variables.
- Let's go over the syntax!
- Here, we create a variable called
cupcakes_ive_eaten
and have it hold the number3
. This is also called assignment. If we print out the contents ofcupcakes_ive_eaten
, Python will tell us thatcupcakes_ive_eaten
currently holds 3. - When you create a variable, it's called declaring a variable. The syntax for declaring a variable is what you want the variable to be named, followed by an equal sign, and finally what you want the variable to hold. Notice the space before and after the equal sign!
- Also, note that in Python, the equal sign doesn't evaluate things the way it does in math. Instead, it assigns them values. Here, we're using the
=
to tell Python that thecupcakes_ive_eaten
label is going to hold the value3
. - See that underscore? We'll look at variable naming in a second!
#
Naming Conventions: Mistakes and SyntaxSome common naming mistakes:
- Not using meaningful names.
delicious = 3
doesn't mean anything -cupcakes_ive_eaten = 3
does! - Case sensitivity (
CUPCAKES_IVE_EATEN
andcupcakes_ive_eaten
are not the same!) - No spaces or punctuation ("cupcakes i've eaten" isn't allowed)
- This is invalid syntax
- Use snake_case:
lowercase_letters_with_underscores
(it's in the official Python style guide)
Quick Checks:
Bring up a replit - this one already has the code. As you go through, try each of those common naming mistakes and see it breaking.
If you make a typo in the variable name (even if it is a different capitalization), it will create a new variable!
You can name a variable anything you'd like, but you probably shouldn't. If I called my variable "delicious", would you have any idea that the number it held was the number of cupcakes I've eaten? Probably not. In Python, we try to name variables as closely as we can to what it actually is. Technically, variable names can be almost anything, so it's up to us to be organized and thoughtful when we pick them!
Any name is allowed - Python doesn't enforce helpfulness. Try to always have meaningful variable names so that later, you know what that variable holds!
Variables are case sensitive.
When you want to use a variable name consisting of several words, you will get an error if you have spaces between the words. Try creating a variable called
my number
and you'll get an error; specifically, one that says "Invalid Syntax.Syntax is the set of rules surrounding how a language looks. In the English language, we call syntax "grammar." For example, sentences always start with a capital letter and end with something such as a period, exclamation point, or question mark. Other languages have syntax, too, including programming languages like Python.
Here, Python is telling us that putting a space between two words in a variable name is invalid syntax. It's not proper grammar and it will not run.
#
Discussion: Changing ValuesWhat if, later, you eat more cupcakes? Now, this is wrong.
cupcakes_ive_eaten = 3
What do you think we need to do?
#
Discussion: Reassigning VariablesIn the example below, what do you think the output of the code is?
cupcakes_ive_eaten = 3print(cupcakes_ive_eaten)cupcakes_ive_eaten = 4print(cupcakes_ive_eaten)
Quick Checks:
Bring up a repl.it and see this. Here is one that has this code.
Make it clear that only the last value is saved!
We can always change what a variable is holding; it's just a container. Initially setting a variable to a value is known as assigning the variable. In our example above, we declared the
cupcakes_ive_eaten
variable and assigned it the value of3
.If we eat more cupcakes, we can reassign the variable to a different value - here, 4.
We can reassign our variable as many times as we want. However, only the most recent value of a variable will be retained. Once a variable is reassigned, its original value is lost forever. If you think of a box, reassigning a variable is like throwing away what's in the box and replacing it with something new.
#
Quick ReviewA variable is a box that holds a value.
It can be declared, called, and changed within your program.
When declaring variables, syntax and naming conventions matter!
Variables can be reassigned as often as you like, but only the most recent declaration counts.
UP NEXT: Math!
- Now it’s time for everyone’s favorite subject -- math!
#
Mathematical OperatorsMath works on numerical variables, too!
- The
+
,-
,*
(multiply), and/
(divide) operators work just like they do with regular math.
cupcakes_ive_eaten = 6 + 3print(cupcakes_ive_eaten)# Prints 9
cupcakes_ive_eaten = 6 - 3print(cupcakes_ive_eaten)# Prints 3
cupcakes_ive_eaten = 6 * 3print(cupcakes_ive_eaten)# Prints 18
cupcakes_ive_eaten = 6 / 3print(cupcakes_ive_eaten)# Prints 2.0
cupcakes_ive_eaten = 6 // 3print(cupcakes_ive_eaten)# Prints 2, the // operator is an integer division operator
Quick Checks:
- When we're dealing with variables that have numbers for values, the operators work just like they do with regular math.
- We can use pretty much any mathematical operator in Python to manipulate our variables and achieve our goals with our program. We’ve talked about addition, subtraction, multiplication and division so far.
- Note the syntax - the spaces around each character. Note that it works without the spaces, but it's poor practice and harder to read.
#
Even More Mathematical OperatorsBeyond the +
, -
, *
(multiply), and /
(divide) operators, we have modulus and exponents.
making_exponents = 10 ** 2print(making_exponents)# Prints 100
more_exponents = 10 ** 3print(more_exponents)# Prints 1,000
making_modulus = 10 % 3print(making_modulus)# Prints 1
more_modulus = 6 % 2print(more_modulus)# Prints 0
#
Math On The Same VariableYou can reassign a variable using that very same variable - or other variables!
cupcakes_ive_eaten = 3cupcakes_ive_eaten = cupcakes_ive_eaten + 1print(cupcakes_ive_eaten)# Prints 4.cupcakes_left_in_box = 6cupcakes_left_in_box = cupcakes_left_in_box - 1 print(cupcakes_ive_eaten)# Prints 5.cupcakes_left_in_box = cupcakes_left_in_box - cupcakes_ive_eaten print(cupcakes_ive_eaten)# Prints 1.
Quick Checks:
- You may have a scenario where you want to reassign a variable to itself. We do this so we don't have to create extra variables. In our cupcakes example, we don't want to have to use a whole new variable just to add a cupcake.
- Note that this works because the right side of the equals sign is evaluated first. Thus, the
1 + 3
in the second line is happening before the reassignment. The right side becomes 4, then that value is set to cupcakes_ive_eaten. - A great thing about variables is that, because they store a value, you can use them later - even to create new variables. For example, if we have a variable declared
cupcakes_in_a_box = 3
, and we know that there are 5 cupcakes in a box, we can multiply them to determine the number of cupcakes I will eat.
#
Partner Exercise: Mathematical OperatorsPair up and choose roles:
- Driver
- Navigator
Try to code the following:
# Make a variable to hold the number of guitars you own (3).
# Make a variable to hold the number of guitars Nikhil owns (1).
# You give 2 of your guitars to Nikhil, so subtract 2 from you and add 2 to Nikhil.
10 MINUTES
Quick Checks:
- Try this pair programming activity:
- Code can be found here.
- Let’s give it a shot! In a second, I’m going to ask you to pair up and program together in repl.it
- In pair programming, one person serves as the driver -- their hands are on the keyboard -- and one person serves as the navigator -- they provide guidance as the code is written.
- When you pair up, decide who will be the driver and who will be the navigator. Then, follow the directions in the comments.
- Raise your hand when you’ve managed to complete each step, and I’ll come around and provide feedback.
#
Reassignment ShorthandThis is okay:
my_num = 9my_num = my_num + 7# my_num is now 16
But this is better:
my_num = 9my_num += 7 # += is short for theSameVariable = theSameVariable + 7# my_num is now 16
This works with +=
, -=
, *=
, /=
- any math operations.
Quick Checks:
The shorthand is equivalent to writing out the reassignment in full.
The code on top is good, but it is actually such a common scenario that we want to reassign a variable that we've made a shortcut. For example, saying
my_num += 9
is exactly the same as sayingmy_num = my_num + 9
. It's just a shorter way to write it.Keep in mind that we'll always need an
=
somewhere in the line of code when we want to either assign or update the value of a variable.
#
Partner Exercise: Numerical ReassignmentGet with the same partner, but switch driver and navigator roles.
In the environment below, follow the prompts:
10 MINUTES
Quick Checks:
- Let’s give it a shot! In a second, I’m going to ask you to pair up and program together in repl.it
- Remember, in pair programming, one person serves as the driver -- their hands are on the keyboard -- and one person serves as the navigator -- they provide guidance as the code is written.
- Follow the directions in the comments.
- Raise your hand when you’ve managed to complete each step, and I’ll come around and provide feedback.
Repl.it Note: The code is all comments:
# Declare two variables `num1` and `num2` and assign them to any numbers you'd like.
# Set `num1` to the result of subtracting `num1` from the `num2`.
# Create a new variable `num3` that will help us tell if `num2` is even or odd.
# Using shorthand, add 5 to `num1`.
# Print out `num1`, `num2`, and `num3`
#
Important Aside: Even or Odd?Is 6
even or odd?
Is 7
even or odd?
How do you think a computer knows?
Modulus operator shows the remainder of a division problem.
Modding by 2
only gives a 0
or a 1
.
- 4 % 2:
4 % 2 = 0
. Even!
- 5 % 2:
5 % 2 = 1
. Odd!
Quick Checks:
- This is where modulus is helpful. The modulus operator shows the remainder of a division problem.
- For example, five divided by two equals two with a remainder of one. The modulus operator takes two numbers as inputs and returns what is left over from the division.
#
Quick Review II- A variable is a value that can be defined, declared, called and changed within your program.
my_number = 5
- Naming:
- Variable names are case sensitive.
- Use
snake_case
!
- Variables can be reassigned as often as you like, but only the most recent declaration counts.
- Python can do math using operators, such as
+
,-
,*
, and/
- You can shorthand the math assignments:
my_num += 7
- You can shorthand the math assignments:
#
Taking a BreatherThat was a lot of math!
When it comes down to it, computers operate with a simple, straightforward logic.
Let's switch gears. Up next: Strings!
- While we've covered what seems like a lot of math in this section, don't worry: You're not going to be doing calculus in this course. However, it's important that we review these concepts, because there will be many times when you'll solve a problem using basic principles. When it comes down to it, computers operate with a simple, straightforward logic.
- We’ve learned about numerical values and mathematical operators. Now, we’re going to transition to string variables.
#
Introducing StringsA character is:
- Anything on your keyboard , such as a letter or a number.
- "Apple" is five characters: a, p, p, l, e.
- Spaces count! (they're on the keyboard!)
A string is:
- A complete list of characters.
"Apple"
"Chocolate Cupcake"
- This entire sentence:
"Hello, you are 1 of a kind!"
Quick Checks:
"Because a variable is just a box, it can also hold strings. You tell Python that your variable will hold a string using quotation marks."
"Strings can be words, like apple. Strings are made of characters. A character is anything on your keyboard , such as a letter or a number. The string apple is 5 characters."
"A space counts as a character, too (it's on the keyboard). For example, "Marty McFly" is a string. So is this entire sentence:"
#
How Do I Create Strings in Python?You tell Python that your variable will hold a string using quotation marks.
box_contents = "cupcakes" # This is a stringprint(box_contents) # It's a normal variable - we can print it.best_snack = "Frosted Cupcakes" # This is a string.cupcakes_ive_eaten = 5 # No quotes - this is a number.cupcakes_ive_eaten_as_string = "5" # Because this is in quotes, this is a string.
Quick Checks:
- To declare a string in Python, put it in quotes when you assign it to your variable.
- What's the difference between "numerical variable" versus "string variable"?
- Walk through the difference between strings and numbers here. Be clear that they're both variables, just different types.
#
We Do: Declaring StringsA "We Do" means let's practice together. Follow along!
- We'll declare a variable called
name
and assign it the valueMarty
- We'll declare a variable called
car
and assign it the valueDelorean
- We'll declare a variable called
speed
and assign it the string value"88"
- We'll print out these variables
- We'll add
4
tospeed
- what happens?
- "Let's declare some variables in and print them. You'll be doing a lot of programming, and if you practice typing variable declarations out, you'll get faster every time."
After you run the very last one...
- It's important to note that you cannot do math on strings! Even if what's inside the quotations is a number, Python will interpret it as a word.
- In our last example, instead of printing
92
like you might expect, Python will throw an error. It seesspeed
as a string, not a number, so it doesn't know how to do addition on it. - Make sure that when you want a numerical value you do not use quotes!
#
String Concatenation+
on:
- Numerical variables adds (
5 + 5 = 10
). - String variables concatenate (
"Doc" + "Brown" = "DocBrown"
).- Pssst: Pronunciation tip: con-CAT-en-ATE
- Numerical strings concatenate to new strings! (
"5" +
"4"=
"54"`)
first_name = "Doc"last_name = "Brown"full_name = first_name + last_nameprint(full_name)# Prints "DocBrown".
Quick Checks:
The
+
operator means addition for numbers, but not for strings. When given string values, the+
operator actually behaves differently — it concatenates, or combines, two strings together to make one big string.Using the
+
operator to combine the two strings together literally puts them next to each other instead of evaluating their total."Concatenation is a formal term for when strings are glued together. Here's an example of concatenation."
Important: the plus sign will not add string variables with numbers in them.
#
We Do: Spaces in ConcatenationIt's another "We Do." Let's do this together - follow along!
Repl.it Note: The code is:
name = "Marty"car = "Delorean"speed = "88mph"
To begin: sentence = name + "is driving his" + car + speed
We expect the sentence to be Marty is driving his Delorean 88mph
. Is that what we got?
Quick Checks:
- Python put the strings together, but do you notice anything wrong? There is no space between the words! This is because we didn't add the spaces in. It's just one of many reasons why we have to carefully watch our spacing and grammar!
- Since a space is a character - it's on the keyboard - we can make it a string. Therefore, we can add it into our concatenation. By default, concatenation doesn't have spaces - you'll always have to add them yourself.
#
Strings and Printing: ReviewStrings are made with quotes:
name = "Marty"car = "Delorean"speed = "88"
String Concatenation - we need to add the spaces!
sentence = name + " is driving his " + car + " " + speedstring_numbers = "88" + "51"# string_numbers = 8851
To easily create spaces while printing:
print(name, "is driving his", car, speed)
Quick Checks:
- You can also
print
directly; you don't necessarily need an extra variable. To print strings next to each other, you separate them with a comma. Then, Python will add the space for you. This isn't concatenating variables, but it's useful to know!" Change code to:sentence = name + " is driving his " + car + " " + speed
- "When
print
ing, commas also create spaces." Change code to:print(name, "is driving his", car, speed)
#
Discussion: Some Common Mistakes: 1Do you think this will run? If yes, what does it print?
my_numprint(my_num)
#
Discussion: Some Common Mistakes: 2How about this? Does it run? If so, what does it print?
my_num = 5print()
#
Discussion: Some Common Mistakes: 3How about this? Does it run? If so, what does it print?
my_num = 5my_string = "Hello"print(my_num + my_string)
#
Discussion: Some Common Mistakes: 4One last question. What does this do?
my_num1 = "10"my_num2 = "20"print(my_num1 + my_num2)
#
Q&A and SummaryWe learned a lot today!
- We created, used, and re-assigned number and string variables.
- We used the numerical operators
+ - / * // %
- We did some complex stuff with the
print
function!
Congrats! You've finished your first programming lesson!