Section 1

Preview this deck

How do you assign a variable to an index

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

0

All-time users

0

Favorites

0

Last updated

6 years ago

Date created

Mar 1, 2020

Cards (167)

Section 1

(50 cards)

How do you assign a variable to an index

Front

variable= "string"[index #] For example, fifth_letter = "MONTY"[4] sets the variable fifth_letter equal to the letter y (REMEMBER THESE START AT 0)

Back

What would you do if you wanted a variable to correspond to false

Front

variable= False remember to capitalize

Back

What is control flow

Front

Gives you ability to choose among outcomes based on what else is happening in the program.

Back

How would you print "Life of Brian" by writing three separate strings? What is this called?

Front

print "Life " + "of " + "Brian" Remember the spaces in the quotation marks!! This is called concatenation.

Back

Update point_total to be what it was before plus the result of multiplying exercises_completed and points_per_exercise.

Front

point_total+= exercises_completed*points_per_exercise

Back

If you're trying to do "print _______" and you get NameError, what might it mean?

Front

You left out quotes. Python found what it thinks is a command, but doesn't know what it means because it's not defined anywhere.

Back

Create a string called product that contains the result of multiplying the float value of float_1 and float_2. where float_1 = 0.25 float_2 = 40.0

Front

product= float(0.25) * float(40.0)

Back

How do you print a variable

Front

print variable No quotations

Back

How do you give an integer a numeric value?

Front

dogs = 1

Back

What do you use to convert a variable to a different datatype, like to put it in text?

Front

str( ) age = 13 print "I am " + str(age) + " years old!" Prints "I am 13 years old!"

Back

What is the editor and what is the console? How does this relate to the print command?

Front

The area where we've been writing our code is called the editor. The console (the window to the right of the editor) is where the results of your code is shown. print simply displays your code in the console.

Back

How do you write a multi-line comment

Front

Triple quotes, no variable

Back

How do you get the current date and time

Front

from datetime import datetime print datetime.now()

Back

Say day=6 How would you create 03 - 6 - 2019? What about 03 - 06 - 2019?

Front

day = 6 print "03 - %s - 2019" % (day) # 03 - 6 - 2019 print "03 - %02d - 2019" % (day) # 03 - 06 - 2019

Back

How to combine multiple strings

Front

"this is"+"a string" comes out as: this is a string

Back

What is an index

Front

Each character in a string is assigned a number. This number is called the index. These always start from 0- meaning the first character in a string is the 0th index, the second character is the 1st index, etc.

Back

What's the nitpicky thing to remember about leaving a comment

Front

# comment won't work. Needs to be #comment

Back

What is the problem with 'There's a snake in my boot!' and how do you fix it

Front

This code breaks because Python thinks the apostrophe in 'There's' ends the string. Change to: 'There\'s a snake in my boot!' Remember to use \ instead of / Or just use double quotations for all strings

Back

What do you write if you don't want the entire date and time, just the day, month, and year?

Front

from datetime import datetime now = datetime.now() current_year = now.year current_month = now.month current_day = now.day

Back

What is the main symbol you want to remember if you're changing a variable's value with arithmetic

Front

original_variable += new_variable That += or -=

Back

product= float(0.25) * float(40.0) Create a string called big_string that says: The product was X with the value of product where the X is.

Front

big_string= "The product was " + str(int(product))

Back

What is a comment and how do you leave one

Front

If you want to include a piece of information to explain a part of your code, you can use the # sign. A line of text preceded by a # is called a comment. The machine does not run this code — it is only for humans to read

Back

Converting a string to a numeric datatype with decimals

Front

If you use int() on a floating point number, it will round the number down. To preserve the decimal, you can use float(): string_num = "7.5" print int(string_num) -> gives you 7 print float(string_num) -> gives you 7.5

Back

What if we want to print today's date as mm/dd/yyyy

Front

from datetime import datetime now = datetime.now() print '%02d/%02d/%04d' % (now.month, now.day, now.year)

Back

What does lower( ) do? How should you write it?

Front

Gets rid of all capitalization in a string print "Ryan".lower() will return "ryan". Can also do it after a variable parrot = "Norwegian Blue" print parrot.lower()

Back

What is the modulo operator

Front

indicated by % and returns the remainder after division is performed. Example: is_this_number_odd = 15 % 2

Back

Can you do math with variables? How?

Front

Yes. Example: fish_in_clarks_pond = fish_in_clarks_pond - number_of_fish_caught

Back

What does str( ) do? How should you write it?

Front

Turns non-strings into strings! For example: str(2) would turn 2 into "2". And with variables: pi=3.14 print str(pi)

Back

What does upper( ) do? How should you write it? use an example with a variable

Front

Makes a string completely upper case. parrot = "norwegian blue" print parrot.upper()

Back

Print a string to the console that says: I got X points! with the value of point_total where X is.

Front

print "I got "+str(point_total)+" points!" Make sure the "p" in print is lower case

Back

What are variables?

Front

Python uses variables to define things that are subject to change. For example, you could say greeting_message= "hi" and then if you changed it later to greeting_message="hello" everywhere that greeting_message was used, it would change to "hello"

Back

What is a float and how do you write it? How do you use scientific notation?

Front

A number with a decimal point. cats = 1.0 You can also define a float using scientific notation, with e indicating the power of 10 parrots = 1.5e2

Back

What's unique about division in python 2? How can you make sure you get an exact answer?

Front

Always rounded to an integer. Need either or both numbers to be a float (have a decimal) Example: quotient= 7/2 will give 3 Quotient= 7./2.= 3.5

Back

What are string methods? Give 4 examples

Front

String methods let you perform specific tasks for strings. Ex: len() lower() upper() str()

Back

What is the shorthand for adding or subtracting a number to the original contents of the variable.

Front

original_variable += new_variable Then any time you type "original variable" after entering that, it'll actually be using the original variable+the new variable

Back

What is the index of the letter C in the string "cats"?

Front

c = "cats"[0]

Back

ministry = "The Ministry of Silly Walks" Call the len() function with the argument ministry. Then invoke the ministry's .upper() function.

Front

print len(ministry) print ministry.upper()

Back

How can you make a computer do math?

Front

Just assign it as a variable. Example: multiplication= 5*25

Back

What is a string

Front

A series of letters, numbers, or symbols connected in order. Text like print "something" is an example

Back

How do booleans relate to integers

Front

A value of True corresponds to an integer value of 1, and will behave the same. A value of False corresponds to an integer value of 0.

Back

What does len( ) do? How should you write it?

Front

gets the length (the number of characters) of a string. Example of how to write: parrot="Norwegian Blue" print len(parrot) That gives you the number of characters in "Norwegian Blue"

Back

Why do you use len(string) and str(object), but dot notation such as "String".upper() for the rest?

Front

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

Back

Strings need to be within _______

Front

Quotes

Back

What is a boolean? How do you define booleans in python?

Front

datatype which can only ever take one of two values is called a boolean. In Python, we define booleans using the keywords True and False

Back

Difference between python 2 and 3: how to write a print statement

Front

In python 3, print has parenthesis Example: print("hi") In python 2, just quotations Example: print "hi"

Back

What do you do if you want a string of text to span multiple lines

Front

Triple quotes, assign it to a variable Example: address_string = """136 Whowho Rd Apt 7 Whosville, WZ 44494"""

Back

Declare a variable called the_machine_goes and assign it the string value "Ping!" Print the_machine_goes

Front

the_machine_goes= "Ping!" print the_machine_goes

Back

What is the easiest way to combine a string with variables? Give an example

Front

1. Create variables for the parts of the string that you want to replace Example: string_1 = "Camelot" string_2 = "place" 2. Write your string with print, but replace those words with %s. Then at the end of the quotes, put a % and (variable 1, variable 2, etc) Example: print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2) This gives you: Let's not go to Camelot. 'Tis a silly place. Remember to use %s. not just %

