Python Basics Flashcards

1
Q

Create function with default argument

A

def student(firstname, lastname =’Mark’):
pass

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Loop through elements in an array

A

for element in array:
pass

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Check if a variable is an array

A

type(array) is list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Decode and parse a URL

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Increment a variable number by 1

A

n += 1 (note, n++ is not valid Python syntax)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Return minimum value in array

A

min(1, 2, 3)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Loop through index and value of elements in an array

A

for idx, value in enumerate(arr):
pass

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Add element to end of list

A

myList.append(value)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Round a float number to an integer

A

round(n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How can you write a number in python using a thousands place delimeter

A

num = 16_000

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you indicate that a number is binary?

A

Prefix with 0b, example 0b0101

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What number is this binary value, 10101

A

The 4 digits represent 16-8-4-2-1
Therefore this is calculated as 16 + 0 + 4 + 0 + 1 = 21

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you negate / reverse a result?

A

not True # use the ‘not’ keyword

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Write a full if statement with different conditions

A

if a > b:
pass
elif b > a:
pass
else:
pass

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Print numbers 1 through 100

A

for i in range(1, 101):
print(i)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Print numbers from 100 to 1

A

for i in range(100, 0, -1):
print(i)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you determine the size of a list?

A

len(myList)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Add a new value to the end of a list

A

myList.append(‘new value’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Remove the last element of a list

A

myList.pop()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Loop through values in a list

A

for value in [1, 2, 3, 4]:
print(value)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Set variables to the max and min numbers possible

A

negative_infinity = float(‘-inf’)
positive_infinity = float(‘inf’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Return every other element from a list

A

myList[::2]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Return the last 2 elements from a list

A

myList[-2:]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Combine to lists

A

[1, 2, 3] + [4, 5, 6]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Determine whether an item is in a list
"my item" in myList
26
Delete the second element from a list
del myList[1]
27
Delete the second and third elements from a list
del myList[1:3]
28
Delete all elements from a list
del myList[:]
29
How do you add an element to a tuple
You can't. They're a fixed size
30
Create a tuple with one item
myTuple = ("myItem",) // OR tuple("myItem") // You must include a comma so Python knows it's a tuple
31
Given a sentence, create a list of the words
words = message.split()
32
Given a list of words, create a sentence from them
" ".join(words)
33
Given an array, divide it in half evenly between two separate arrays without using a loop
myArray[::2], myArray[1::2]
34
Delete a key from a dictionary
del my_dict["my_key"] // an error is thrown if the key doesn't exist
35
Check if a key exists within a dictionary
"my_key" in my_dict
36
Increment the value of a dictionary key
my_dict[my_key] += 1
37
Iterate through keys in a dictionary
for key in my_dict: pass
38
Determine how many keys are present in a dictionary
len(my_dict)
39
Are Python dictionaries ordered?
Yes, as of Python version 3.7 (they are unordered in Python 3.6 and earlier)
40
Combine two Python dictionaries
first_dict | second_dict
41
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)
42
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
43
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
44
Handle an exception error
try: 10 / 0 except Exception as e: print(e)
45
How do you throw an error
raise Exception("here is the error") // or, raise ValueError("") etc
46
How can you check if a variable is an integer, floating point number, or string?
type(n) == int type(n) == float type(n) == str
47
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
48
Convert a string to lowercase
"My String".lower()
49
Remove an item from a list based on value (not index)
my_list.remove(value)
50
How do you make a property or method private within a class?
Prefix with two underscores, eg self.__armor
51
What is encapsulation?
It's for hiding internal state / implementation details (like private properties and methods)
52
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
53
What is inheritance?
Allows one class (the "child') to inherit the properties of another class (the "parent")
54
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
55
Create an empty array of n elements
[None for _ in range(n)]
56
Sort an array in descending order
my_array.sort(reverse=True)
57
Get the absolute value of a number
abs(n)
58
Return the value of a given dictionary key, otherwise return null if the key doesn't exist
my_dict.get(key, None)
59
Determine if list contains a value
any(value == 'a' for value in my_list)
60