1/159
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
print()
prints to the screen whatever is inside the parentheses
value
information associated with a variable
Variable names can contain only
letters, numbers, and underscores.
Variables can start with a letter or an underscore, but not
with numbers
Spaces are not allowed in variable names, but
underscores can be used to separate words in variable names
String
a series of characters. Anything inside quotes. You can use single or double quotes around them
Method
an action that Python can perform on a piece of data. Every method is followed by a set of parentheses, because methods often need additional information to do their work
.lower()
convert strings to lowercase. Temporary. Doesn’t change the value that was originally stored
.title()
changes each word to title case, where each word begins with a capital letter
.upper()
converts strings to uppercase
f-strings
f is for format, because Python formats the string by replacing the name of any variable in braces with its value
To insert a variable’s value into a string,
place the letter f immediately before the opening quotation mark. Put braces around the name or names of any variable you want to use inside the string. Python will replace each variable with its value when the string is displayed.
.format()
list the variables you want to use in the string inside the parentheses following format. Each variable is referred to by a set of braces; the braces will be filled by the values listed in parentheses in the order provided
Whitespace
any nonprinting character, such as spaces, tabs, and end- of-line symbols
\t
to add a tab to your text
\n
to add a newline in a string
\n\t
move to a new line, and start the next line with a tab
.rstrip()
to ensure that no whitespace exists at the right end of a string
associate the stripped value with the variable name
to remove the whitespace from the string permanently
.lstrip()
strip whitespace from the left side of a string
.strip()
strip whitespace from both sides at once
**
exponents
/
float division
//
integer division
Python supports the order of operations too, so
you can use multiple operations in one expression. You can also use parentheses to modify the order of operations so Python can evaluate your expression in the order you specify.
Float
any number with a decimal point
When you divide any two numbers, even if they are integers that result in a whole number,
you’ll always get a float
When you’re writing long numbers, you can group digits using
underscores to make large numbers more readable for you. Python ignores the underscores when storing these kinds of values
You can assign values to more than one variable using
just a single line. You’ll use this technique most often when initializing a set of numbers. You need to separate the variable names with commas, and do the same with the values, and Python will assign each value to its respectively positioned variable. As long as the number of values matches the number of variables, Python will match them up correctly
Constant
a variable whose value stays the same throughout the life of a program. Use all capital letters to indicate a variable should be treated as a constant and never be changed
#
a comment to explain what your code is supposed to do and how you are making it work
List
a collection of items in a particular order. Mutable. Wrapped in square brackets []. Individual elements are separated by commas.
Access any element in a list by
writing the name of the list followed by the index of the item enclosed in square brackets
Index of first item in a list
[0]
Index of last item in a list
[-1]
you can also use f-strings to create a message based on
a value from a list
To change an element in a list
use the name of the list followed by the index of the element you want to change, and then = provide the new value you want that item to have.
.append()
The new element in the () is added to the end of the list
you can start with an empty list and then add items to the list using
a series of append() calls
.insert( , )
Add a new element at any position in your list. In the (), specify the index of the new element and the value of the new item. This operation shifts every other value in the list one position to the right
del statement
Use if you know the index of the item you want to remove from a list. You can no longer access the value that was removed
.pop()
method removes the last item in a list, but it lets you work with that item after removing it. To remove an item from any position in a list, include the index of the item you want to remove in ()
.remove()
Use this method if only know the value of the item (you don’t know the index) you want to remove. Can still work with value after it’s removed. deletes only the first occurrence of the value you specify. If there’s a possibility the value appears more than once in the list, you’ll need to use a loop to make sure all occurrences of the value are removed.
.sort()
permanently change the order of the list to store them alphabetically or in ascending order
.sort(reverse=True)
permanently change the order of the list to store them in reverse alphabetical or in descending order
sorted()
maintain the original order of a list but present it in a sorted order. List variable in (). Also accepts reverse=True
.reverse()
permanently reverses the original order of a list. Can revert to the original order anytime by applying the method to the same list a second time
len()
find the length
Index error
Python can’t find an item at the index you requested
for loop
takes a collection of items and executes a block of code once for each item in the collection. You know the number of iterations
looping
set of steps is repeated once for each item in the list, no matter how many items are in an iterable. each indented line is executed once for each value. Any lines of code after the loop that are not indented are executed once without repetition
inside the loop
Every indented line (body) following the head. Each indented line is executed once for each value
only lines you should indent are
the actions you want to repeat for each item in a for or while loop
range() function
makes it easy to generate a series of numbers.
range(start, stop+1, step)
If step is excluded, default increasing by 1
Two numbers are (start, end+1)
If start is excluded, 0 is default start
One number (end+1)
Get even numbers: 2 as step
list(range())
convert the results of range() directly into a list of numbers
list comprehension
combines the for loop and the creation of new elements into one line, and automatically appends each new element
how to write a list comprehension
begin with a descriptive name for the list. Next, open a set of square brackets and define the expression for the values you want to store in the new list. Then, write a for loop to generate the numbers you want to feed into the expression, and close the square brackets. No colon is used at the end of the for statement.
slice
work with a specific group of items in a list. Specify the index of the first and last elements you want to work with
listname[start:end+1:step]
If you omit the first index in a slice, Python automatically starts your slice at the beginning of the list [:2]
Omit the end index, it will default get all the elements since the indicated start. Like [2:]
[:] get all elements
You can use a slice in a for loop if
you want to loop through a subset of the elements in a list
copy the entire list using slicing
by omitting the first index and the second index ([:])
tuple
list-like. Immutable and elements put in ( ). Index to access elements. If you want to define a tuple with one element, you need to include a trailing comma (3,)
immutable
cannot change
mutable
can change
Although you can’t modify a tuple, you can
reassign by associating a new tuple with the variable
conditional test (Booleon expression)
every if statement is an expression that can be evaluated as True or False. Python uses the values True and
False to decide whether the code in an if statement should be executed.
If a conditional test evaluates to True, Python executes the code following the if statement.
If the test evaluates to False, Python ignores the code following the if statement.
== double equal sign
equality operator returns True if the values on the left and right side of the operator match, and False if they don’t match
variable = value
states “set the variable equal to value”
variable == value
asks “Is the variable equal to value?”
two values with different capitalization are
not considered equal
!=
determine whether two values are not equal. The exclamation point represents not. If these two values do not match, Python returns True and executes the code following the if statement. If the two values match, Python returns False and does not run the code following the if statement.
To check whether two conditions are both True simultaneously
use the keyword and to combine the two conditional tests;
If each test passes, the overall expression evaluates to True.
If either test fails or if both tests fail, the expression evaluates to False
The keyword or allows you to check multiple conditions as well, but
it passes when either or both of the individual tests pass. An or expression fails only when both individual tests fail.
Use the keyword in
To find out whether a particular value is already in an iterable and to iterate through a sequence in a for loop:.
i.e., requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' in requested_toppings
True
Use the keyword not in
to know if a value does not appear in an iterable
Boolean value
either True or False, just like the value
simple if statement
if conditional_test:
do something
You can put any conditional test in the first line and just about any action in the indented block following the test. If the conditional test evaluates to True, Python executes the indented code following the if statement. If the test evaluates to False, Python ignores the indented code following the if statement.
else block
matches any condition that wasn’t matched by a specific if or elif test
In a simple if-else chain,
one of the two actions will always be executed.
if-elif-else chain
Used to test more than two possible situations, and to evaluate. Python executes only one block in the chain. It runs each conditional test in order until one passes. When a test passes for one condition, the code following that test is executed and Python skips the rest of the tests.
elif block
like another if test. It only runs if the previous tests failed. You can use as many elif blocks in your code as you like
is an else block required at the end of an if-elif chain?
not always required. Sometimes an else block is useful; sometimes it is clearer to use an additional elif statement that catches the specific condition of interest. If you have a specific final condition you are testing for, consider using a final elif block and omit the else block
When more than one condition could be True, use
a series of independent if statements with no elif or else blocks. More than one block of code is run regardless of whether the previous test passed or not
Check whether a list is empty by
running a for loop. When only the name of a list is used in an if statement, Python returns True if the list contains at least one item; an empty list evaluates to False
Dictionary
a collection of key-value pairs. Wrapped in braces, {}, with a series of key-value pairs inside the braces. Every key is connected to its value by a colon, and individual key-value pairs are separated by commas.
To get the value associated with a key,
give the name of the dictionary and then place the key inside a set of square brackets []. dictionaryname[key]
Key-value pair
a set of values associated with each other
When you provide a key,
Python returns the value associated with that key.
To add a new key-value pair,
you would give the name of the dictionary followed by the new key in square brackets = along with the new value
To start filling an empty dictionary,
define a dictionary with an empty set of braces and then add each key-value pair on its own line
To modify a value in a dictionary,
give the name of the dictionary with the key in square brackets and then the new value you want associated with that key
Use the del statement in a dictionary
to permanently remove a key-value pair. All del needs is the name of the dictionary and the key that you want to remove.
When you know you’ll need more than one line to define a dictionary,
press enter after the opening brace. Then indent the next line one level (four spaces), and write the first key-value pair, followed by a comma. From this point forward when you press enter, your text editor should automatically indent all subsequent key-value pairs to match the first key-value pair. Once you’ve finished defining the dictionary, add a closing brace on a new line after the last key-value pair and indent it one level so it aligns with the keys in the dictionary. It’s good practice to include a comma after the last key-value pair as well, so you’re ready to add a new key-value pair on the next line.
Using keys in square brackets to retrieve the value you’re interested in from a dictionary might cause one potential problem
if the key you ask for doesn’t exist, you’ll get an error
For dictionaries, specifically, you can use the get() method to
set a default value that will be returned if the requested key doesn’t exist.
.get() for dictionaries
requires a key as a first argument. As a second optional argument, you can pass the value to be returned if the key doesn’t exist. If you leave out the second argument in the call to get() and the key doesn’t exist, Python will return the value None.
None
means “no value exists.” This is not an error: it’s a special value meant to indicate the absence of a value.
Default behavior when looping through a dictionary
loops through keys
Loop through a dictionary with a
for loop