Skip to main content

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 and DATA would be different variable names).
# defining variables
apple = 3
# assigning value to a var
apple = apple + apple
apple
Output:
6

Print()​

# printing a string
print("printed")
Output:
printed
# printing an integer
print(apple)
Output:
6
# using print with format
name = "Sam"
grade = 81
print("{} scored a grade of {} on the test.".format(name, grade))
Output:
Sam scored a grade of 81 on the test.
# using f-string with print statement
print(f"{name} scored a grade of {grade} on the test.")
Output:
Sam scored a grade of 81 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)
Output:
addition     7
subtraction 3
multiplying 10
making an exponential calculation 25
dividing 2.5
dividing and returning only the whole part 2
dividing and returning remainder after division 1

Strings​

# creating a simple string - single quotes
'This is fun!'
# Or with Double-quotes
"This is fun, isn't it!?"
Output:
"This is fun, isn't it!?"
# concatenanting 2 strings together
"This is fun, " + "isn't it!?"
Output:
"This is fun, isn't it!?"

Booleans​

Booleans represent one of two values: True or False.

# TRUE boolean
True
Output:
True
# FALSE boolean
False
Output:
False
# using int() to turn the boolean into 1 
int(True)
Output:
1
# using int() to turn the boolean into 0
int(False)
Output:
0
# 'True and True' always return'True'
True and True
Output:
True
# 'True AND False' always returns 'False'
True and False
Output:
False
# 'True OR False' always returns 'True'
True or False
Output:
True

Comparison Operators​

# comparing values and returning a boolean
1 < 2
Output:
True
# comparing values and returning a boolean
1 > 2
Output:
False
# comparing values and returning a boolean
1 <= 2
Output:
True
# comparing values and returning a boolean
1 >= 2
Output:
False
# comparing values and returning a boolean
1 == 2
Output:
False
# comparing values and returning a boolean
1 == 1
Output:
True
# comparing values and returning a boolean
1 != 2
Output:
True
# comparing values and returning a boolean
(1 < 2) and (2 < 3)
Output:
True
# comparing values and returning a boolean
(1 > 2) or (2 < 3)
Output:
True
# comparing values and returning a boolean
"string" == "string"
Output:
True
# comparing values and returning a boolean
"string" == 'spring'
Output:
False
# comparing values and returning a boolean
"Bill" in ["Bill", "Sarah", "Karen"]
Output:
True
# comparing values and returning a boolean
"Ann" not in ["Bill", "Sarah", "Karen"]
Output:
True

Lists​

# creating a list of integers
[1,2,3,4,5]
Output:
[1, 2, 3, 4, 5]
# creating a list of int and string
L = [1, 'two', 3, 4, 5]
L
Output:
[1, 'two', 3, 4, 5]
# accessing list items using index notation
L[0]
Output:
1
# assigning value to an item of the list
L[1] = 2
L
Output:
[1, 2, 3, 4, 5]
# concatenating lists together 
L + [6, 7, 8, 9]
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

List slicing​

# slicing a list
L3 = [1,2,3,4,5]
L3[0:3]
Output:
[1, 2, 3]
# selecting all items - starting for the position 3
L3[3:]
Output:
[4, 5]
# selecting the last element of the list
L3[-1]
Output:
5
# returning reversed list
L3[::-1]
Output:
[5, 4, 3, 2, 1]

List comprehension​

# creating a list
L = [-1,-2,-3,-4,-5]
L
Output:
[-1, -2, -3, -4, -5]
# creating a new list based on the list 'L'
L_dbl = [n*2 for n in L]
L_dbl
Output:
[-2, -4, -6, -8, -10]
# creating a new list based on the list 'L'
L_abs = [abs(num) for num in L]
L_abs
Output:
[1, 2, 3, 4, 5]
# creating a new list based on the list 'L_abs'
filter_L = [num for num in L_abs if num < 3]
filter_L
Output:
[1, 2]

Tuples​

# creating a tuple
tup = (1,2,3)
tup
Output:
(1, 2, 3)
# selecting elements of the list
tup[:2]
Output:
(1, 2)
# unpacking and assigning multiple values at once
num1, num2, num3 = (5,11,15)
print(num2)
Output:
11

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))
Output:
size of a_list 96
size of a_tuple 80
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)
Output:
Instantiation time for LIST: 0.3332700729370117
Instantiation time for TUPLE: 0.31255292892456055
Lookup time for LIST: 0.5446491241455078
Lookup time for TUPLE: 0.5337920188903809

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")
Output:
True
# for any non-zero number it will return True
if -3.1415:
print("negative Pi is True!")
Output:
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.")
Output:
Access granted.
# creating an 'if' statement for value comparison
if 5>2:
print("True")
Output:
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!")
Output:
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!")
Output:
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()
Output:
Hello
Hola
Ciao
# 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")
Output:
Go Bearcats!

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))
Output:
You can do it! Go Bearcat!

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"
)
Output:
The sum is 15
The difference is -5
The multiplication gives 50
The division gives 0.5

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))
Output:
100

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)
Output:
a: 6 b: 2
6 divided by 2 is 3.0
This will run no matter what
# calling the fucntion and passing arguments
divide(6, 'a')
Output:
a: 6 b: a
Type error:
unsupported operand type(s) for /: 'int' and 'str'
This will run no matter what
# calling the fucntion and passing arguments
divide(6,0)
Output:
a: 6 b: 0
Divide by zero:
division by zero
This will run no matter what

for Loops​

A for loop is used to iterate over a sequence of values.

# creating a sequence of numbers
range(10)
Output:
range(0, 10)
# applying the sequence to a list
list(range(10))
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# creating a 'for loop'
for number in range(10):
print(number)
Output:
0
1
2
3
4
5
6
7
8
9
# creating a for loop for a specific range of values - range(start, stop)
for num in range(90,101):
print(num)
Output:
90
91
92
93
94
95
96
97
98
99
100
# creating a for loop for a specific range of values - range(start, stop)
for item in range(0, 26, 5):
print(item)
Output:
0
5
10
15
20
25
# creating a for loop for a range of values that goes in reverse/decending order
for value in range(10,0,-1):
print(value)
Output:
10
9
8
7
6
5
4
3
2
1
# creating a more elaborated for looop 
my_list = [1, 11, 4, 44]

for thing in my_list:
greeting()
print("\n")
Output:
Hello
Hola
Ciao


Hello
Hola
Ciao


Hello
Hola
Ciao


Hello
Hola
Ciao
# creating a for loop to print values from a list
my_list = [1, 11, 4, 44]

for thing in my_list:
print(thing)
Output:
1
11
4
44