Back

How do you convert a string to a numeric datatype

Front

int( ) number1 = "100" number2 = "10" string_addition = number1 + number2 #string_addition now has a value of "10010" int_addition = int(number1) + int(number2) #int_addition has a value of 110

Back

How do you print an integer with extra zeroes using the % operator

Front

"pad" it with zeros using %02d. The 0 means "pad with zeros"" The 2 means to pad to 2 characters wide The d means the number is a signed integer (can be positive or negative).

Back

Section 2

(50 cards)

Give an example of a function that calls another function

Front

def fun_one(n): return n * 5 def fun_two(m): return fun_one(m) + 7

Back

Boolean Operator or

Front

The boolean operator or returns True when at least one expression on either side of or is true. For example: 1 < 2 or 2 > 3 is True; 1 > 2 or 2 > 3 is False.

Back

What is a parameter and what does it do? What are arguments? Give an example

Front

A parameter is a variable that is an input to a function. It says, "Later, when square is used, you'll be able to input any value you want, but for now we'll call that future value n" Example: def square(n): Here, n is a parameter of square. The values of the parameters passed into a function are known as the arguments. Recall in the previous example, we called: square(10) The argument is 10

Back

How do you search for items in a list

Front

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.

Back

What do you do if you only want to access a portion of the list? What is this called?

