3.1 Variables and Assignments
Variables
Variables are values that can store data and can change depending on info passed through a program.
Variables can be useful when storing different values that change based on user input, for example, changing the avatar, sound effects, and powerups in a video game based on a character selected by the player early on.
Variable names can be anything from just a letter, like n
for number to a descriptive name like grade
. It’s important that variable names can be understood by human readers and not just computers, so make sure to pick something that makes sense.
n = 17
name = "Maryam"
student_grade = 12
# In Python, you can view the value stored in a variable using print statements, as shown below.
# Use the syntax "print(variable_name)" for Python
print(n)
print(name)
print(student_grade)
17
Maryam
12
Notice how my name is surrounded by quotation marks. Variables with words or phrases are called strings (explained in 3.1.2), and you must put quotes around them
Variables can be useful when you want to call information stored previously in code.
player_name = "Maryam"
player_age = 17
player_blonde = False #this variable is a boolean! More info on those in 3.1.2
print(player_name)
print(player_age)
print(player_blonde)
Maryam
17
False
Re-declaring a variable will overwrite any previous declaration, so be careful when creating new variables and make sure they have distinct names.
student_age = 16
print(student_age)
print()
student_age = 17
print("Redefinding variable")
print()
print(student_age)
16
Redefinding variable
17
Variable Naming
Remember, it’s important that your variable names can easily be understood by others, both in your group and in the class. When naming a variable, you cannot use any spaces, so you must use another way to call multi-word variables.
There are three common formats used when formatting the name for your variable that you can use to break up the text. In Python, variable names are CASE SENSITIVE. Make sure you remember which letters are capital in your variable names.
SnakeCase
Replace all spaces with underscores. This is the standard naming convention in Python for variables.
player_one = "Joanna"
PascalCase
Capitalize every new word in variable name, but include no spaces. This example is for learning purposes only, but stay away from this naming convention for variables in Python, as PascalCase is reserved for class names.
PlayerOne = "Nora"
CamelCase
Capitalize every word after the first in the variable name. Not typically used in Python, but is standard for variables in JavaScript.
playerOne = "Kushi"
# Popcorn Hack Cell
player_one = "Joanna"
PlayerOne = "Nora"
playerOne = "Kushi"
# All three variables are different. Programming languages are sensitive to snake case, upper case, etc.
print(player_one, PlayerOne, playerOne)
Joanna Nora Kushi
Popcorn Hack:
Make your own variables for members of your team, but follow naming convention for Python