Ken Yuan Python Flashcards
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.
boolean
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
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 datetime.now() to retrieve the current date and time. # code from datetime import datetime print datetime.now() 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 = datetime.now() print ‘%s-%s-%s’ % (now.year, now.month, now.day) # 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
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”
.isalpha()
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”
.lower()
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.
function
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
- 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.
module
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
- 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
Pros:
Less maintenance of your import statements. Don’t need to add any additional imports to start using another item from the module
Cons:
Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo)
from module import foo
Pros:
Less typing to use foo
More control over which items of a module can be accessed
Cons:
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]
“c”