Front

Called list slicing follows the format [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 variable = ["list1", list2", "list3"] ugh= variable[1:3:1] print ugh """that returns ["list2", list3"] (remember there's no index 3 but that second number is excluded so we couldnt say variable [1:2])"""

Back

Write a function using the parameters base and exponent that will raise a number to a power of a different number

Front

def power(base, exponent): result = base ** exponent print "%d to the power of %d is %d." % (base, exponent, result)

Back

What do you use functions for

Front

Situations where you would like to reuse a piece of code, just with a few different values. Instead of rewriting the whole code, it's much cleaner to define a function, which can then be used repeatedly.

Back

What is a for loop and how do you use it?

Front

for variable in list_name: #do stuff Example:

Back

What are the three components needed to define a function

Front

1. Header 2. Comment (optional) 3. Body

Back

True or not False and False

Front

1. not is evaluated first not false= true so: Now "True or True and False" 2. and is evaluated next; True and False Since "and" will only give true if both statements are true, this gives false Now "True or False" 3. or is evaluated last. Returns true if at least one side is true. "True or False" becomes "True"

Back

What is one way to add items to a list

Front

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

Back

First, def a function called cube that takes an argument called number. Don't forget the parentheses and the colon! Make that function return the cube of that number (i.e. that number multiplied by itself and multiplied by itself once again). Define a second function called by_three that takes an argument called number. if that number is divisible by 3, by_three should call cube(number) and return its result. Otherwise, by_three should return False.

Front

def cube(number): return number**3 def by_three(number): if number % 3 == 0: return cube(number) else: return False

Back

What is a function import and how do you do it? What does it allow you to do?

Front

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) Example: from math import sqrt Allows you to just type sqrt( ) instead of math.sqrt()

Back

bool_one = (2 <= 2) and "Alpha" == "Bravo" What will this return

Front

False. The statement is "True and False" With "and" both statements must be true for it to evaluate to true So this comes out as false

Back

Write something with if and elif that will return the correct letter grade for a numerical score that is entered

Front

def grade_converter(grade): if grade >= 90: return "A" elif grade >= 80 and grade <= 89: return "B" elif grade >= 70 and grade <= 79: return "C" elif grade >= 65 and grade <= 69: return "D" else: return "F" In this example, entering grade_converter (92) would return an A

Back

Give an if/else example

Front

if 8 > 9: print "I don't printed!" else: print "I get printed!"

Back

Set bool_three equal to the result of 19 % 4 != 300 / 10 / 10 and False

Front

bool_three = False and False

Back

What is a list

Front

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.)

Back

Explain the header of a function

Front

Includes the def keyword, the name of the function, and any parameters the function requires. Here's an example: def hello_world(): # There are no parameters

Back

Give an example of "if" statement syntax

Front

Need three things: an "if" and a ":" and an indented print Example: if 8 < 9: print "Eight is less than nine!" Remember to indent with four spaces before the "print" so that the computer knows the only statement the "is" is checking is "8<9"

Back

What are the three boolean operators and what do they do

Front

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.

Back

Set bool_five equal to the result of not not False

Front

bool_five = False

Back

Boolean operator and

Front

The boolean operator and returns True when the expressions on both sides of and are true. For instance: 1 < 2 and 2 < 3 is True; 1 < 2 and 2 > 3 is False.

Back

What do you do if you need to slice all of a really long list and you dont know how long it is, so you don't know the second number?

Front

If you just say list[::1] it'll automatically go from the beginning to the end

Back

Give an example of list slicing with a list comprehension editor

Front

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] #prints [9, 25, 49, 81]

