Ken Yuan Python Flashcards Preview

Data Sci/Programming > Ken Yuan Python > Flashcards

Flashcards in Ken Yuan Python Deck (129):

what's a variables

Creating web apps, games, and search engines all involve storing and working with different types of data. They do so using variables. A variable stores a piece of data, and gives it a specific name. For example:spam = 5 The variable spam now stores the number 5.



Numbers are one data type we use in programming. A second data type is called a boolean. A boolean is like a light switch. It can only have two values. Just like a light switch can only be on or off, a boolean can only be True or False. You can use variables to store booleans like this: a = True b = False


The # sign

The # sign is for comments. A comment is a line of text that Python won't try to run as code. It's just for humans to read. Comments make your program easier to understand. When you look back at your code or others want to collaborate with you, they can read your comments and easily figure out what your code does.


multi-line comments

starting each line with # can be a pain. Instead, for multi-line comments, you can include the whole block in a set of triple quotation marks: """Sipping from your cup 'til it runneth over, Holy Grail. """


2 to the power of 3

variable = 2 ** 3 Notice that we use ** instead of * or the multiplication operator.



Modulo returns the remainder from a division. So, if you type variable = 3 % 2 , it will return 1, because 2 goes into 3 evenly once, with 1 left over.


What's wrong with the code 'There's a snake in my boot!'

This code breaks because Python thinks the apostrophe in 'There's' ends the string. We can use the backslash to fix the problem, like this: 'There\'s a snake in my boot!'


HOW TO Access by Index

So if you wanted "Y", you could just type "PYTHON"[1] (always start counting from 0!)


String methods

String methods let you perform specific tasks for strings. len() - gets the length (the number of characters) of a string! lower() - get rid of all the capitalization in your strings. upper() - turn all characters upper case in your strings str() - The str() method turns non-strings into strings!


why you use len(string) and str(object), but dot notation (such as "String".upper()) for the rest. e.g. lion = "roar" len(lion) lion.upper()

Methods that use dot notation only work with strings. On the other hand, len() and str() can work on other data types.


String Concatenation

print "Life " + "of " + "Brian" This will print out the phrase Life of Brian. The + operator between strings will 'add' them together, one after the other. Notice that there are spaces inside the quotation marks after Life and of so that we can make the combined string look like 3 words.


combine a string with something that isn't a string

In order to do that, you have to convert the non-string into a string. print "I have " + str(2) + " coconuts!"


When you want to print a variable with a string, there is a better method than concatenating strings together.

Method is called string substitution string_1 = "Camelot" string_2 = "place" print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2) returns - Let's not go to Camelot. 'Tis a silly place. The % operator after a string is used to combine a string with variables. The % operator will replace a %s in the string with the string variable that comes after it.


Three ways to create strings

'Alpha' "Bravo" str(3)


Getting the Current Date and Time

We can use a function called to retrieve the current date and time. # code from datetime import datetime print The first line imports the datetime library so that we can use it.The second line will print out the current date and time. What if you don't want the entire date and time? # code print now.year only prints current year. same applies to month, day, hour, minute, and second.


What if we want to print today's date in the following format? mm/dd/yyyy

Let's use string substitution again! # code from datetime import datetime now = print '%s-%s-%s' % (now.year, now.month, # will print: 2014-02-19


the simplest aspect of control flow: comparators.

