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
Q

Determine whether an item is in a list

A

“my item” in myList

26
Q

Delete the second element from a list

A

del myList[1]

27
Q

Delete the second and third elements from a list

A

del myList[1:3]

28
Q

Delete all elements from a list

A

del myList[:]

29
Q

How do you add an element to a tuple

A

You can’t. They’re a fixed size

30
Q

Create a tuple with one item

A

myTuple = (“myItem”,) // OR tuple(“myItem”)
// You must include a comma so Python knows it’s a tuple

31
Q

Given a sentence, create a list of the words

A

words = message.split()

32
Q

Given a list of words, create a sentence from them

A

” “.join(words)

33
Q

Given an array, divide it in half evenly between two separate arrays without using a loop

A

myArray[::2], myArray[1::2]

34
Q

Delete a key from a dictionary

A

del my_dict[“my_key”]
// an error is thrown if the key doesn’t exist

35
Q

Check if a key exists within a dictionary

A

“my_key” in my_dict

36
Q

Increment the value of a dictionary key

A

my_dict[my_key] += 1

37
Q

Iterate through keys in a dictionary

A

for key in my_dict:
pass

38
Q

Determine how many keys are present in a dictionary

A

len(my_dict)

39
Q

Are Python dictionaries ordered?

A

Yes, as of Python version 3.7 (they are unordered in Python 3.6 and earlier)

40
Q

Combine two Python dictionaries

A

first_dict | second_dict

41
Q

How do you create and use a set in Python (including iterating through one)?

A

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
Q

Find all the items that are present in one list but not another

A

list(set(first_list) - set(second_list))
// You can subtract the elements in one Set from another Set using the - operator

43
Q

What are two kinds of errors in Python?

A

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
Q

Handle an exception error

A

try:
10 / 0
except Exception as e:
print(e)

45
Q

How do you throw an error

A

raise Exception(“here is the error”)
// or, raise ValueError(“”) etc

46
Q

How can you check if a variable is an integer, floating point number, or string?

A

type(n) == int
type(n) == float
type(n) == str

47
Q

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

A

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
Q

Convert a string to lowercase

A

“My String”.lower()

49
Q

Remove an item from a list based on value (not index)

A

my_list.remove(value)

50
Q

How do you make a property or method private within a class?

A

Prefix with two underscores, eg self.__armor

51
Q

What is encapsulation?

A

It’s for hiding internal state / implementation details (like private properties and methods)

52
Q

What is abstraction?

A

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
Q

What is inheritance?

A

Allows one class (the “child’) to inherit the properties of another class (the “parent”)

54
Q

Create a cow class that inherits from the animal class

A

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
Q

Create an empty array of n elements

A

[None for _ in range(n)]

56
Q

Sort an array in descending order

A

my_array.sort(reverse=True)

57
Q

Get the absolute value of a number

A

abs(n)

58
Q

Return the value of a given dictionary key, otherwise return null if the key doesn’t exist

A

my_dict.get(key, None)

59
Q

Determine if list contains a value

A

any(value == ‘a’ for value in my_list)

60
Q
A