Back

Set bool_two equal to the result of True or False

Front

bool_two = 1 != 3 or 1 == 3

Back

Order of operations for boolean operators

Front

1. not is evaluated first; 2. and is evaluated next; 3. or is evaluated last. Anything in parenthesis is evaluated as its own unit

Back

Explain the body of a function

Front

Describes the procedures the function carries out. The body is indented, just like conditional statements. print "Hello World!" or return 42

Back

Set bool_one equal to the result of False and False

Front

bool_one = 1<0 and 3<2

Back

Write a function called answer that takes no arguments and returns the value 42.

Front

def answer(): return 42

Back

How do you insert items into a specific place in a list

Front

animals.insert(1, "dog") print animals We insert "dog" at index 1, which moves everything down by 1. So it's variable.insert( index number, "String to insert")

Back

How to sort a list alphabetically

Front

animals = ["cat", "ant", "bat"] animals.sort() for animal in animals: print animal

Back

What is elif? Give an example of its use

Front

elif is short for "else if." Means "if this other expression is true, do this" if 8 > 9: print "I don't get printed!" elif 8 < 9: print "I get printed!" else: print "I also don't get printed!" In the example above, the elif statement is only checked if the original if statement is False.

Back

What is a negative stride and how does it affect list slicing

Front

A stride describes the space between items in the sliced list. A positive stride progresses through the list from left to right. 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'].

Back

Create a function, spam, that prints the string "Eggs!" to the console.

Front

def spam(): """ew spam""" print "Eggs!"

Back

How to assign something in an index a different value

Front

zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"] zoo_animals[2] = "hyena"

Back

What are some functions that are built into python and what do they do? How do you write them?

Front

1. The max() function takes any number of arguments and returns the largest one 2. min() then returns the smallest of a given series of arguments 3. The abs() function returns the absolute value of the number it takes as an argument 4. the type() function returns the type of the data it receives as an argument. REMEMBER TO WRITE print type(integer, float, or string here )

Back

How do you assign items to a list? What about an empty list?

Front

list_name = [item_1, item_2] empty_list = [].

Back

How would you ask a user to input their name in a way that would store the name

Front

name = raw_input("What's your name?") print name Then the name will be stored under the variable "name"

Back

Write some examples of comparators

Front

#False bool_two = 5 == 3 #True bool_three = 10 >= (2+2) #False bool_four = 500 <= 3**2 #True bool_five = 5**2 != (1/2)

Back

What are the six comparators and how do you write them

Front

