Python

¡Supera tus tareas y exámenes ahora con Quizwiz!

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

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

How to combine multiple strings

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

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

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

Write some examples of comparators

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

How do you write "to the power of"

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

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

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

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

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 %

What are the three components needed to define a function

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

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

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 )

What are the three boolean operators and what do they do

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.

True or not False and False

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"

Order of operations for boolean operators

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

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

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.

What is a list

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

What is a dictionary and how do you write it

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

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

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)

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

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

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

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

What is a string

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

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

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'].

How do booleans relate to integers

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.

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

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

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

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

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.

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

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])"""

What are the six comparators and how do you write them

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

Explain the body of a function

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

What is an index

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.

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

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

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?

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

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

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

What is control flow

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

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?

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

Converting a string to a numeric datatype with decimals

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

What is a comment and how do you leave one

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

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

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.

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

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

Explain the header of a function

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

What does the while loop do and how is it different than 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.

How can you make a computer do math?

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

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

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

What does the super call do

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

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

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

What are 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]

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

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.

Give an example of "if" statement syntax

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"

Explain the comment of a function

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

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

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

What are variables?

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"

Strings need to be within _______

Quotes

Bitwise operator "or"

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)

What does an if/else pair do

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

What do you use functions for

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.

What are string methods? Give 4 examples

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

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

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

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

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"])

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

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.

Bitwise operator "and"

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

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

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.

Boolean operator and

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.

Boolean Operator not

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.

Boolean Operator or

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.

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

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

What is __init__().

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

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

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

How do you write a multi-line comment

Triple quotes, no variable

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

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

How to turn a bit on or off

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.

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

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]

How do you get out of a "for" loop

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

What is a method

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

Explain the scopes different variables can have with classes

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

Can you do math with variables? How?

Yes. Example: fish_in_clarks_pond = fish_in_clarks_pond - number_of_fish_caught

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

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.

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

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

How do you search for items 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 sort a list alphabetically

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

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

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

How do you remove one single item from a list

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

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.

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

What python function helps you print a number in binary

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

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

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

Set bool_five equal to the result of not not False

bool_five = False

Set bool_one equal to the result of False and False

bool_one = 1<0 and 3<2

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

bool_three = False and False

Set bool_two equal to the result of True or False

bool_two = 1 != 3 or 1 == 3

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

c = "cats"[0]

Give an example of typical class syntax

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

How does inheritance syntax work

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

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

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

Give an example of dot notation

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.

Bitwise operator "XOR" or "exclusive or"

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)

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

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

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

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

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

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

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

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

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

def answer(): return 42

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.

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

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.

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

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

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

Give an example of a function that calls another function

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

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

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

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.

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

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]

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

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

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

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

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

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

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

How do you delete an item from a dictionary

del dict_name[key_name]

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

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]

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

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

How do you give an integer a numeric value?

dogs = 1

What is elif? Give an example of its use

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.

What is enumerate? Give an example

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

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

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

Example of file I/O syntax

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

Write a loop that prints the numbers 0 through 20

for i in range(21): print i

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

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

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

for variable in list_name: #do stuff Example:

How do you get the current date and time

from datetime import datetime print datetime.now()

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

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

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

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

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.

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

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

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"

Give an if/else example

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

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

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

What is the modulo operator

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

How do you convert a string to a numeric datatype

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

How to use the int function on bitwise operators

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

Give an example of list slicing with a list comprehension editor

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]

What is one way to add items to a list

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

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

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

Write an example of a dictionary in a list

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

How to read the entire output.txt file

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

How to read an output.txt file line by line

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

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

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.

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]

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

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

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)

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

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]

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

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

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.

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

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

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

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

original_variable += new_variable That += or -=

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

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

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

point_total+= exercises_completed*points_per_exercise

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

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

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

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

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

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

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

print len(ministry) print ministry.upper()

How do you print a variable

print variable No quotations

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

product= float(0.25) * float(40.0)

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

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

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

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.

What are shift operations with bitwise

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)

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

square(10)

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 = []

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

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

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

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

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

What is the "condition" in a while statement

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.

The length len() of a dictionary is

the number of key-value pairs it has.

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

the_machine_goes= "Ping!" print the_machine_goes

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.

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

How do you assign a variable to an index

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

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

variable= False remember to capitalize

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

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

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

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

What does the zip function do?

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!

How to assign something in an index a different value

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


Conjuntos de estudio relacionados

HIPAA and Privacy Act Training -JKO

View Set

Ch 2 The Constitution True/False

View Set