Python Basics Flashcards
Create function with default argument
def student(firstname, lastname =’Mark’):
pass
Loop through elements in an array
for element in array:
pass
Check if a variable is an array
type(array) is list
Decode and parse a URL
from urllib.parse import urlparse, parseqs
URL=’https://someurl.com/with/query_string?i=main&enc=+Hello’
parsed_url = urlparse(URL)
parse_qs(parsed_url.query)
Increment a variable number by 1
n += 1 (note, n++ is not valid Python syntax)
Return minimum value in array
min(1, 2, 3)
Loop through index and value of elements in an array
for idx, value in enumerate(arr):
pass
Add element to end of list
myList.append(value)
Round a float number to an integer
round(n)
How can you write a number in python using a thousands place delimeter
num = 16_000
How do you indicate that a number is binary?
Prefix with 0b, example 0b0101
What number is this binary value, 10101
The 4 digits represent 16-8-4-2-1
Therefore this is calculated as 16 + 0 + 4 + 0 + 1 = 21
How do you negate / reverse a result?
not True # use the ‘not’ keyword
Write a full if statement with different conditions
if a > b:
pass
elif b > a:
pass
else:
pass
Print numbers 1 through 100
for i in range(1, 101):
print(i)
Print numbers from 100 to 1
for i in range(100, 0, -1):
print(i)
How do you determine the size of a list?
len(myList)
Add a new value to the end of a list
myList.append(‘new value’)
Remove the last element of a list
myList.pop()
Loop through values in a list
for value in [1, 2, 3, 4]:
print(value)
Set variables to the max and min numbers possible
negative_infinity = float(‘-inf’)
positive_infinity = float(‘inf’)
Return every other element from a list
myList[::2]
Return the last 2 elements from a list
myList[-2:]
Combine to lists
[1, 2, 3] + [4, 5, 6]
Determine whether an item is in a list
“my item” in myList
Delete the second element from a list
del myList[1]
Delete the second and third elements from a list
del myList[1:3]
Delete all elements from a list
del myList[:]
How do you add an element to a tuple
You can’t. They’re a fixed size
Create a tuple with one item
myTuple = (“myItem”,) // OR tuple(“myItem”)
// You must include a comma so Python knows it’s a tuple
Given a sentence, create a list of the words
words = message.split()
Given a list of words, create a sentence from them
” “.join(words)
Given an array, divide it in half evenly between two separate arrays without using a loop
myArray[::2], myArray[1::2]
Delete a key from a dictionary
del my_dict[“my_key”]
// an error is thrown if the key doesn’t exist
Check if a key exists within a dictionary
“my_key” in my_dict
Increment the value of a dictionary key
my_dict[my_key] += 1
Iterate through keys in a dictionary
for key in my_dict:
pass
Determine how many keys are present in a dictionary
len(my_dict)
Are Python dictionaries ordered?
Yes, as of Python version 3.7 (they are unordered in Python 3.6 and earlier)
Combine two Python dictionaries
first_dict | second_dict
How do you create and use a set in Python (including iterating through one)?
fruits = {‘apple’, ‘banana’} // or, fruits = set() or fruits = set([‘apple’, ‘banana’])
fruits.add(‘grape’)
fruits.remove(‘apple’)
for fruit in fruits:
pass
// you can also pass a list to a set to convert it, eg set(myList)
Find all the items that are present in one list but not another
list(set(first_list) - set(second_list))
// You can subtract the elements in one Set from another Set using the - operator
What are two kinds of errors in Python?
Syntax errors: code that isn’t adhering to proper Python syntax
Exceptions: an execution error, eg 10 / 0; these can be handled using a try-except pattern
Handle an exception error
try:
10 / 0
except Exception as e:
print(e)
How do you throw an error
raise Exception(“here is the error”)
// or, raise ValueError(“”) etc
How can you check if a variable is an integer, floating point number, or string?
type(n) == int
type(n) == float
type(n) == str
Create a class called wall that has armor value initialized at 10 and a height value initialized at passed in value and a method to double the height
class Wall:
height = 10 // this is a class variable (don’t use them because all instances of this class will share this global value, which can be changed by any of the instances)
def __init__(self, armor):
// this is referred to as the constructor
self.armor = armor // this is an instance variable as it’s specific to an instance
def double_height(self):
Wall.height *= 2
my_wall = Wall(5) // this “object” is called an “instance” of the Wall class
Convert a string to lowercase
“My String”.lower()
Remove an item from a list based on value (not index)
my_list.remove(value)
How do you make a property or method private within a class?
Prefix with two underscores, eg self.__armor
What is encapsulation?
It’s for hiding internal state / implementation details (like private properties and methods)
What is abstraction?
It’s about creating a simple interface for complex behavior that’s easy to use
Getting abstractions right is crucial because changing them later can be disastrous
What is inheritance?
Allows one class (the “child’) to inherit the properties of another class (the “parent”)
Create a cow class that inherits from the animal class
class Animal:
def __init__(self, num_legs):
self.num_legs = num_legs
class Cow(Animal):
def __init__(self):
super().__init__(4) # call the parent constructor
Create an empty array of n elements
[None for _ in range(n)]
Sort an array in descending order
my_array.sort(reverse=True)
Get the absolute value of a number
abs(n)
Return the value of a given dictionary key, otherwise return null if the key doesn’t exist
my_dict.get(key, None)
Determine if list contains a value
any(value == ‘a’ for value in my_list)