Comparators check if a value is (or is not) equal to, greater than (or equal to), or less than (or equal to) another value. Equal to (==) Not equal to (!=) Less than (<) Less than or equal to (<=) Greater than (>) Greater than or equal to (>= REMEMBER- the equals signs should always be on the right

Back

How do you access an individual item on the list by its index.

Front

Use format list_name[index] List indices begin with 0, not 1! You access the first item in a list like this: list_name[0]

Back

Define a function called plane_ride_cost that takes a string, city, as input. The function should return a different price depending on the location

Front

def plane_ride_cost(city): if city == "Charlotte": return 183 if city == "Tampa": return 220 if city == "Pittsburgh": return 222 if city == "Los Angeles": return 475

Back

What is a universal import and how do you do it? What does it allow you to do?

Front

if you still want all of the variables and functions in a module but don't want to have to constantly type math, use universal import from module import * Don't want to use this a lot bc it brings in a ton of variables

Back

Explain the comment of a function

Front

Optional comment explains what the function does. ALSO INDENTED Example: """Prints 'Hello World!' to the console."""

Back

Boolean Operator not

Front

The boolean operator not returns True for false statements and False for true statements. For example: not False will evaluate to True, while not 41 > 40 will return False.

Back

How do you write "to the power of"

Front

** So 3**7 is three to the seventh power

Back

A function, square, has already been set up. Call it on the number 10

Front

square(10)

Back

What is a module and how do you do a generic import? Once imported, how do you use a module

Front

A file that contains definitions—including variables and functions—that you can use once it is imported. For generic, all you need is the import keyword Example of how to use: If module is math, and sqrt is a function it contains, do import math print math.sqrt(25)

Back

What does an if/else pair do

Front

Says "If this expression is true, run this indented code block; otherwise, run this other code that comes after the else statement."

Back

Section 3

(50 cards)

Give an example of how to use "break" to exit a while loop

Front

count = 0 while True: print count count += 1 if count >= 10: break

Back

What is one way to iterate over a dictionary in no particular order and get the key/value pairs

Front

dictionaryname.items() Ex: my_dict = { "Thing": "Sky", "Color": "Blue", "Comments": "The sky is cool" } print my_dict.items()

Back

Give an example of how to use "for" loops to go through a list

Front

numbers = [7, 9, 12, 54, 99] for num in numbers: print num

Back

What python function helps you print a number in binary

Front

bin() takes an integer as input and returns the binary representation of that integer in a string.

Back

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

Front

def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x

Back

Give an example of the syntax you use for the lambda function. When would you use a lambda function vs a def function?

Front

my_list = range(16) filter(lambda x: x % 3 == 0, my_list) so it's filter(lambda x: x == ???, listname) 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.

Back

How do you use "for" to loop through keys in a dictionary

Front

d = {"foo" : "bar"} for key in d: print d[key] # prints "bar"

Back

Write a loop that prints the numbers 0 through 20

Front

for i in range(21): print i

Back

What are shift operations with bitwise

Front

shifting all the 1s and 0s left or right by the specified number of slots. Ex: # Left Bit Shift (<<) 0b000001 << 2 == 0b000100 (1 << 2 = 4)

Back

Use a list comprehension to create a list, threes_and_fives, that consists only of the numbers between 1 and 15 (inclusive) that are evenly divisible by 3 or 5.

Front

threes_and_fives = [x for x in range(1, 16) if x % 3 == 0 or x % 5 == 0]

Back

How do you get out of a "for" loop

Front

Use the break command for turn in range(4): guess_row = int(raw_input("Guess Row: ")) guess_col = int(raw_input("Guess Col: ")) if guess_row == ship_row and guess_col == ship_col: print "Congratulations! You sunk my battleship!" break

Back

Give some examples of how to use the "in" operator

Front

*Note that the trailing comma ensures that we keep printing on the same line.*

Back

Explain the base 2 number system. Write out the numbers 1-7 in base two

Front

print 0b1, #1 print 0b10, #2 print 0b11, #3 print 0b100, #4 print 0b101, #5 print 0b110, #6 print 0b111 #7 For example, the numbers one and zero are the same in base 10 and base 2. But in base 2, once you get to the number 2 you have to carry over the one, resulting in the representation "10". Adding one again results in "11" (3) and adding one again results in "100" (4).

Back

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

Front

start_list = [5, 3, 1, 2, 4] square_list = [] # Your code here! for number in start_list: square_list.append(number ** 2) square_list.sort() print square_list

Back

What are two ways of iterating through a list

Front

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]

