Python Flashcards
#
Python interprets anything after a # as a comment
print( “ “ )
Function used to print whatever is put in the quotes
Strings
Blocks of text, can be within “ “ or ‘ ‘
Variables
We can store data for reuse, variables are assigned by using =
Variables cannot have spaces or symbols in their names, only underscore can be used as a space
Two common errors in python
SyntaxError
NameError
SyntaxError
Means there is something wrong with the way your program is written - punctuation, command in wrong spot, missing parenthesis
NameError
Occurs when the Python interpreter sees a word it does not recognize
Code that contains something that looks like a variable but was never defined
Integer
Data type that is a whole number
int
Floating point number
A data type that is a decimal number
float
Literal
A number that is actually a number and not a variable
print(variable + 3)
Changing numbers
Variables will not be changed when performing arithmetic
Variables will only update with =
Modulo
% operator
Gives the remainder of a division calculation
If the two numbers are divisible then the result will be 0
This is good in programming for use if we want to perform an action every nth time
Concatenation
The + operator can be used to combine variables that are strings together
If we want to combine a number and string together and store it as a variable then we need to convert the number variable to a string using str()
If we just want to print the variables we do not need to convert the number variable to a string. We can simply use commas in the print operator - print( , , )
+=
Shorthand operator to add to the current value of a variable
“ “ “
Allows spacing of strings to multiple lines or including quote marks within your strings
Functions
Allow to group code into reusable blocks. It is a sequence of steps that can be performed repeatedly without having to rewrite the code
Defining a function
def function_name( parameter1, parameter2, parameter3, etc ):
print( … )
print( … )
Remove the indent of the line to end the function
Parameter vs argument
A parameter is defined with the function and is treated as a variable
The argument is the data that is passed into the function in the form of that variable when the function is called using the argument
Types of arguments
Positional arguments
Keyword arguments
Default arguments
Positional argument
Standard way of definition. The order in which you enter your arguments will be assigned according to the order in which the parameters were defined
Keyword argument
When entering your argument, you bypass the positional definition of the parameters and simply call out the definition directly in the function call
def function(x, y, z)
function(y=5, z=3, x=1)
Default argument
When defining the function we can assign a default value to the parameter
When calling the function we can enter no argument at that position to keep the default or enter a value to replace the default
def function(x, y=10)
function(x)
Variable scope
If a variable is defined outside of a function then it can be used anytime
If it is only defined within a function then it can only be used when calling the function
Returns
def calculation(x, y)
return x * y
Functions can return a value to the program so that it can be modified or used later
Returned function value
A result from a function that is stored in a variable
Boolean expression
A statement that can either be true or false
It will be returned as True and not “True”. I.e. a Boolean value and not a string
It is a bool data type
Variables with a bool type are Boolean variables
Relational operators / comparators
Operators that compare two items and return either true or false
Equals ==
Not equals !=
String != integer
> =
<
<=
Conditional statement syntax
if is_raining:
print(“bring an umbrella”)
The : represents the Then part of the if and what comes after the colon will be executed if it is true
Boolean operators
And - all conditions must be met in order to be True
Or - only one condition must be met in order to be True
Not - reverses a Boolean value
not True == False
if not x > 5:
print(“ “)
Else statements
Else statements allow us to elegantly describe what we want our code to do when conditions are not met rather than using not
Else statements always appear with if
if weekday:
print(“wake up at 6:30”)
else:
print(“sleep in”)
Else if statements
elif
Allow us to check multiple ifs
Will check in the order it is written
List
Allows us to work with a collection of data in sequential order
Heights = [61, 70, 67, 64]
Lists can contain any data type together
It is not required for a list to have values
list = []
List methods
Append - adds a single element to the end of the list - example_list.append(5)
Remove - remove an element from the list - example_list.append(5)
Add multiple - updated list = list1 + [“ex1”, “ex2”]
List index
Lists are indexed and the starting index is 0
print(list[0])
We can select the last element of the list using -1 even if we don’t know the length of the list
Replacing a value in a list
We can directly replace a value in a list by calling the index
List[5] = ‘strawberries’
Zip()
Used to combine two lists
new_list = zip(list1, list2)
In order to print the list you need to use the list() function
print_new_list = list(new_list)
.count()
A list method to count the number of occurrences of an element in a list
.insert()
A list method to insert an element into a specific index of a list
.pop()
A list method to remove an element from a specific index or from the end of a list
range()
A built in python function to create a sequence of integers
my_range = range(2, 9, 2)
Creates a range starting at 2 up to 8 counting by 2s
len()
A built in python function to get the length of a list
.sort() / sorted()
A method and a built in function to sort a list
.sort will modify the existing list
sorted() will create a new list
Slicing
sliced_list = list[first index : index+1 of the last item we want to include]
Slice section from beginning up to n
list[:n]
Slice section from end up to n
list[-n:]
Slice section but leave remainder n
list[:-n]
Indefinite iteration
The number of times the loop is executed depends on how many times a condition is met
Definite iteration
The number of times the loop will be executed is defined in advance
for loop
A definite iteration
for <temporary> in <collection>:</collection></temporary>
<action>
</action>
Using range() with for loop
Allows to define a certain number of iterations without caring what is in the list
for temp in range(6):
print(“Learning Loops!”)
while loop
An indefinite iteration
Will perform a set of instructions as long as a condition is true
while <conditional>:</conditional>
<action>
</action>
Loop break
We can break a loop when a condition is met
for item in items_on_sale:
print(item)
if item == “knit dress”:
break
continue
Used in loop to skip
for i in big_number_list:
if i <= 0:
continue
print(i)
this will skip negative numbers and only print positive numbers in the number list
List comprehensions
We can write loops in a cleaner way in python
numbers = [ … , … , ]
doubled = [num*2 for num in numbers]
print(doubled)
We can also add if, in this case to only double negative numbers
numbers = [ … , … , ]
negative_doubled = [num*2 for num in numbers if num < 0]
print(negative_doubled)