Knowledge Pillars Code Questions
Knowledge Pillars Code Questions
Pedro Padron
Duck-type
• Not a lot of structure
• Uses indentation to group functions and operations
• Will interpret your code if you get close
• Why Duck Type
• If it looks like a duck and quacks like a duck, it is probably a duck.
• If it looks like what you wanted to do, it will probably be able to figure it out
Variable Storage Types
• List or Array [ ]
• Set ( , )
• Dictionary { , }
• Tuple ( )
List
• Just like any other list.
• Separate items with a comma
• Name list with lower case word
• Is Indexed
• Is Ordered
• Is Iterable
• Is Mutable
• No Duplicates
• sample_list[1, 2, 3, “A”, “B”, “C”]
Array
• Structured as a list or an embedded list
• arr[1, 2, 3]
• multi_dimensional_array[[1, 2, 3],[“a”, “b”, “c”]]
Set
• set(a, b)
• Not indexed
• Not ordered
• Is Iterable
• Is Mutable
• No duplicates allowed
• Stored as a set of data similar to an ordered pair of X,Y coordinates
• Only data type that is not indexed or ordered.
Dictionary or dict
• Is Ordered
• Is Mutable
• No Duplicates
• Uses keys to locate the data
• Data stored as a {key, value} structure
• Think of key as a word and value as a definition
Tuple
• Tuple is a immutable class data type similar to a list.
• Immutable means, that it CANNOT be changed.
• A tuple is a permanent fixed list of data.
• Is Ordered
• Is Indexed
• Is Iterable
• Not mutable
• No Duplicates
Variables
• No formal variable declaration
• Variable is not declared with a data type
Functions
• Function starts with the term def
• Ends with a colon :
• All items contained in the function are indented to show the
structure of inclusion.
def MaxList():
a = max(mylist)
return a
mylist = [1, 3, 5, 2, 12, 10 ]
print(MaxList(mylist))
If / Then / Else / Elif
• If statement ends with : colon
• Included in IF statement is indented for all items that would accept
Then. No word “Then” is used like in Basic.
• Else statement ends with : colon
• Included with ELSE statement is indented
• Uses elif (short for else if) for multiple If conditional tests.
If Example
if type(value) is list:
return 0
elif type(value) is tuple:
return 1
elif type(value) is set:
return 2
else:
return 3
For Loops
• Works like any other For loop.
• Indent items that are within the loop
def summing(a: int, b: int): Does the range(a, b) include b?
sum = 0
No.
for x in range(a, b):
To include b use range(a, b+1)
sum += x
return sum
print(summing(2, 5))
Change Data Type
def convert_float(fl): 79.99 to int = 79
fl = int(fl)
fl = str(fl) 79 to str = “79”
fl = list(fl)
return fl “79” to list = [‘7’ , ‘9’]
print(convert_float(79.99)
Want Python to figure out the data type
that works…
• Let’s say you have variable a, but don’t remember if it is a float or a
string when entered by the user.
• Maybe you forgot to make the user input a float data type. By
default it would be a string.
• You try something like this and get an error because you can’t add a
string
price + a
• Use eval() and let python figure it out for you. Maybe int, string, bool
price + eval(a)
User Input
name = input(“Enter your name: “) Default is always string
price = float(input(“Enter the price: “)
age = int(input(“Enter your age: “) Must declare data type if not a string
price = float(input(“Enter the price: “)
Python does not need to declare this as a
tip_rate = .15 float. It figures it out on it’s own.
tip = price * tip_rate
total_price = price + tip
Open and read, write, append a file
• r = read = only reads the file
• w = write = overwrites the entire file
• a = append = adds to the end of a file
• Example to open and read a file:
fin = open(“file_name.txt”, “r”)
Comments
• # used for single line comment
• “”” used for multi-line comment “””
• ‘’’ can be used instead of “”” ‘’’
• “”” if referred to as documentation and can be output
as help or documentation “””
A third parameter of Step can be added to
either. randint(1,6,2) will count by 2’s.
• randint is a random integer selected from the given parameters
• Is INCLUSIVE of the start and end number
random.randint(1,5)
will select one number from 1, 2, 3, 4, 5
• randrange is a random integer selected from the given parameters
• Is NOT INCLUSIVE of the end number
random.randrange(1,5)
will select one number from 1, 2, 3, 4
Importing Packages / Modules
• Python packages are a collection of modules that are not in the standard
installation of python.
• Can create your own import files using PIP
• PIP is Python Import Package
• Syntax is
from package.module import name
• Math package
from math.calculus import volume
• Scientific Equations
from scikit-learn.linear_model import LinearRegression
Importing Modules
• You can create your own .py files or modules
• You can import these into another .py file
import file01
• This means import file01.py
Custom Packages
• You can create your own Python packages.
• You will need to install them in the PIP section of python.
• Custom Python Packages or those downloaded from the Internet can
be accessed from the PIP.
• Packages can then be imported as any other package
Try / Except
• To keep your program from breaking, you can use the Try / Except
block.
• If the Try works, code will continue
• If the Try fails, the Except block will execute
• A Try block must have at least one Except block to run.
• Example to trap an invalid integer value
try:
a = type(float) or type(bool)
except:
print(“Error”)
Extend / Insert / Pop
• extend() = multiple items added as an individual item to a list
• insert() = inserts a value to a specific position
• pop() = single item deleted and returned
Break / Continue / Pass
• break = loop is broken, control passed to outside of the loop
• continue = loop not broken, iterates loop without execution
• pass = loop not broken, used as a placeholder for future code, allows
you to write a loop without having all the other code written.
Shebang or Hashbang
• # is called she or hash
• ! is called bang
• Together the symbol #! is called a shebang or hashbang
• #!/usr/bin/env python3
• Shebang specifies which program should be called to run a script.
• In the example above, python3 is called to run the script.
• To run any outside script, the #! must be used
Python Magic
• Magic or Dunder Methods.
• Magic methods in Python are the special methods that start and end
with the double underscores.
• They are also called dunder methods.
• Magic methods are not meant to be invoked directly by you, but the
invocation happens internally from the class on a certain action
• __init__
• __main__
• __call__
Python Activities
• Open your Replit online account to work the following coding
problems
Print the maximum value from a list
named mylist. Output: 12
def MaxList(lst):
# enter your code here
return max(lst)
# Please don’t modify
mylist = [1, 3, 5, 2, 12, 10]
print(MaxList(mylist))
Write a function that accepts any arbitry
argugument (Value) and returns True if the
argument is a list, otherwise it should return
False
def
correct_type_passed(value) -> bool:
#Enter your code here
if type(value) == list:
return True
else:
return False
print(correct_type_passed(6)) Integer
print(correct_type_passed([6, 7, 9])) List
print(correct_type_passed((6,2))) Tuple
Write a function that accepts any arbitrary
argument (Value) and returns True if the
argument belongs to the integer class,
otherwise it should return False
def correct_type_passed(value) -> bool:
#Enter your code here
if type(value) == int:
return True
else:
return False
print(correct_type_passed(6)) #Integer
print(correct_type_passed([6, 7, 9])) #List
print(correct_type_passed((6,2))) #Tuple
Write a function that accepts any arbitrary
argument (Value) and returns True if the
argument is a tuple, otherwise it should return
False
def correct_type_passed(value) -> bool:
#Enter your code here
if type(value) == tuple:
return True
else:
return False
print(correct_type_passed(6)) #Integer
print(correct_type_passed([6, 7, 9])) #List
print(correct_type_passed((6,2))) #Tuple
Write a function that accepts two integers(a,
b), it should sum up all the numbers from a to
b (inclusive of a and b) and then return the
sum divided by 2 as a float.
def looping_sum(a: int, b: int) -> int:
# Enter your code here
sum = 0
for x in range (a,b+1):
sum += x
return float(sum/2)
print(looping_sum(2, 5))
print(looping_sum(7, 9))
Write a function that accepts an integer(i)
which can only be 0 or 1. The function should
return the inverse Boolean representation of
the integer.
def return_bool_integer(i: int) -> bool:
# Enter your code here
if i == 0:
return True
else:
return False
print(return_bool_integer(0))
print(return_bool_integer(1))
Write a function that accepts an integer(i)
which can only be 0 or 1 and returns the
Boolean representation of that integer.
def return_bool_integer(i: int) -> bool:
# Enter your code here
if i == 1:
return True
else:
return False
print(return_bool_integer(0))
print(return_bool_integer(1))
Write a function that accepts a tuple of
positive integers (tup) and return a new
ordered list containing the smallest and
largest integers only.
def return_smallest_largest(tup: tuple) -> tuple:
#Enter your code here
a = min(tup)
b = max(tup)
return [a,b]
print(return_smallest_largest((5, 4, 6, 1, 10, 35)))
print(return_smallest_largest((10, 4, 7, 8, 21, 34, 100)))
Add the line of code needed to accumulate
the total of all values of a and then print the
result.
total = 0
for a in range(6):
# Here goes your code
total = total + a
print(total)
Add the line of code needed to count the
number of values generated for a and then
print the result.
count = 0
for a in range(6):
# Here goes your code
count = count + a
print(count)
Write a function that accepts two integers(a
and b, where a < b) and returns the sum of all
numbers between a and b (inclusive of a and
b)
def looping_sum(a: int, b: int) -> int:
# Enter your code here
sum = 0
for x in range(a, b+1)
sum += x
return sum
print(looping_sum(2, 5))
print(looping_sum(8, 10))
You are given a function
which contains a non def while_loop_finisher(x: int):
working while loop. The value = -1
function also accepts a while value:
positive integer (x). The value -= 1
while loop is in an infinite # Enter your code here
loop state, which would be
if value == x:
unwise to run. The while
loop continually decreases return value
the value variable by 1. print(while_loop_finisher(-7))
Your task is to fix the code print(while_loop_finisher(-15))
so that the loop exits and
returns the value variable
when it is equal to x.
Write a function that takes a string (st)
containing one letter surrounded by numbers.
The funcition should iterate through the string
and return only the letter as a string.
def return_only_the_letter(st: str) -> str:
#Enter your code here
for i in list(st):
if i.isalpha():
return i
print(return_only_the_letter(“124f2312”))
Write a function that accepts two tuples (t1
and t2) and returns a list containing the
intersection of two tuples.
def tuple_intersection(t1: tuple, t2: tuple) -> tuple:
# Enter your code here
return tuple(set(t1) & set(t2))
print(sorted(tuple_intersection((1, 2, 5), (5, 6, 7))))
print(sorted(tuple_intersection((1, 2, 5, 6, 10, 0), (0, 5, 6, 7, 10))))
Write a function that iterates over a tuple(tup)
and returns the position of the first odd
number.
def return_position_of_odd(tup: tuple) -> int:
# Enter you code here
for x in tup:
if x % 2 !=0:
return tup.index(x)
print(return_position_of_odd((5, 7, 9, 12, 44, 66)))
print(return_position_of_odd((50, 7, 9, 12, 44, 66)))
Add the calc function to the Point class. The
function should return the value of x variable
multiplied by the value of the y variable.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# Enter your code here
def calc(self):
return self.x * self.y
p1 = Point(3, 4)
print(p1.calc()) # this should print 12
def convert_float_to_string_to_list(fl: float) -> str:
Write a function that accept # Enter your code here
a float(fl) with 2 decimal
fl = int(fl)
places. Convert this float to
an integer, removing its fl = str(fl)
decimal places, then the fl = list(fl)
resulting integer as a string return fl
and then convert it to a list. print(convert_float_to_string_to_list(79.99))
The process looks like this print(convert_float_to_string_to_list(61.12))
65.66 -> 65 -> ’65’ -> [‘6’,
‘5’].
Print all the keys of a dictionary.
def DictKeys(dict): Replace ‘ ‘ marks in Replit.
These are the wrong ones
# Enter your code here
return dict.keys()
dict = {1: ‘apple’, 2: ‘ball’ }
print(DictKeys(dict))