Files
labs/Module-2/1.Basic/01-Variable Assignment.ipynb

5.5 KiB

Variable Assignment

Rules for variable names

  • names can not start with a number

  • names can not contain spaces, use _ intead

  • names can not contain any of these symbols:

    :'",<>/?|\!@#%^&*~-+
    
  • it's considered best practice (PEP8) that names are lowercase with underscores

  • avoid using Python built-in keywords like list and str

  • avoid using the single characters l (lowercase letter el), O (uppercase letter oh) and I (uppercase letter eye) as they can be confused with 1 and 0

In [ ]:
my_dogs = 2
In [ ]:
my_dogs
In [ ]:
my_dogs = ['Sammy', 'Frankie']
In [ ]:
my_dogs

Assigning Variables

Variable assignment follows name = object, where a single equals sign = is an assignment operator

In [ ]:
a = 5
In [ ]:
a

Here we assigned the integer object 5 to the variable name a.
Let's assign a to something else:

In [ ]:
a = 10
In [ ]:
a

You can now use a in place of the number 10:

In [ ]:
a + a

Reassigning Variables

Python lets you reassign variables with a reference to the same object.

In [ ]:
a = a + 10
In [ ]:
a

There's actually a shortcut for this. Python lets you add, subtract, multiply and divide numbers with reassignment using +=, -=, *=, and /=.

In [ ]:
a += 10
In [ ]:
a
In [ ]:
a *= 2
In [ ]:
a

Determining variable type with type()

You can check what type of object is assigned to a variable using Python's built-in type() function. Common data types include:

  • int (for integer)
  • float
  • str (for string)
  • list
  • tuple
  • dict (for dictionary)
  • set
  • bool (for Boolean True/False)
In [ ]:
type(a)
In [ ]:
a = (1,2)
In [ ]:
type(a)

Simple Exercise

In [ ]:
my_income = 100
tax_rate = 0.1
my_taxes = my_income * tax_rate
In [ ]:
my_taxes