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 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
Video credits to Khan Academy
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
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
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
>>> a = 0
>>> while a < 5:
...print(a)
...a = a + 2