04-Review (Fundamentals)#
Goals of this lecture#
This lecture is a quick refresher on Python fundamentals.
Variables.
Defining and using functions.
Conditional statements.
Loops.
Hopefully, much of this will be review from CSS 1 (and lab 1).
Variables#
A variable stores a particular value.
Unlike literals (e.g., an
int), the value of a variable can change (i.e., it can vary).Variables can be assigned using the assignment operator (
=).Once you’ve assigned a variable, you can use it by referencing that variable name.
## Example variable
my_int = 5
## Using this variable
my_int + 2
7
## Changing the value of the variable
my_int += 10
my_int
15
Rules on assigning variables#
Names on the left, values on the right (e.g.,
test_var = 2).Names are case sensitive (the variable
test_varcannot be accessed withtest_VAR).Variable names must begin with a letter.
They can contain a number (e.g.,
test1) or under-score, but can’t begin with a number or under-score.
Python mostly doesn’t care how you name your variables, though you should!
Remember that code is intended to be read by others––so make sure it’s clear!
types of objects#
The value assigned to a variable can have different types.
Here are some of the possible types in Python:
Type |
Description |
Example |
|---|---|---|
|
String/text |
|
|
Integer |
|
|
Float |
|
|
List |
|
|
Dictionary |
|
|
Boolean |
|
|
None |
|
Some types have special functions#
In Python, different types of objects have different functions.
The
strobject has thereplaceandsplitfunction.The
listobject has theappendandjoinfunction.
my_str = "CSS 1"
my_str = my_str.replace("1", "2")
my_str
'CSS 2'
my_str.split(" ")
['CSS', '2']
Some types are “collections”#
Both
lists anddictionaries store collections of items.
### example list
my_list = [1, 2, "a"]
my_list
[1, 2, 'a']
### example dictionary
my_dictionary = {'a': 1, 'b': 2}
my_dictionary
{'a': 1, 'b': 2}
Functions#
A function is a re-usable piece of code that performs some operation (typically on some input), and then typically returns a result (i.e., an output).
A function is defined using the def keyword:
def func_name(arg1):
### Whatever the function does
return some_value
Once a function has been created, you can use it.
Functions: a simple example#
The function square below returns the result of multiplying the input x by itself.
def square(x):
return x * x
square(2)
4
square(3)
9
Check-in: functions vs. variables#
Suppose we define a function called cube, which cubes some input x. How would we call that function, e.g., on an input like 2?
cubecube()cube(2)cube 2
Check-in: decoding a function#
What does the following function do?
def mystery_func(x, n):
return x % n == 0
Solution#
Here, mystery_func checks whether x is divisible by n.
mystery_func(10, 2)
True
mystery_func(10, 3)
False
Default values#
A default value is the value taken on by an argument by default. If no other value is specified, this is the value assumed by the function.
In the function definition, a default value can be specified by setting: arg_name = default_value.
In the example below,
xis required.But
nhas a default value of2.
def is_divisible(x, n = 2):
return x % n == 0
is_divisible(10) ### Assumes n = 2
True
is_divisible(10, 3) ### Override with n = 3
False
Check-in: positional vs. keyword arguments#
An argument to a function can be indicated using its position or a keyword. Which of these is demonstrated in the code below?
Positional
Keyword
Both
is_divisible(24, n = 3)
True
Control Flow#
Control flow refers to tools we can use to control which lines of code get executed, when.
In Python, there are two main ways to control the “flow” of our program:
Conditional statements:
if/elif/elseLoops:
for/while
Conditional statements#
In a nutshell, a conditional is a statement that checks for whether some condition is met.
We can use the if command to control which lines of code are executed.
x = "One string"
y = "One string"
if x == y:
print("These strings are the same.")
These strings are the same.
else#
An
elsestatement tells Python what to do if anifstatement evaluates toFalse.
x = "One string"
y = "Different string"
if x == y:
print("These strings are the same.")
else:
print("These strings are different")
These strings are different
Conditionals and functions#
Conditional statements become particularly useful when we combine them with functions.
def square_if_even(x):
if x % 2 == 0:
return x ** 2
else:
return x
Check-in#
How would you write a function fizzbuzz that:
Takes a number
xas input.returns “Fizz” if the number is divisible by3.returns “Buzz” if the number is divisible by5.returns “FizzBuzz” if the number is divisible by both3and5.
### Your code here
Solution#
def fizzbuzz(x):
if x % 5 == 0 and x % 3 == 0:
return "FizzBuzz"
if x % 3 == 0:
return "Fizz"
if x % 5 == 0:
return "Buzz"
Check-in#
How would you write a function called contains_letter that:
Takes both a
wordand aletteras inputs.Checks whether the
wordcontains thatletter.ifit does, itprints out “Yes”.Otherwise, it
prints out “No”.
### Your code here
Solution#
def contains_letter(word, letter):
if letter in word:
print("Yes")
else:
print("No")
contains_letter("dog", "o")
Yes
contains_letter("cat", "o")
No
Loops#
A loop is a way to repeat the same piece of code multiple times.
When should you use a loop?#
Rule of thumb: if you find yourself copying/pasting the same code many different times…you might think about using a loop!
More generally: in programming, we often want to execute the same action multiple times.
Apply the same instruction to every item on a
list.Continue running some code until a condition is met.
for loops in action#
A
forloop is used for iterating over a sequence.
A for loop uses the syntax:
for elem in list_name:
# Do something
## This is a list in Python
numbers = [1, 2, 3]
### This is a for loop
for number in numbers:
print(number)
1
2
3
for loops and functions#
Like if statements, a for loop becomes especially powerful when combined with a function.
def multiply_list(numbers):
product = 1 ## why do I start at 1, not 0?
for i in numbers:
product *= i
return product ## note the indentation!
multiply_list([1, 2, 3])
6
Check-in#
Write a function called find_vowels, which:
Takes as input a
str.returns a list of the vowels in that string.
### Your code here.
Solution#
def find_vowels(s):
vowels = []
for c in s:
if c.lower() in "aeiou":
vowels.append(c)
return vowels
find_vowels("programming")
['o', 'a', 'i']
find_vowels("cat")
['a']
Conclusion#
This was intended as a rapidfire review of Python fundamentals, including:
Basic Python syntax.
Defining functions.
Using
ifstatements.Using
forloops.
Next time, we’ll review packages that will be helpful for working with data, such as pandas.