Fundamental Lessons

Variables & Operators

Variables

Like most programming languages, Python uses variables to store values. The = assignment operator assigns a variable to a integer(int), string (str), or a bool(bool)

>>> a = 3
>>> b = 'Hello'
>>> c = True 

Python understands each variable type, it knows that a is a type int, b is a type str, and c is type bool

Operators

Operators are special symbols in Python that carry out arithmetic or logical computation.The int type uses the following operators: Addition (+) Subtraction (-), Multiplication (*), Division (/), Modulo (%), Exponentiation (**)

>>> a = 3
>>> b = 4
>>> a + b
>>> a * b
>>> a % b
7
12
3

List

Lists are used to store multiple elements. Elements in a list can of type (str) or (int)

grocery = ['milk', 'eggs', 'juice', 'water', 'chicken']
numbers = [1,2,3,4,5]

Now that we created our list called numbers and our list called grocery. Let's add cheese to our grocery list and the number 6 to our numbers list by using the append() function

>>> grocery.append('cheese')
>>> numbers.append(6)
grocery = ['milk', 'eggs', 'juice', 'water', 'chicken', 'cheese']
numbers = [1,2,3,4,5,6]

We can also remove elements from the list with the remove() function

>>> grocery.remove('milk')
grocery = ['eggs', 'juice', 'water', 'chicken', 'cheese']

Video credits to Khan Academy


Loops

For Loops

For loops in Python are used for iterating over elements in list. Let's iterate over each item on our grocery list

>>> grocery = [eggs', 'juice', 'water', 'chicken', 'cheese']
>>> for d in grocery:
...print(d)
eggs
juice
water
chicken
cheese


Video credits to Khan Academy


While Loops

The while loop allows us to repeat the same code as long as the condition is true

>>> n = 1
>>> while n < 4
...n += 1
...print(n)
1
2
3

Video credits to Khad Academy


Time to test what you have learned!


Which of the following variables correctly stores a string?
>>> x = Hey
>>> y = 'Hello'
>>> z == 'True'
x
y
z

What does the following code print?
>>> x = 3
>>> y = 4
>>> z = x * y
>>> print(z)
 7
z
 12
x * y

Which of the following values cannot be stored in this list?
grocery = ['milk', 'eggs', 'juice', 'water', 'chicken']
wow123
123
wow
 All values can be stored



Time: 0s
>>> a = 0
>>> while a < 5:
...print(a)
...a = a + 2