1/98
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
Positional Arguments
Arguments that must be passed in the same order in which the corresponding parameters are defined
Keyword Arguments
used to specify the parameter name with values in a function call, making the order irrelevant, and MUST be written to the right of all the positional arguments
Variable Length Arguments
*args
used in combination with regular arguments and MUST be placed after all the regular arguments
Ex: def variable_sum(first_arg,*args):
Variable-Length Keyword Arguments
**kwargs
used in the parameter list to pass a variable number of keyword arguments
Local Variables
variables defined insdie a fucntion and their scope is limited to that function
Global Variables
variables outside any function and accessible throughout the program
“global” keyword
used to modify the value of a global variable by defining it
Inner (nested) Function
a function defined inside another function and dependent on the outer function calling it to execute
“nonlocal” keyword
keyword used to affect inner function by changes to the outer function
Hidden variable
if a variable with the same name as the global variable is present in the outer function the global variable or varibale in outer function
Lambda function
lambda arguments : expression
small one-line functions that does not use keywords and can take any number of arguments but only one expression
Importing modules
import module_name
to use a user-written model and can use the keyword “as” to abbreviate module name
Import Specfic elements
from module_name import func
use the keyword “from” to import specific element
if _name_ == ‘_main_’
will execute only if the module is run as a standalone script but NOT when the module is imported ti another script
used when you want a module to define reusable values/functions while also containing runnable code
Recursion
mathematical and programming concept, meaning that a function calls itself
solves a problem by breaking it down into simpler and more manageable parts
Recursion Piece One
one or more base cases; simplest cases that the function already knows how to solve
Ex: if n==0:
return 1
Recursion Piece Two
recursive steps, slightly simpler or smaller versions of the orginal problem
Ex: return n*factorial(n-1)
Recursion Terminate
terminates when the sequence of smaller problems equals or converges to the base case
Iteration Control Statement
repetition (loops)
Iteration Repetition Involved
repeated loop body
Iteration Termination
when the loop condition fails
Iteration Performance
usually quicker than recursion
Recursion Control Statement
conditional statements (branching aka if,elif, and else)
Recursion Rpeetition Involved
repeated function calls
Recursion Performance
singnificant overhead (run time) due to repeated function calls
Accesing Characters in a String
string_name[index]
String Slices
string_name[start:step]
a segement of a string
len() function strings
reutnrs the number of characters in the string
the ‘in’ operator string
a boolean operator that takes two stirngs and returns True if the first operatorappears as substring in the second
Ex: ‘a’ in ‘banana’ → True ; ‘seed’ in ‘banana’ → False
String Compariosn == and !=
check if two strings are equal
String Comparison >,<,>=, and <=
use lexicographical comparison of strings
Lexicographical comparison
comparing string based on the order of thier elements; comparison stops at the first position where elements differ
Python String Formatting
f “string { }”
Escpae Charaters
a baclash followed by character you want to insert
can insert special characters in a string
Ex: print(“He said to me, “\How are you?\” with a smile. ”)
Quote
\’ or \”
Backlash
\\
prints a \ in a string
New Line
\n
Carriage Return
\r
overwrite the existing content on that same line from the beginning, effectively replacing the previously printed characters
Tab
\t
Backspace
\b
deletes character it follows a in string
Slice Assignment (List)
use the slice operator on the left side of an assignment to update multiple lsit elements
Deleting List Elements
use ‘del’ operator to delete one or a slice of list elements
List Operations ‘+’
The operator combines the list to form a new list
[1,2,3] + [4,5,6] → [1,2,3,4,5,6]
List Operator ‘*’
the operator returns a list that repeats the original list a given number of times
[2,4,6]*3 → [2,4,6,2,4,6,2,4,6]
len() fucntion in list
function returns the number of elements in the list
len([‘spam’,2.0,5,[10,20]])==4
min() and max()
return the min and max elements of a list respectively
will say an error if the list has an items of mixed type
sum () function list
calculates the summation of numbers in the list
sum([2.0, 5, 10, 20]) → 37.0
List updating
slice assignment meaning the orginal and updated lists are the same object
id() function and ‘is’ operator
check if two variables refer to the same object
List Comprehension
newlist = [espression for item in oldest if condition]
offers a concise syntax to create a new list based on the items of an existing list
slicing list
creates a new list
slice assingment lists
modifies the exisitng list
Multi-Dimensional Lists
list_name[row_index][column_index]
Ex: a[2][-4]==8
Multi-dimnensional list comprehension
creates a m x n matrix where m is the number of rows and n is the number of columns
Tuples
a sequence of values where values can be ANY type, values are ordered, and duplicate values are allowed
Tuple Operators Invalid
can NOT add or remove from a tuple once created and can NOT append to or extend a tuple
Tuple Operators Valid
‘+’ and ‘*’ operators
len(), sum(), max(), min() functions
compare lexicogrpahically
‘del’
sorted()
sort the tuple alphabetically
Tuple Assignment
can assign multiple values to multiple variables all on one line (unpacking)
Ex: (a,b,c,d) = (1,2,’xyz’,True)
List Mutability
mutable (can be modified after creation)
List Syntax
defined using square brackets [ ]
List Methods
has more built in methods (ex: append, remove)
List Use Cases
suitable for collections of items that may change
LIst Memory Usage
consumes more memroy due to flexibility
List Iteration
iteration can be slightly lower
List Performance
slower due to dynamic size and mutability
Tuple Mutability
immutable (cannot be modified after creation)
Tuple Syntax
defined using parentheses ( )
Tuple Methods
fewer built in methods
Tuple Use Cases
ideal for fixed collections of items
Tuple Memory Usage
consumes less memory due to immutability
Tuple Iteration
iteration faster due to immutability
Tuple Performance
faster due to static size and immutability
Sets
a collection of items enclosed by curly brackets { }
and are unordered so can NOT be referred to by index and duplicate vlaues are NOT allowed
Ex: fruits= {“apple”, “banana”, “cherry”}
Add Set Items
add() function to add one item to a set
update() function to add items from another set, lidt or tuple to a set
both in place changes
Delete Set Items
remove() and discard() fucntions to remove an item
Empties set
clear() function
‘del’ opetator set
deletes set completely
List to Tuple Conversion
list1=[0,1,2]
tuple(list1) → (0,1,2)
Set Conversion to other Data Structures
set() function
Ex: x = set((“apple”, “banana”, “cherry”)) or
n = set([0,1,2,3,4])
Set Method difference()
returns the difference between two or more sets
Set Method intersection()
returns the interaction of two oe more sets
Set Method isdisjoint()
returns whether two sets have an interaction or not
Set Method issubset()
returns whether another set contains this set or not
Set Method issuperset()
returns whether this set contains another set or not
Set Method symmetric_difference()
returns the symmetric differneces of two sets
Set Method union()
reutrns the union of sets
String Modifier :<
left aligns the result
String Modifier :>
right aligns the result
String Modifier :^
center aligns the result
String Modifier :+
use a plus sing to indicate if the result is positive or negative
String Modifier :
use a space to insert an extra space before positive numbers and aminus sign before negative numbers
String Modifier :,
use a underscore as a thousand separator
String Modifier :b
binary format
String Modifier :d
decimal format
String Modifier :e or :E
scientific format
String Modifier :f
fix point number format
String Modifier :%
percentage format
Iterable
an object that can be looped over or ‘iterated’ through one element at a time
capable of returning its member value one by one