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”