Back

Create a 5 x 5 grid initialized to all 'O's and store it in board. Use range() to loop 5 times. Inside the loop, .append() a list containing 5 "O"s to board, just like in the example above

Front

board = [] for i in range(5): board.append(['O'] * 5)

Back

What does the while loop do and how is it different than an if statement

Front

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.

Back

What is a continuation character and what do you use it for

Front

The \ character is a continuation character. The following line is considered a continuation of the current line. Ex: return 0.9 * average(cost["apples"]) + \ 0.1 * average(cost["bananas"])

Back

Define a function compute_bill that takes one argument food as input. In the function, create a variable total with an initial value of zero. For each item in the food list, add the price of that item to total. Finally, return the total.

Front

def compute_bill(food): total = 0 for item in food: total = total + prices[item] return total

Back

How do you just remove an item from a list (using its index position). Hint: this is similar to another method, but it doesn't return the deleted item to you

Front

del(n[1]) is like .pop in that it will remove the item at the given index, but it won't return it: del(n[1]) # Doesn't return anything print n # prints [1, 5]

Back

Give an example of list comprehension syntax (ex: create a list of the squares of the even numbers from 1 to 11)

Front

even_squares = [x ** 2 for x in range(1, 12) if x % 2 == 0]

Back

garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX" Create a new variable called message. Set it to the result of calling filter() with the appropriate lambda that will filter out the "X"s. The second argument will be garbled. Finally, print your message to the console.

Front

garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX" message = filter(lambda x: x != "X", garbled) print message

Back

Bitwise operator "XOR" or "exclusive or"

Front

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. 0 ^ 0 = 0 0 ^ 1 = 1 1 ^ 0 = 1 1 ^ 1 = 0 Example: a: 00101010 42 b: 00001111 15 ================ a ^ b: 00100101 37 Therefore: 111 (7) ^ 1010 (10) = 1101 (13)

Back

The length len() of a dictionary is

Front

the number of key-value pairs it has.

Back

range(6) # => range(1, 6) # => range(1, 6, 3) # =>

Front

range(6) # => [0, 1, 2, 3, 4, 5] range(1, 6) # => [1, 2, 3, 4, 5] range(1, 6, 3) # => [1, 4]

Back

How do you just remove an item from a list (without even having to know its index position)

Front

n.remove(item) will remove the actual item if it finds it: n.remove(1) # Removes 1 from the list, # NOT the item at index 1 print n # prints [3, 5]

Back

Give an example of how to loop over a dictionary. Do you get the key or the value?

Front

you get the key which you can use to get the value.

Back

Define a function called list_extender that has one parameter lst. Inside the function, append the number 9 to lst. Then return the modified list. n = [3, 5, 7]

Front

n = [3, 5, 7] def list_extender(lst): lst.append(9) return lst print list_extender(n)

Back

How do you remove one single item from a list

Front

beatles = ["john","paul","george","ringo","stuart"] beatles.remove("stuart")

Back

How do you delete an item from a dictionary

Front

del dict_name[key_name]

Back

What can you do to make sure that a print statement all prints on the same line?

Front

Add a , after print Ex: word = "Marble" for char in word: print char, #prints M a r b l e

Back

What is a dictionary and how do you write it

Front

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: # Assigning a dictionary with three key-value pairs to residents: residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} print residents['Puffin'] # Prints Puffin's room number

