Python Variables

Creating Variables

variables help us reference a piece of data for later use.

name = "Ahmed"
height_cm = 180
weight_kg = 85.5

A variable gives us an easy-to-use shortcut to a piece of data. Whenever we use the variable name in our code, it will be replaced with the original piece of data.
In this case, one of our variables name and its vale is Ahmed. Another variable is height_cm and its value is 180. We define variables using an equal sign =.

Variables Names Rules

When defining variables, we need to follow a few rules:

  • Must start with a letter (usually lowercase)
  • After first litter, we can use letters/numbers/underscores
  • No space or special characters
  • Variable names a re case sensitive (my_var is different from MY_VAR)
# Valid Variables
baby_weight
bw
baby1
b_1
# Invalid Variables
baby-weight
bw!
baby@1

Error Messages

Let's see what happens when we try to use an invalid variable name. The variable baby-weight is invalid because of the hyphen -.

File "main.py", line 1
    baby-weight = 3
    ^
SyntaxError: cannot assign to operator

Floats and Stings

Variables come in many flavors. Two important flavors are floats and strings.

  • Floats represent either integers or decimals
height = 180
weight = 85.5
  • Strings represent text; can contain letters, numbers, spaces, and special characters
name = 'Ahmed'
Job = "Data Analytics & Visualization Engineer"

We define a string by putting either single '' or double "" quotes around a piece of text.

Common String Mistakes

It's easy to get errors when working with strings. If you get one, there are two likely causes.

  • Without quotes last_name = Gouda, you'll get a NameError.
File "main.py", line 1, in <module>
    last_name = Gouda
NameError: name 'Gouda' is not defined

If you forgot to put quotation marks around your string, Python will thing that your string is a variable. And if that variable wasn't previously defined, you'll get a NameError.

  • Different quotation marks last_name = "Gouda', you'll get a SyntaxError.
File "main.py", line 9
    last_name = "Gouda'
                      ^
SyntaxError: EOL while scanning string literal

If you mix single ' and double " quotes, you'll get a syntax error.

Displaying Variables

name = "Ahmed"
height_cm = 180
weight_kg = 85.5

print(height_cm)

Output:

180

If we want to know the current value of one of our variables, we can use print. We simply type the word print and put our variable name inside of the parentheses print(name).