Comparators check if a value is (or is not) equal to, greater than (or equal to), or less than (or equal to) another value. Comparisons result in either True or False, which are booleans` equal to (==) -Note that == compares whether two things are equal, and = assigns a value to a variable. Not equal to (!=) Less than () Greater than or equal to (>=)


Boolean operators

Boolean operators compare statements and result in boolean values. There are three boolean operators: 1. and, which checks if both the statements are True; 2. or, which checks if at least one of the statements is True; 3. not, which gives the opposite of the statement.


order of operations for boolean operators:

not is evaluated first; and is evaluated next; or is evaluated last. For example, True or not False and False returns True. Parentheses () ensure your expressions are evaluated in the order you want. Anything in parentheses is evaluated as its own unit.


An if/else pair says what?

An if/else pair says "If this expression is true, run this indented code block; otherwise, run this code after the else statement." Unlike if, else doesn't depend on an expression. For example: if 8 > 9: print "I don't printed!" else: print "I get printed!"



elif is short for "else if." It means exactly what it sounds like: "otherwise, if the following expression is true, do this!" Remember that an elif statement is only checked if all preceding if/elif statements fail. if 8 > 9: print "I don't get printed!" elif 8 < 9: print "I get printed!" else: print "I also don't get printed!"


input statement

name = raw_input("What's your name?") print name In the above example, raw_input() accepts a string, prints it, and then waits for the user to type something and press Enter (or Return). In the interpreter, Python will ask: What's your name? Once you type in your name and hit Enter, it will be stored in name.


how to check that the user's string actually has characters!

original = raw_input("enter a word?") print original if len(original) > 0: print original else: print "empty"



returns False when the string contains non-letter characters.e.g. original = raw_input("Enter a word:") if len(original) > 0 and original.isalpha(): print original else: print "empty"



the_string = "Hello" the_string = the_string.lower() The .lower() function does not modify the string itself, it simply returns a lowercase-version. In the example above, we store the result back into the same variable.



A function is a reusable section of code written to perform a specific task in a program. Instead of rewriting the whole code, it's much cleaner to define a function, which can then be used repeatedly. functions that can print text or do simple arithmetic, but functions can be much more powerful than that. For example, a function can call another function:


Functions are defined with three components

1. The header, which includes the def keyword, the name of the function, and any parameters the function requires. e.g. def square(n): A function can require as many parameters as you'd like, but when you call the function, you should generally pass in a matching number of arguments. 2. An optional comment that explains what the function does. 3. The body, which describes the procedures the function carries out. The body is indented, just like conditional statements.



A module is a file that contains definitions—including variables and functions—that you can use once it is imported.


# code import math print math.sqrt(25)

This tells Python not only to import math module(see module def) , but to get the sqrt() function from within math


what are diff types of Imports for modules

1. Generic Imports # code import math print math.sqrt(100) 2. Function Imports - Pulling in just a single function from a module is called a function import, and it's done with the from keyword: from module import function - #code from math import sqrt print sqrt(100) 3. Universal Imports - What if we still want all of the variables and functions in a module but don't want to have to constantly type math.? Universal import can handle this for you #code from math import * print sqrt(100)

The difference between import module and from module import foo is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.

import module


Less maintenance of your import statements. Don't need to add any additional imports to start using another item from the module


Typing in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing

from module import foo


Less typing to use foo

More control over which items of a module can be accessed


To use a new item from the module you have to update your import statement

You lose context about foo. For example, it's less clear what ceil() does compared to math.ceil()

Either method is acceptable, but don't use from module import *.

For any reasonable large set of code, if you import * you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use the import any more but it's extremely difficult to be sure.


functions - max(), min(), abs() ,

it's best to use max() on integers and floats, where the results are straightforward, and not on other objects, like strings. abs() function returns the absolute value


type() function

returns the type of the data it receives as an argument. If you ask Python to do the following: print type(42) print type(4.2) print type('spam') Python will output:


The example defines the function fruit_color that accepts a string as the argument fruit. The function returns a string if it knows the color of that fruit.

elif lets you test more than one conditions def fruit_color(fruit): if fruit == "apple": return "red" elif fruit == "banana": return "yellow" elif fruit == "pear": return "green"


a += b , a -= b

a += b or a -= b is essentially the same as a = a + b or a = a - b


Calculate the cost of renting the car: Every day you rent the car costs $40. if you rent the car for 7 or more days, you get $50 off your total. Alternatively (elif), if you rent the car for 3 or more days, you get $20 off your total. You cannot get both of the above discounts. Return that cost.

def rental_car_cost(days): cost = days * 40 if days >= 7: cost -= 50 elif days >= 3: cost -= 20 return cost


what are Lists

Lists are a datatype you can use to store a collection of different pieces of information as a sequence under a single variable name. (Datatypes you've already learned about include strings, numbers, and booleans.) You can assign items to a list with an expression of the form list_name = [item_1, item_2] with the items in between brackets. A list can also be empty: empty_list = [].


how to access an individual item on the list by its index.

List indices begin with 0, not 1! You access the first item in a list like this: list_name[0]. The second item in a list is at index 1: list_name[1] e.g. numbers = [5, 6, 7, 8], numbers[0] returns 5


A list doesn't have to have a fixed length. You can add items to the end of a list any time you like! but how?

letters = ['a', 'b', 'c'] letters.append('d')


What does this return letters = ['a', 'b', 'c', 'd', 'e'] slice = letters[1:3]

['b', 'c'], it's called List Slicing You can slice a string exactly like a list! In fact, you can think of strings as lists of characters: each character is a sequential item in the list, starting from index 0. my_list[:2] # Grabs the first two items my_list[3:] # Grabs the fourth through last items


how to search for an item's position in a list.

animals = ["ant", "bat", "cat"] print animals.index("bat") First, we create a list called animals with three strings. Then, we print the first index that contains the string "bat", which will print 1.


how to insert items into a list.

animals = ["ant", "bat", "cat"] animals.insert(1, "dog") print animals We insert "dog" at index 1, which moves everything down by 1. We print out ["ant", "dog", "bat", "cat"] Here the number comes before the information you're trying to insert, because that's the most efficient way the computer can perform the task


animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] How to change the list to - ['aardvark', 'badger', 'cobra', 'duck', 'emu', 'fennec fox'] using list index and list insert functions

duck_index = animals.index("duck")# Use index() to find "duck" animals.insert(duck_index, "cobra")


what does for loop do

for variable in list_name: # Do stuff! A variable name follows the for keyword; it will be assigned the value of each list item in turn. Then in list_name designates list_name as the list the loop will work on. The line ends with a colon (:) and the indented code that follows it will be executed once per item in the list.


start_list = [5, 3, 1, 2, 4] square_list = [] Write a for-loop that iterates over start_list and .append()s each number squared (x ** 2) to square_list. Then sort square_list!

# Your code here! for number in start_list: square_list.append(number ** 2) square_list.sort() print square_list it returns [1, 4, 9, 16, 25]


what is a dictionary

A dictionary is similar to a list, but you access values by looking up a key instead of an index. A key can be any string or number. Dictionaries are enclosed in curly braces, like so: d = {'key1' : 1, 'key2' : 2, 'key3' : 3} This is a dictionary called d with three key-value pairs. The key 'key1' points to the value 1, 'key2' to 2, and so on. #code residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} print residents['Puffin'] gives you 104, the value stored under the 'Puffin' Dictionaries are great for things like phone books (pairing a name with a phone number), login pages (pairing an e-mail address with a username), and more!


An empty pair of curly braces {}

is an empty dictionary, just like an empty pair of [] is an empty list.


Like Lists, Dictionaries are mutable. This means they can be changed after they are created. One advantage of this is that we can add new key/value pairs to the dictionary after it is created. how

dict_name[new_key] = new_value


The length len() of a dictionary is what

the number of key-value pairs it has. Each pair counts only once, even if the value is a list. (That's right: you can put lists inside dictionaries!)


Items can be removed from a dictionary with the del command. how

del dict_name[key_name] will remove the key key_name and its associated value from the dictionary.


Items can be removed from a list with the remove command. how

beatles = ["john","paul","george","ringo","stuart"] beatles.remove("stuart") print beatles This code will print: ["john","paul","george","ringo"]


What does this print my_dict = { "fish": ["c", "a", "r", "p"], "cash": -4483, "luck": "good" } print my_dict["fish"][0]



for loop on a dictionary to loop through its keys with the following: # A simple dictionary d = {"foo" : "bar"}

for key in d: print d[key] # prints "bar" Note that dictionaries are unordered, meaning that any time you loop through a dictionary, you will go through every key, but you are not guaranteed to get them in any particular order.


Explain the code Below in words numbers = [1, 3, 4, 7] for number in numbers: if number > 6: print number print "We printed 7."

In the above example, we create a list with 4 numbers in it. Then we loop through the numbers list and store each item in the list in the variable number. On each loop, if number is greater than 6, we print it out. So, we print 7. Finally, we print out a sentence. Make sure to keep track of your indentation or you may get confused!


what is String Looping

Strings are like lists with characters as elements. You can loop through strings the same way you loop through lists!


how to use def sum(n): to cal the sum of numbers in the list called n

def sum(numbers): total = 0 for number in numbers: total += number return total n = [1, 2, 5, 10, 13] print sum(n)


5 / 2 # 2 5.0 / 2 # 2.5 how to make 5/2 = 2.5?

float(5) / 2 # 2.5 When you divide an integer by another integer, the result is always an integer (rounded down, if needed). When you divide a float by an integer, the result is always a float. To divide two integers and end up with a float, you must first use float() to convert one of the integers to a float.


The \ character

The \ character is a continuation character. The following line is considered a continuation of the current line.


Append the number 4 to the end of the list n = [1, 3, 5]



diff btwn n.pop(index), n.remove(item) and del(n[1])

n.pop(index) will remove the item at index from the list and return it to you: e.g. n = [1, 3, 5] n.pop(1) # Returns 3 (the item at index 1) print n # prints [1, 5] n.remove(item) will remove the actual item if it finds it e.g. n.remove(1) # Removes 1 from the list, # NOT the item at index 1 print n # prints [3, 5] del(n[1]) is like .pop in that it will remove the item at the given index, but it won't return it: e.g. del(n[1]) # Doesn't return anything print n # prints [1, 5]


Create a function called double_list that takes a single argument x (which will be a list) and multiplies each element by 2 and returns that list.

n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x # Don't forget to return your new list!


The range function has three different versions: range(stop) range(start, stop) range(start, stop, step) explain

In all cases, the range() function returns a list of numbers from start up to (but not including) stop. Each item increases by step. If omitted, start defaults to 0 and step defaults to 1. range(6) # => [0, 1, 2, 3, 4, 5] range(1, 6) # => [1, 2, 3, 4, 5] range(1, 6, 3) # => [1, 4]


we have two ways of iterating through a list.

Method 1 - for item in list: for item in list: print item Method 2 - iterate through indexes: for i in range(len(list)): print list[i] Method 1 is useful to loop through the list, but it's not possible to modify the list this way. Method 2 uses indexes to loop through the list, making it possible to also modify the list if needed.


Create a function that concatenates strings. n = ["Michael", "Lieberman"]

def join_strings(words): result = "" for x in words: result += x return result print join_strings(n) #gives you MichaelLieberman


for list_of_lists = [[1, 2, 3], [4, 5, 6]] how to iterate and print 1 2 3 4 5 6

list_of_lists = [[1, 2, 3], [4, 5, 6]] for lst in list_of_lists: for item in lst: print item


for n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]], how to Create a function called flatten that takes a single list and concatenates all the sublists that are part of it into a single list.

def flatten(lists): results = [] for numbers in lists: for number in numbers: results.append(number) return results print flatten(n) or def flatten(lists): results = [] for y in lists: results += y return results print flatten(n)


think about what this returns and explain what join function does letters = ['a', 'b', 'c', 'd']

print " ".join(letters)

print "---".join(letters)

In the example above, we create a list called letters. Then, we print a b c d. The .join method uses the string to combine the items in the list. Finally, we print a---b---c---d. We are calling the .join function on the "---" string.


Explain the while loop and compare it to if statement

he while loop is similar to an if statement: it executes the code inside of it if some condition is true. The difference is that the while loop will continue to execute as long as the condition is true. In other words, instead of executing if something is true, it executes while that thing is true. # code count = 0 if count < 5: print "Hello, I am an if statement and count is", count while count < 5: print "Hello, I am a while and count is", count count += 1 Line 6 decides when the loop will be executed. So, "as long as count is less than 5," the loop will continue to execute. Line 8 increases count by 1. This happens over and over until count equals 5.


explain the code below , starting with the sentence - There are 5 steps to this program... loop_condition = True while loop_condition: print "I am a loop" loop_condition = False

The loop_condition variable is set to True The while loop checks to see if loop_condition is True. It is, so the loop is entered. The print statement is executed. The variable loop_condition is set to False. The while loop again checks to see if loop_condition is True. It is not, so the loop is not executed a second time.


What's an infinite Loop and what are the two things that could cause it

An infinite loop is a loop that never exits. This can happen for a few reasons: The loop condition cannot possibly be false (e.g. while 1 != 2) The logic of the loop prevents the loop condition from becoming false.


What is Break?

The break is a one-line statement that means "exit the current loop.". e.g. - this code would print out 0 to 9 count = 0 while True: print count count += 1 if count >= 10: break


while/else is similar to if/else, but there is a difference, what?

the else block will execute anytime the loop condition is evaluated to False. This means that it will execute if the loop is never entered or if the loop exits normally. If the loop exits as the result of a break, the else will not be executed.


raw_input turns user input into a what data type?

string, we could use int() to make it a number again If needed


Recall and visualize the exercise that first generate a random number Between 1 and 10 , and then , allow the user to guess what the number is 3 times, using while and else construction - Pay attention to indentation

from random import randint

# Generates a number from 1 through 10 inclusive

random_number = randint(1, 10)

guesses_left = 3

# Start your game!

while guesses_left > 0:

    guess = int(raw_input("Your guess: "))

    if guess == random_number:

        print "You win!"


    guesses_left -= 1

else: print "You lose."


#code phrase = "A bird in the hand..." how to write code to print out this - X b i r d i n t h e h X n d . . .

for char in phrase: if char == "A" or char == 'a': print 'X', else: print char, # The , character after our print statement means that our next print statement keeps printing on the same line.


when looping over a dictionary would work. Would you get the key or the value?

The short answer is: you get the key which you can use to get the value. e.g. d = {'x': 9, 'y': 10, 'z': 20} for key in d: if d[key] == 10: print "This dictionary has the value 10!"


It is useful to know how far into the list you are. enumerate works by supplying a corresponding index to each element in the list that you pass it. Each time you go through the loop, index will be one greater, and item will be the next item in the sequence. It's very similar to using a normal for loop with a list, except this gives us an easy way to count how many items we've seen so far. w/ this list - choices = ['pizza', 'pasta', 'salad', 'nachos'], How do you print out the following - Your choices are: 0 pizza 1 pasta 2 salad 3 nachos

choices = ['pizza', 'pasta', 'salad', 'nachos'] print 'Your choices are:' for index, item in enumerate(choices): print index, item


what does the built-in zip function do?

It's also common to need to iterate over two lists at once. This is where the built-in zip function comes in handy. zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list. zip can handle three or more lists as well! e.g. #code list_a = [3, 9, 17, 15, 19] list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90] for a, b in zip(list_a, list_b): print max(a, b), #prints out 3 9 17 15 30


Just like with while, for loops may have an else associated with them. What does this code print - fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape'] print 'You have...' for f in fruits: if f == 'tomato': print 'A tomato is not a fruit!' # (It actually is.) break print 'A', f else: print 'A fine selection of fruits!'

You have... A banana A apple A orange A tomato is not a fruit! In this case, the else statement is executed after the for, but only if the for ends normally—that is, not with a break. This code will break when it hits 'tomato', so the else block won't be executed.



four spaces is a typical amount of indentation for Python. In most other programming languages, indentation is used only to help make the code look pretty. But in Python, it is required for indicating what block of code a statement belongs to.


Define a function is_even that will take a number x as input. If x is even, then return True. Otherwise, return False.

def is_even(x): if x % 2 == 0: return True else: return False


Define a function called is_prime that takes a number x as input.

def is_prime(x): if x < 2: return False else: for n in range(2, x-1): if x % n == 0: return False return True


Define a function called reverse that takes a string textand returns that string in reverse. For example: reverse("abcd") should return "dcba". You may not use reversed or [::-1] to help you with this. You may get a string containing special characters (for example, !, @, or #).

def reverse(text): word = "" l = len(text) - 1 while l >= 0: word = word + text[l] l -= 1 return word


score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10} Define a function scrabble_score that takes a string word as input and returns the equivalent scrabble score for that word. Assume your input is only one word containing no spaces or punctuation. As mentioned, no need to worry about score multipliers! Your function should work even if the letters you get are uppercase, lowercase, or a mix. Assume that you're only given non-empty strings.

def scrabble_score(word): word = word.lower() total = 0 for letter in word: for leter in score: if letter == leter: total = total + score[leter] return total


rite a function called censor that takes two strings, text and word, as input. It should return the text with the word you chose replaced with asterisks. For example: censor("this hack is wack hack", "hack") should return: "this **** is wack ****"

def censor(text, word): words = text.split() result = '' stars = '*' * len(word) count = 0 for i in words: if i == word: words[count] = stars count += 1 result =' '.join(words) return result


Define a function called count that has two arguments called sequence and item. Return the number of times the item occurs in the list. For example: count([1, 2, 1, 1], 1) should return 3 (because 1 appears 3 times in the list).

def count(sequence, item): count = 0 for i in sequence: if i == item: count += 1 return count


a. Define a function called purify that takes in a list of numbers, removes all odd numbers in the list, and returns the result. For example, purify([1,2,3]) should return [2]. Do not directly modify the list you are given as input; instead, return a new list with only the even numbers.

def purify(lst): res = [] for ele in lst: if ele % 2 == 0: res.append(ele) return res


Write a function remove_duplicates that takes in a list and removes elements of the list that are the same. For example: remove_duplicates([1, 1, 2, 2]) should return [1, 2]. Don't remove every occurrence, since you need to keep a single occurrence of a number. The order in which you present your output does not matter. So returning [1, 2, 3] is the same as returning [3, 1, 2]. Do not modify the list you take as input! Instead, return a new list.

def remove_duplicates(inputlist): if inputlist == []: return [] # Sort the input list from low to high inputlist = sorted(inputlist) # Initialize the output list, and give it the first value of the now-sorted input list outputlist = [inputlist[0]] # Go through the values of the sorted list and append to the output list # ...any values that are greater than the last value of the output list for i in inputlist: if i > outputlist[-1]: outputlist.append(i) return outputlist


How does sorted function work

sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5]


Write a function called median that takes a list as an input and returns the median value of the list. For example: median([1, 1, 2]) should return 1. The list can be of any size and the numbers are not guaranteed to be in any particular order. Make sure to sort it! If the list contains an even number of elements, your function should return the average of the middle two.

def median(lst): sorted_list = sorted(lst) if len(sorted_list) % 2 != 0: #odd number of elements index = len(sorted_list)//2 return sorted_list[index] elif len(sorted_list) % 2 == 0: #even no. of elements index_1 = len(sorted_list)/2 - 1 index_2 = len(sorted_list)/2 mean = (sorted_list[index_1] + sorted_list[index_2])/2.0 return mean print median([2, 4, 5, 9])


The method .items()

The method items() returns a list (It turns the dictionary into a list)of dict's (key, value) tuple pairs, not in any specific order. You can think of a tuple as an immutable (that is, unchangeable) list. Tuples are surrounded by ()s and can contain any data type. #code dict.items() dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.items() #the program produces following result − Value : [('Age', 7), ('Name', 'Zara')]


compare these three methods .items() , .keys() , .values()

While .items() returns an array of tuples with each tuple consisting of a key/value pair from the dictionary The .keys() method returns a list of the dictionary's keys, and , not in any specific order. The .values() method returns a list of the dictionary's values , not in any specific order.


for loop can be used to iterate over lists, tuples, dictionaries, and strings. Think of examples

for number in range(5): print number, d = { "name": "Eric", "age": 26 } for key in d: print key, d[key], for letter in "Eric": print letter, # note the comma!


to build a list of the numbers from 0 to 50 (inclusive).

my_list = range(51)


What is list comprehension

List comprehensions are a powerful way to generate lists using the for/in and if keywords we've learned. e.g. evens_to_50 = [i for i in range(51) if i % 2 == 0] print evens_to_50 returns [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50] another e.g. oubles = [x * 2 for x in range(1, 6)] # => [2, 4, 6, 8, 10]


List Slicing - Recall what it is used for and its syntax

Sometimes we only want part of a Python list. Maybe we only want the first few elements; maybe we only want the last few. Maybe we want every other element! List slicing allows us to access elements of a list in a concise manner. The syntax looks like this: [start:end:stride] Where start describes where the slice starts (inclusive), end is where it ends (exclusive), and stride describes the space between items in the sliced list. For example, a stride of 2 would select every other item from the original list to place in the sliced list. e.g. l = [i ** 2 for i in range(1, 11)] # Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] print l[2:9:2] #returns - [9, 25, 49, 81]


If you don't pass a particular index to the list slice, Python will pick a default. hoe does it work?

The default starting index is 0. The default ending index is the end of the list. The default stride is 1. e.g. to_five = ['A', 'B', 'C', 'D', 'E'] print to_five[3:] # prints ['D', 'E'] print to_five[:2] # prints ['A', 'B'] print to_five[::2] # print ['A', 'C', 'E']


how to reverse a List

A negative stride progresses through the list from right to left. letters = ['A', 'B', 'C', 'D', 'E'] print letters[::-1] In the example above, we print out ['E', 'D', 'C', 'B', 'A'].


what is an anonymous function.

Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda". This is not exactly the same as lambda in functional programming languages, but it is a very powerful concept that's well integrated into Python and is often used in conjunction with typical functional concepts like filter(), map() and reduce().

This piece of code shows the difference between a normal function definition ("f") and a lambda function ("g"):

>>> def f (x): return x**2
>>> print f(8)


>>> g = lambda x: x**2
>>> print g(8)


As you can see, f() and g() do exactly the same and can be used in the same ways. Note that the lambda definition does not include a "return" statement -- it always contains an expression which is returned. Also note that you can put a lambda definition anywhere a function is expected, and you don't have to assign it to a variable at all.


when to use lambda functions vs regular functions? ``

Lambdas are useful when you need a quick function to do some work for you. If you plan on creating a function you'll use over and over, you're better off using def and giving that function a name.


The string is garbled in two ways: garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI" Our message is backwards. The letter we want is every other letter. Use list slicing to extract the message and save it to a variable called message.

message = garbled[::-2]


What are Bitwise operations

Bitwise operations are operations that directly manipulate bits. In all computers, numbers are represented with bits, a series of zeros and ones. In fact, pretty much everything in a computer is. To be honest, you aren't really going to see bitwise operators in everyday


What does bin() function do?

bin() takes an integer as input and returns the binary representation of that integer in a string. (Keep in mind that after using the bin function, you can no longer operate on the value like a number.)


left and right shift bitwise operators

These operators work by shifting the bits of a number over by a designated number of slots. The block below shows how these operators work on the bit level. Note that in the diagram, the shift is always a positive integer: # Left Bit Shift (<>) 0b0010100 >> 3 == 0b000010 (20 >> 3 = 2) 0b0000010 >> 2 == 0b000000 (2 >> 2 = 0) it's often easier just to think of it as shifting all the 1s and 0s left or right by the specified number of slots.


The bitwise AND (&amp;) operator

The bitwise AND (&amp;) operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if the corresponding bits of both numbers are 1. For example: a: 00101010 42 b: 00001111 15 =================== a &amp; b: 00001010 10


The bitwise OR (|) operator

The bitwise OR (|) operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of either number are 1. For example: a: 00101010 42 b: 00001111 15 ================ a | b: 00101111 47 Note that the bitwise | operator can only create results that are greater than or equal to the larger of the two integer inputs.


The XOR (^) or exclusive or operator

The XOR (^) or exclusive or operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of the two numbers are 1, but not both. a: 00101010 42 b: 00001111 15 ================ a ^ b: 00100101 37 Keep in mind that if a bit is off in both numbers, it stays off in the result. Note that XOR-ing a number with itself will always result in 0.


The bitwise NOT operator (~)

The bitwise NOT operator (~) just flips all of the bits in a single number. What this actually means to the computer is actually very complicated, so we're not going to get into it. Just know that mathematically, this is equivalent to adding one to the number and then making it negative. e.g. print ~1 print ~42 -2 -43


A bit mask is just a variable that aids you with bitwise operations. what can it do?

A bit mask can help you turn specific bits on, turn others off, or just collect data from an integer about which bits are on or off. num = 0b1100 mask = 0b0100 desired = num &amp; mask if desired > 0: print "Bit was on" You can also use masks to turn a bit in a number on using |. For example, let's say I want to make sure the rightmost bit of number a is turned on. I could do this: a = 0b110 # 6 mask = 0b1 # 1 desired = a | mask # 0b111, or 7 Using the bitwise | operator will turn a corresponding bit on if it is off and leave it on if it is already on. Using the XOR (^) operator is very useful for flipping bits. Using ^ on a bit with the number one will return a result where that bit is flipped. For example, let's say I want to flip all of the bits in a. I might do this: a = 0b110 # 6 mask = 0b111 # 7 desired = a ^ mask # 0b1 Finally, you can also use the left shift (<>) operators to slide masks into place. a = 0b101 # Tenth bit mask mask = (0b1 << 9) # One less than ten desired = a ^ mask Let's say that I want to turn on the 10th bit from the right of the integer a. Instead of writing out the entire number, we slide a bit over using the << operator. We use 9 because we only need to slide the mask nine places over from the first bit to reach the tenth bit.


Definition of an object and a class

Python is an object-oriented programming language, which means it manipulates programming constructs called objects. You can think of an object as a single data structure that contains data as well as functions; the functions of an object are called its methods. The fact that they're instances of the str and dict classes, respectively. A class is just a way of organizing and producing objects with similar attributes and methods.


What is the construct of Class Syntax

A basic class consists only of the class keyword, the name of the class, and the class from which the new class inherits in parentheses. (We'll get to inheritance soon.) For now, our classes will inherit from the object class, like so: class NewClass(object): # Class magic here This gives them the powers and abilities of a Python object. By convention, user-defined Python class names start with a capital letter.


What is the the pass keyword.

pass doesn't do anything, but it's useful as a placeholder in areas of your code where Python expects an expression. e.g. class Animal(object): pass


What is __init__() function

This function is required for classes, and it's used to initialize the objects it creates. __init__() always takes at least one argument, self, that refers to the object being created. You can think of __init__() as the function that "boots up" each object the class creates.


What is the first parameter of __init__() , And what does it do

self. This is a Python convention; there's nothing magic about the word self. However, it's overwhelmingly common to use self as the first parameter in __init__(), so you should do this so that other people will understand your code. The part that is magic is the fact that self is the first parameter passed to __init__(). Python will use the first parameter that __init__() receives to refer to the object being created; this is why it's often called self, since this parameter gives the object being created its identity. # Note that self is only used in the __init__() # function definition; we don't need to pass it # to our instance objects.


After Self, what other arguments does __init__() take?

The first argument __init__() gets is used to refer to the instance object, and by convention, that argument is called self. If you add additional arguments—for instance, a name and age for your animal—setting each of those equal to and self.age in the body of __init__() will make it so that when you create an instance object of your Animal class, you need to give each instance a name and an age, and those will be associated with the particular instance you create. e.g # Class definition class Animal(object): """Makes cute animals.""" # For initializing our instance objects def __init__(self, name, age, is_hungry): = name self.age = age self.is_hungry = is_hungry zebra = Animal("Jeffrey", 2, True) giraffe = Animal("Bruce", 1, False) panda = Animal("Chad", 7, True) print, zebra.age, zebra.is_hungry Returns Jeffrey 2 True


what is the scope of a variable

The scope of a variable is the context in which it's visible to the program. It may surprise you to learn that not all variables are accessible to all parts of a Python program at all times. When dealing with classes, you can have variables that are available everywhere (global variables), variables that are only available to members of a certain class (member variables), and variables that are only available to particular instances of a class (instance variables). The same goes for functions: some are available everywhere, some are only available to members of a certain class, and still others are only available to particular instance objects.e.g. ote that each individual animal gets its own name and age (since they're all initialized individually), but they all have access to the member variable is_alive, since they're all members of the Animal class. class Animal(object): """Makes cute animals.""" is_alive = True def __init__(self, name, age): = name self.age = age zebra = Animal("Jeffrey", 2) giraffe = Animal("Bruce", 1) panda = Animal("Chad", 7) print, zebra.age, zebra.is_alive returns - Jeffrey 2 True


What are methods

When a class has its own functions, those functions are called methods.


class Animal(object): """Makes cute animals."""

is_alive = True

    def __init__(self, name, age): = name

        self.age = age

Add a method, description, to your Animal class. Using two separate print statements, it should print out the name and age of the animal it's called on. Then, create an instance of Animal, hippo (with whatever name and age you like), and call its description method.

# Add your method here! def description(self): print print self.age hippo = Animal("Anderson", 36) hippo.description()


Try to understand the code on the right - The code in the editor is a more realistic demonstration of the kind of classes and objects you might find in commercial software. Here we have a basic ShoppingCart class for creating shopping cart objects for website customers; though basic, it's similar to what you'd see in a real program.

after attached

Create an instance of ShoppingCart called my_cart. Initialize it with any values you like, then use the add_item method to add an item to your cart.

my_cart = ShoppingCart("Eric")
my_cart.add_item("Ukelele", 10)

returns "Ukelele added."

A image thumb

explain Inheritance process 

Inheritance is the process by which one class takes on the attributes and methods of another, and it's used to express an is-a relationship. For example, a Panda is a bear, so a Panda class could inherit from a Bear class. However, a Toyota is not a Tractor, so it shouldn't inherit from the Tractor class (even if they have a lot of attributes and methods in common). Instead, both Toyota and Tractor could ultimately inherit from the same Vehicle class.


Understand code on inheritance

class Customer(object):
    """Produces objects that represent customers."""
    def __init__(self, customer_id):
        self.customer_id = customer_id

    def display_cart(self):
        print "contents of your shopping cart!"

class ReturningCustomer(Customer):
    """For customers of the repeat variety."""
    def display_order_history(self):
        print "order history!"

monty_python = ReturningCustomer("ID: 12345")


contents of your shopping cart!

order history!

We've defined a class, Customer, as well as a ReturningCustomer class that inherits from Customer. Note that we don't define the display_cart method in the body of ReturningCustomer, but it will still have access to that method via inheritance. 


What is the Inheritance Syntax

In Python, inheritance works like this:

class DerivedClass(BaseClass):

# code goes here

where DerivedClass is the new class you're making and BaseClass is the class from which that new class inherits.


Sometimes you'll want one class that inherits from another to not only take on the methods and attributes of its parent, but to override one or more of them. Describe how override works in the example below

class Employee(object):

    def __init__(self, name): = name

    def greet(self, other):

        print "Hello, %s" %

class CEO(Employee):

    def greet(self, other):

        print "Get back to work, %s!" %

ceo = CEO("Emily")

emp = Employee("Steve")

emp.greet(ceo) # Hello, Emily

ceo.greet(emp) # Get back to work, Steve!

Rather than have a separate greet_underling method for our CEO, we override (or re-create) the greet method on top of the base Employee.greet method. This way, we don't need to know what type of Employee we have before we greet another Employee.


sometimes you'll be working with a derived class (or subclass) and realize that you've overwritten a method or attribute defined in that class' base class (also called a parent or superclass) that you actually need.  what do you do now?


You can directly access the attributes or methods of a superclass with Python's built-in super call.

The syntax looks like this, where m() is a method from the base class

class Derived(Base):

    def m(self):

        return super(Derived, self).m()

#See example below

class Employee(object):
  """Models real-life employees!"""
  def __init__(self, employee_name):
    self.employee_name = employee_name

  def calculate_wage(self, hours):
    self.hours = hours
    return hours * 20.00

class PartTimeEmployee(Employee):
  def calculate_wage(self, hours):
    self.hours = hours
    return hours * 12.00
  def full_time_wage(self, hours):
    return super(PartTimeEmployee, self).calculate_wage(hours)

milton = PartTimeEmployee('Milton')
print milton.full_time_wage(10)

#returns 200.0



Inside the Triangle class below, Create a method named check_angles. The sum of a triangle's three angles should return True if the sum of self.angle1, self.angle2, and self.angle3 is equal 180, and False otherwise.

class Triangle(object):
  number_of_sides = 3
  def __init__(self, angle1, angle2, angle3):
    self.angle1 = angle1
    self.angle2 = angle2
    self.angle3 = angle3

  def check_angles(self):
    if (self.angle1 + self.angle2 + self.angle3) == 180:
      return True
      return False


Class member variables

Classes can have member variables that store information about each class object. We call them member variables since they are information that belongs to the class object.

Creating member variables and assigning them initial values is as easy as creating any other variable:

class Car(object):
  condition = "new"

my_car = Car()

Each class object we create has its own set of member variables. Since we've created an object my_car that is an instance of the Car class, my_car should already have a member variable named condition. This attribute gets assigned a value as soon as my_car is created.


how to access the member variables of classes

We use dot notation to access the member variables of classes since those variables belong to the object.

For instance, if we had created a member variable named new_variable, a new instance of the class named new_object could access this variable by saying:



in code below, what is perimeter(self) called?

class Square(object):

    def __init__(self, side):

        self.side = side

    def perimeter(self):

        return self.side * 4

A method under class Square. 

Besides member variables, classes can also have their own methods. The perimeter() class method is identical to defining any other function, except that it is written inside of the Square class definition.

Just like when we defined __init__(), you need to provide self as the first argument of any class method.


what does this return 

number = 0

for number in range(10):

    number = number + 1

    if number == 5:

        break # break here

    print('Number is ' + str(number))

print('Out of loop')

Then, there is an if statement that presents the condition that if the variable number is equivalent to the integer 5, then the loop will break.

Within the loop is also a print() statement that will execute with each iteration of the for loop until the loop breaks, since it is after the break statement.

Number is 1

Number is 2

Number is 3

Number is 4

Out of loop


Lines beginning with ">>>" and "..." indicate what ? 

Lines beginning with ">>>" and "..." indicate input to Python (these are the default prompts of the interactive interpreter). Everything else is output from Python.e.g. 

>>> def f (x): return x**2
>>> print f(8)


>>> g = lambda x: x**2
>>> print g(8)