1/80
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
T/F: Functions with return statements, built in functions (len, max), expressions return a VALUE
True
T/F: Functions without a return statement, statements (assignment and conditionals), print() returns a value
False
What is immutable?
Strings
What data types can list elements store?
Any data type
T/F: Python allows multiple return statements in a function
True
What can the len() function be used on?
strings, lists, tuples, dictionaries, ranges (NOT INTEGERS)
T/F: The in operator checks whether a value exists in a sequence like a list or a string
True
Data type: [ ]
list
Data type: { }
Dictionary
Data type: ( )
Tuple
Index of the last element in a list of size n
n-1
What does range(5) print?
0,1,2,3,4
If the else statement is outside of a for loop, will it execute with a break statement?
The else statement only executes if the loop wasnt exited via break
For loops
prints each iterable in the set until going through all, or meets an if/ else condition stating to break
What is the difference between = and ==?
= is an assignment operator
== is for mathematic expressions or used as a comparison operator for boolean expressions
What is the purpose of the pass statement?
Acts as a placeholder, essentially does nothing but allows code to run without errors. Can be used if you want to add something to a function later.
How can you generate a list of numbers from 1-10?
x=list(range(1,11))
print(x)
#the range function makes a set of numbers but doesnt include the last number
What is the difference between a function argument and a function parameter?
Parameter is the placeholder name in the definition
Argument is the actual value you pass to the function when CALLING it
What is the output of the following code?
a = [1,2,3]
b=a
b.append(4)
print(a)
[1,2,3,4]
#B is not a duplicate of a, instead it is just being called by a different name (think of it as a nickname), but the object is still adding 4
#Think of it as Meg (or) Meghan changing her hair color, it’ll different regardless of her name
Using user input in a function
define a variable OUTSIDE OF the function that takes user input then set that variable equal to the argument when calling the function
How to make input a different data type (other than a string)?
before using keyword input, write data type (int, list, tuple, etc.)
Write a function count_vowels(s) that takes a string s as input and returns the number of values (a,e,i,o,u) in the string.
s= input("Provide a string: ") #define outside func
def count_vowels(s):
vowels = ["a","e","i","o","u"] #make sure vowels are in quotes
a= [ ]
for i in s.lower(): #lower will count upper case too
if i in vowels: #in will search for element in vowles
a.append(i) #adds vowel to new list
return len(a) #counts list of vowels
print(count_vowels(s))
Write a function named sum_of_squares that takes an integer n as input and returns the sum of squares of all integers from 1 to n.
n = int(input("Enter a number: "))
def sum_of_squares(n):
x = 0 #initializing value
for i in range(n + 1): #because range function doesnt include last value, we have to add 1
x += i**2 # using (+=) adds the value to the initial value
return x
print(sum_of_squares(n))
T/F: Dictionaries allow duplicate keys
False
T/F: The self-keyword in Python is mandatory for instance methods in a class
True
T/F: Encapsulation refers to restricting access to certain details of an object
True
T/F: The get() method in dictionaries returns None if the key is not found
True (unless you specify in the second index)
T/F: super() is used to call a method from the parent class
True
T/F: Abstract classes can create an object from a class directly
False
T/F: Object in Python are instances of a class
True
T/F: The init method must return a value
False
T/F: You can edit a list inside of a tuple
True
What method is automatically called when an object is created?
init()
Define Abstraction:
Hiding the implementation details while exposing the functionality
Describe Polymorphism:
One function or method having multiple behaviors
Allows different classes to be treated as if they are the same type, but they behave differently when you call their methods.
class Dog:
def speak(self):
print("Bark")
class Cat:
def speak(self):
print("Meow")
d= Dog()
c= Cat()
d.speak
c.speak
What is a class called that contain 1+ abstract methods, and is a subclass of class ABC?
An abstract class
Opposite would be a concrete class
Access modifiers
Public has no underscore
_ Protected
_ _ Private
How do you add a key-value pair to an existing dictionary?
dictionary_name[“key”]=”value”
print(dictionary_name)
#{”key”: “value”} will be added to dictionary
Why do we use inheritance in object-oriented programming?
A child class (also called a subclass) inherits attributes and methods from a parent class.
It creates simplicity in the code.
Reuse code efficiently
Avoid repetition
Build maintainable systems
Support polymorphism for flexibility
What is multiple inheritance? Give an example.
When a class inherits from more than one parent class. This allows the child class to access the attributes and methods of all parent classes.
class Flyable:
def fly(self): #method
print("I can fly!")
class Swimmable:
def swim(self): #method
print("I can swim!")
class Duck(Flyable, Swimmable): #calling both classes
def quack(self): #method
print("Quack!")
d = Duck() #instance/object
d.fly() #”I can fly"!”
d.swim()
d.quack()
Multi-level inheritance
When a class inherits from a class that already inherited from another class.
class Animal:
def breathe(self):
print("Breathing...")
class Mammal(Animal):
def walk(self):
print("Walking...")
class Dog(Mammal):
def bark(self):
print("Barking!")
T/F: classes need attributes
False
Method Overriding
When a child class defines a method that already exists in its parent class, but gives it a new version - will print the new child version.
Difference between encapsulation and abstraction.
Encapsulation is about protecting and bundling data (attributes) and methods that work on the data within a class. It hides the internal state of an object from the outside world.
Abstraction is about hiding the details and showing only the essential features of something. It helps you focus on what something does, not how it does it.
Abstraction in depth…
Acts as a blueprint or skeleton for child classes.
It doesn’t do anything — it just says “Hey, every class that inherits from me must define this behavior, but I won’t tell you how”
from abc import ABC, abstractmethod
class Animal(ABC): # Abstract base class
@abstractmethod
def make_sound(self):
pass
#This says: "All Animals must make a sound, but I won’t define what that sound is here."
How do you iterate through dictionary keys and values?
keys are returned by default using a for loop
for item in dictionary_name:
return item #returns key
to return values, use the .values() method
for item in dictionary_name.values():
return item
What does the .get() method do in dictionaries?
retrieves values associated with specified key, otherwise returns None unless specific in second indices
dictionary= {"apple": 1, "banana":2}
dictionary.get("apple")
#returns 1
Defining and using classes in Python.
class Animal:
def init(self,animal,color):
self.animal=animal
self.color=color
def appearance(self): #only need to pass on self and new attributes
return(f"This is a {self.animal} and it is {self.color}.")
monkey = Animal("monkey", "brown") #making an instance
print(monkey.appearance()) #to call you must put () after method
print(monkey.color)
Linear vs Binary search
Linear search is an example of the Brute Force Algorithm, going one by one until finding search item
Binary search, the list must be SORTED, and the code will start in the middle and search left if value is smaller than middle, or search right if value is larger
What happens if a recursive function doesnt have a base case?
It is the condition under which the function stops calling itself and begins to return a result. Without it, the recursive function will not know when to stop because there is no simplest form.
Write a function that merges two dictionaries
fruits= {"apple": 1, "banana": 2}
vegetable = {"carrot": 3, "celery": 4}
def merge(dict1, dict2):
merged = {} #create an empty dictionary
for key in dict1:
merged[key] = dict1[key] #adds key from dict 1 to merged dictionary
for key in dict2:
merged[key] = dict2[key]
return merged
print(merge(fruits, vegetable))
Write a program to count occurrences of each element in a tuple.
tup = (1,2,2,3,4,1)
d={}
for item in tup:
d[item] = d.get(item,0)+1
print(d)
break and continue statement
The break statement is used to exit the loop entirely, even if the loop’s condition is still True. When break is encountered, the loop terminates, and the program continues with the next statement after the loop.
The continue statement is used to skip the current iteration of the loop and move to the next iteration. When continue is encountered, the rest of the code inside the loop for that iteration is skipped, and the loop moves to the next cycle.
splitting
The split() method is used to break a string into a list of substrings, based on a specified delimiter. It’s commonly used to divide a sentence into words, or split data separated by commas.
sentence = "Python is awesome"
print(sentence.split())
or you can use list method to directly make split into letter
Returning a dictionary pair
for x, y in dictionary.items():
print(x,y)
the .items() method returns pairs
Write a function to count the first letter of keys in a dictionary
dictionary = {"Apple": 1, "Banana": 1, "Celery": 2}
d = {}
for key in dictionary:
first_letter = key[0]
d[first_letter] = d.get(first_letter, 0) + 1
print(d)
Dictionaries as counters
word = {“apple”: 1, “banana”: 2}
d = {}
for item in word:
d[item]=d.get(item,0) + 1
print(d)
slicing
sentence = "Python is awesome"
print(sentence [7:9]) #Extracts characters from index 7 to 8 (excluding 9)
#output “is”
Linear Search
def name(alist, a):
for item in alist: #in will search
if item == a:
return True
return False
Divide and Conquer
breaking down into smaller problems to solve individually and combing solutions to solve main problem (binary and recursive)
write a recursive function that recursively returns fibonacci sequence
def fibonacci(n)
if n in [1,2]:
return 1
else:
return fib(n-1) + (n-2)
write a factorial function that multiples itself by n-1
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
Set
Data Structure used to store and collect unique elements
no defined order
can create through set() or {}
NumPy
Numerical Python, multi-dimensional container for homogeneous data
enable us to perform math operations on WHOLE block of data
can have nested sequences
shape: tuple indicating length
np.random
Submodule for generating random numbers
np.random.randint
used to generate random integers between an interval (low, inclusive, to high, exclusive)
can specify size=(row, height
Pandas
Made to mainly work with labeled data, like spreadsheets
Pandas Series
A one-dimensional array-like object containing a sequence of homogeneous values and an array of data labels (index)
series = pd.Series([ ])
works the same as a dictionary, use labels in the index to select single values (can also make dictionary a series)
math operators work the same as they do on arrays (can operate a whole set)
Boolean Indexing
to print T/F, assign variable a condition
to print only elements that meet said condition, apply new variable to old array/series
my_arr = np.array([1,-1, 2,-3, 4, 5])
positions = my_arr > 0
my_arr[positions]
Using comparison operators for indexing
my_arr = np.array([1, 2,-3, 4, 6,-4, 8])
positive_even_element = my_arr[(my_arr>0) & (my_arr %2 == 0)]
print(positive_even_element)
inside square brackets put two conditions in parenthesis
DataFrame
represents a rectangular table of data and contains an ordered, named collection of columns
can create from a dictionary using pd.DataFrame()
How to access column and row indexes in a Data Frame?
df.columns
df.index
How to access first few rows in a DataFrame?
df.head(n= )
default is 5
how to access last few rows?
df.tail(n= )
how to collect a random collection of data?
df.sample(n= )
how to access a column in a pandas DataFrame?
df[“column name”]
same way we get value in a dictionary
how to access a whole row
row = df.loc[0]
whatever index number
how to access multiple columns in a data frame?
two brackets [[ ]]
data filtering
df[df[“column”] > condition ]
inserting a column in df
df[“column name”] = np.array([ ])
similar to adding a new key-value pair to a dictionary
What’s mutable?
series, dataframes, sets, arrays