Back

Define a function called join_strings accepts an argument called words. It will be a list. Inside the function, create a variable called result and set it to "", an empty string. Iterate through the words list and append each word to result. Finally, return the result.

Front

def join_strings(words): result = "" for word in words: result += word return result print join_strings(n)

Back

Change list_function to: Add 3 to the item at index 1 of the list. Store the result back into index 1. Return the list. the list is n = [1, 3, 5]

Front

def list_function(x): x[1] = x[1] + 3 return x n = [3, 5, 7] print list_function(n)

Back

How do you add a new key/value pair to a dictionary? How do you associate a different value with a preexisting key?

Front

add a new key/value pair to a dictionary: dict_name[new_key] = new_value associate a different value with a preexisting key: dict_name[key] = new_value

Back

Bitwise operator "and"

Front

The bitwise AND (&) operator compares two numbers and returns a 1 in the resulting number only if both numbers had a "1" in that place so 0 & 0 = 0 0 & 1 = 0 1 & 0 = 0 1 & 1 = 1 Example: a: 00101010 42 b: 00001111 15 =================== a & b: 00001010 10 But the way you actually write this is 0b111 (7) & 0b1010 (10) = 0b10

Back

What are bitwise operations

Front

Bitwise operations are operations that directly manipulate bits. In all computers, numbers are represented with bits, a series of zeros and ones.

Back

How do you get a list of a dictionary's keys alone, or its values alone?

Front

The .keys() method returns a list of the dictionary's keys, and The .values() method returns a list of the dictionary's values. Ex: my_dict = { "Thing": "Sky", "Color": "Blue", "Comments": "The sky is cool" } print my_dict.keys() print my_dict.values()

Back

What does the range function include? What happens if you omit start or step?

Front

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.

Back

How do you remove an item from a list and have it returned to you

Front

n.pop(index) will remove the item at index from the list and return it to you: n = [1, 3, 5] n.pop(1) # Returns 3 (the item at index 1)

Back

What does the range function do? What are the three different versions of the range function

Front

range(stop) range(start, stop) range(start, stop, step) a shortcut for generating a list, so you can use ranges in all the same places you can use lists.

Back

print the numbers 1, 3, and 21 using a "for" statement

Front

for item in [1, 3, 21]: print item

Back

What is the "condition" in a while statement

Front

the expression that decides whether the loop is going to continue being executed or not Ex: 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.

Back

How to use the int function on bitwise operators

Front

int("110", 2) # ==> 6 If you put in something in base 2 and then put a comma and a two afterwards, itll give you an integer in base 10

Back

What is enumerate? Give an example

Front

enumerate works by supplying a corresponding index to each element in the list that you pass it. choices = ['pizza', 'pasta', 'salad', 'nachos'] for index, item in enumerate(choices): print index + 1, item prints 1 pizza 2 pasta 3 salad 4 nachos

Back

What does the zip function do?

Front

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!

Back

Write an example of a dictionary in a list

Front

lloyd = { "homework": [90.0, 97.0, 75.0, 92.0], } alice = { "homework": [100.0, 92.0, 98.0, 100.0], } tyler = { "homework": [0.0, 87.0, 75.0, 22.0], } students = [lloyd, alice, tyler] The students = [lloyd, alice, tyler] is a list, and everything else is 3 dictionaries

Back

What does while/else do and how is it different from if/else

Front

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. Remember that the "while (whatever):" and the "else (whatever):" should be on the same level of indentation

Back

Bitwise operator "or"

Front

Returns a number where the bits of that number are turned on if either of the corresponding bits of either number are 1. 0 | 0 = 0 0 | 1 = 1 1 | 0 = 1 1 | 1 = 1 For example: a: 00101010 42 b: 00001111 15 ================ a | b: 00101111 47 Therefore: 110 (6) | 1010 (10) = 1110 (14)

Back

