Python Refresher
Commentβ
# This is a comment
Variablesβ
- Can only be one word.
- Can use only letters, numbers, and the underscore (_) character.
- Canβt begin with a number.
- Variables are case-sensitive (
data
,Data
andDATA
would be different variable names).
# defining variables
apple = 3
# assigning value to a var
apple = apple + apple
apple
Print()β
# printing a string
print("printed")
# printing an integer
print(apple)
# using print with format
name = "Sam"
grade = 81
print("{} scored a grade of {} on the test.".format(name, grade))
# using f-string with print statement
print(f"{name} scored a grade of {grade} on the test.")
Data Typesβ
Numbers (Integers, Floats)β
print("addition\t", 5+2)
print("subtraction\t", 5-2)
print("multiplying\t", 5*2)
print("making an exponential calculation\t", 5**2)
print("dividing\t", 5/2)
print("dividing and returning only the whole part\t", 5//2)
print("dividing and returning remainder after division\t", 5%2)
Stringsβ
# creating a simple string - single quotes
'This is fun!'
# Or with Double-quotes
"This is fun, isn't it!?"
# concatenanting 2 strings together
"This is fun, " + "isn't it!?"
Booleansβ
Booleans represent one of two values: True
or False
.
# TRUE boolean
True
# FALSE boolean
False
# using int() to turn the boolean into 1
int(True)
# using int() to turn the boolean into 0
int(False)
# 'True and True' always return'True'
True and True
# 'True AND False' always returns 'False'
True and False
# 'True OR False' always returns 'True'
True or False
Comparison Operatorsβ
# comparing values and returning a boolean
1 < 2
# comparing values and returning a boolean
1 > 2
# comparing values and returning a boolean
1 <= 2
# comparing values and returning a boolean
1 >= 2
# comparing values and returning a boolean
1 == 2
# comparing values and returning a boolean
1 == 1
# comparing values and returning a boolean
1 != 2
# comparing values and returning a boolean
(1 < 2) and (2 < 3)
# comparing values and returning a boolean
(1 > 2) or (2 < 3)
# comparing values and returning a boolean
"string" == "string"
# comparing values and returning a boolean
"string" == 'spring'
# comparing values and returning a boolean
"Bill" in ["Bill", "Sarah", "Karen"]
# comparing values and returning a boolean
"Ann" not in ["Bill", "Sarah", "Karen"]
Listsβ
# creating a list of integers
[1,2,3,4,5]
# creating a list of int and string
L = [1, 'two', 3, 4, 5]
L
# accessing list items using index notation
L[0]
# assigning value to an item of the list
L[1] = 2
L
# concatenating lists together
L + [6, 7, 8, 9]
List slicingβ
# slicing a list
L3 = [1,2,3,4,5]
L3[0:3]
# selecting all items - starting for the position 3
L3[3:]
# selecting the last element of the list
L3[-1]
# returning reversed list
L3[::-1]
List comprehensionβ
# creating a list
L = [-1,-2,-3,-4,-5]
L
# creating a new list based on the list 'L'
L_dbl = [n*2 for n in L]
L_dbl
# creating a new list based on the list 'L'
L_abs = [abs(num) for num in L]
L_abs
# creating a new list based on the list 'L_abs'
filter_L = [num for num in L_abs if num < 3]
filter_L
Tuplesβ
# creating a tuple
tup = (1,2,3)
tup
# selecting elements of the list
tup[:2]
# unpacking and assigning multiple values at once
num1, num2, num3 = (5,11,15)
print(num2)
Lists vs Tuplesβ
Similarities:
- They are both used to store collection of data
- They are both heterogeneous data types means that you can store any kind of data type
- They are both ordered means the order in which you put the items are kept.
- They are both sequential data types so you can iterate over the items contained.
- Items of both types can be accessed by an integer index operator, provided in square brackets, [index]
Differences
- The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified.
- Tuples are more memory efficient than the lists.
- When it comes to the time efficiency, again tuples have a slight advantage over the lists especially when lookup to a value is considered.
- If you have data which is not meant to be changed in the first place, you should choose tuple data type over lists.
import sys
a_list = list()
a_tuple = tuple()
a_list = [1,2,3,4,5]
a_tuple = (1,2,3,4,5)
print("size of a_list", sys.getsizeof(a_list))
print("size of a_tuple", sys.getsizeof(a_tuple))
import sys
import time
start_time = time.time()
b_list = list(range(10000000))
end_time = time.time()
print("Instantiation time for LIST:", end_time - start_time)
start_time = time.time()
b_tuple = tuple(range(10000000))
end_time = time.time()
print("Instantiation time for TUPLE:", end_time - start_time)
start_time = time.time()
for item in b_list:
aa = b_list[30000]
end_time = time.time()
print("Lookup time for LIST: ", end_time - start_time)
start_time = time.time()
for item in b_tuple:
aa = b_tuple[30000]
end_time = time.time()
print("Lookup time for TUPLE: ", end_time - start_time)
if, elif, else Statementsβ
if
is a condition statement.elif
is pythons way of saying "if the previous conditions were not true, then try this condition".else
statement catches anything which isn't caught by the preceding conditions.
# using the 'if' statement
if 1:
print("True")
# for any non-zero number it will return True
if -3.1415:
print("negative Pi is True!")
# creating another example of 'if' statements
user_email = "jeff@amazon.com"
password = "bezos"
if user_email == "jeff@amazon.com":
if password == "bezos":
print("Access granted.")
# creating an 'if' statement for value comparison
if 5>2:
print("True")
if <condition>:
block of code
elif <condition)
block of code
# creating an example of combinations of conditions
age = 25
if age < 10:
print("Just a kid.")
elif age < 16:
print("Can't drive yet!")
elif age > 21:
print("You are an adult!")
if <condition>:
block of code
else:
block of code
# creating an example of combinations of conditions
age = 25
if age < 10:
print("Just a kid.")
elif age < 16:
print("Can't drive yet!")
elif age < 21:
print("No drinking for you!")
else:
print("You're good to go!")
Functionsβ
A function is a block of code which only runs when it is called.
# creating a simple function of print statements
def greeting():
print("Hello")
print("Hola")
print("Ciao")
# calling the function
greeting()
# creating a function that requires a parameter
def root_on(school):
if school == "UC":
print("Go Bearcats!")
elif school == "OSU":
print("Go Buckeyes!")
else:
print("Go team!")
# calling the function
root_on("UC")
Retuning a valueβ
# returning a value within a function
def root_on2(school):
if school == "UC":
return "Go Bearcat!"
if school == "OSU":
return "Go Buckeyes!"
return "Go team!"
# calling the fucntion
my_team = root_on2("UC")
print("You can do it! {}".format(my_team))
Returning multiple values in the same functionβ
a single function can return multiple values in the same call. the return outputs are separated by commas - ,
def math_operations(a, b):
sum = a + b
diff = a - b
mul = a * b
div = a / b
return sum, diff, mul, div
# and you can call the function and assign the return values to variables
num1 = 5
num2 = 10
sum, diff, mul, div = math_operations(num1, num2)
print(
f"The sum is {sum}\n"
f"The difference is {diff}\n"
f"The multiplication gives {mul}\n"
f"The division gives {div}\n"
)
Lambda functionβ
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
# creating a 'lambda' fuction
aFunction = lambda x: x * x
print(aFunction(10))
Try, Except, and Else Statementsβ
# creating a fucntion
def divide(a,b):
print("a: {} b: {}".format(a, b))
try:
result = a / b
except (ZeroDivisionError) as err:
print("Divide by zero:")
print(err)
except (TypeError) as err:
print("Type error:")
print(err)
else:
print(f"{a} divided by {b} is {result}") # function strings in python
finally:
print("This will run no matter what")
# calling the fucntion and passing arguments
divide(6,2)
# calling the fucntion and passing arguments
divide(6, 'a')
# calling the fucntion and passing arguments
divide(6,0)
for Loopsβ
A for loop is used to iterate over a sequence of values.
# creating a sequence of numbers
range(10)
# applying the sequence to a list
list(range(10))
# creating a 'for loop'
for number in range(10):
print(number)
# creating a for loop for a specific range of values - range(start, stop)
for num in range(90,101):
print(num)
# creating a for loop for a specific range of values - range(start, stop)
for item in range(0, 26, 5):
print(item)
# creating a for loop for a range of values that goes in reverse/decending order
for value in range(10,0,-1):
print(value)
# creating a more elaborated for looop
my_list = [1, 11, 4, 44]
for thing in my_list:
greeting()
print("\n")
# creating a for loop to print values from a list
my_list = [1, 11, 4, 44]
for thing in my_list:
print(thing)