Create a while loop that prints out all the numbers from 1 to 10 squared (1, 4, 9, 16, ... , 100), each on their own line. Fill in the blank space so that our while loop goes from 1 to 10 inclusive. Inside the loop, print the value of num squared. The syntax for squaring a number is num ** 2. Increment num.

Front

num = 1 while num <= 10: print num**2 num = num + 1

Back

Section 4

(17 cards)

How to turn a bit on or off

Front

USe the "or" operator which is | 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.

Back

How to read an output.txt file line by line

Front

my_file = open("text.txt", "r") print my_file.readline() print my_file.readline() print my_file.readline() my_file.close()

Back

What if you want to read information from a file on your computer, and/or write that information to another file, rather than just sending something to the console?

Front

File I/O (the "I/O" stands for "input/output")- Python has a number of built-in functions that handle this for you.

Back

Example of file I/O syntax

Front

f = open("output.txt", "w") This told Python to open output.txt in "w" mode ("w" stands for "write"). We stored the result of this operation in a file object, f. Doing this opens the file in write-mode and prepares Python to send data into the file. Then some body stuff Then my_file.close()

Back

What is __init__().

Front

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. 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 self.name 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. Ex: def __init__(self, name, age): self.name = name self.age = age zebra = Animal("Jeffrey", 2) As you can see self is only in the init function, but the others are passed down

Back

Explain the scopes different variables can have with classes

Front

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). Same is true for functions

Back

What does the super call do

Front

Keeps a new derived class from overriding the older class. In other words, whatever the older class does, it can still keep doing that if you use the super function (without super function, derived class is the only thing that matters once its written) class Derived(Base): def m(self): return super(Derived, self).m() Where m() is a method from the base class (remember methods are just functions that belong to a class, written like def.Something(argument) )

Back

How to read the entire output.txt file

Front

my_file = open("output.txt", "r") print my_file.read() my_file.close()

Back

How does inheritance syntax work

Front

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. So whatever that new DerivedClass does will override whatever BaseClass did

Back

Way to test whether a file we've opened is closed

Front

Just do file.closed and it'll return False or True Ex: f = open("bg.txt") f.closed # False f.close() f.closed # True

Back

Bitwise operator "not"- what does it do mathematically?

Front

The bitwise NOT operator (~) just flips all of the bits in a single number. Mathematically, this is equivalent to adding one to the number and then making it negative.

Back

What is a method

Front

When a class has its own functions, those functions are called methods Ex: class Animal(object): """Makes cute animals.""" def __init__(self, name, age): self.name = name self.age = age Here, init is a method

Back

Give an example of how to use the __repr__() method

Front

class Point3D(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self): return "(%d, %d, %d)" % (self.x, self.y, self.z) my_point = Point3D(1, 2, 3) print my_point

Back

How do you get python to automatically close a file for you

Front

with open("file", "mode") as variable: That's the syntax Ex: with open("text.txt", "w") as textfile: textfile.write("Success!")

Back

Give an example of typical class syntax

Front

class Animal(object): def __init__(self, name): self.name = name By convention, user-defined Python class names start with a capital letter the def_init___(self) part is pretty much required, as is the class Classname(object) part

Back

Give an example of dot notation

Front

class Square(object): def __init__(self): self.sides = 4 my_shape = Square() print my_shape.sides First we create a class named Square with an attribute sides. Outside the class definition, we create a new instance of Square named my_shape and access that attribute using my_shape.sides.

Back

What does a bit mask do and how do you use it

Front

A bit mask is just a variable that aids you with bitwise operations. 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 & mask if desired > 0: print "Bit was on" In the example above, we want to see if the third bit from the right is on. First, we first create a variable num containing the number 12, or 0b1100. Next, we create a mask with the third bit on. Then, we use a bitwise-and operation to see if the third bit from the right of num is on. If desired is greater than zero, then the third bit of num must have been one.

Back