Professional Documents
Culture Documents
Chapter 05 - If Statements 5
if Statements 5
Chapter 06 - Dictionaries 5
Looping 6
Nesting 6
Chapter 08 - Functions 7
Type of arguments 7
Optional arguments 7
Passing a list 7
Functions in Modules 7
Chapter 09 - Classes 8
Inheritance 8
Chapter 02 - Variables and Simple Data Types
Variables
● Names can be letters, numbers and underscore
● Can’t start with a number
● Remember, variables are like ‘labels’ (memory references) not as box containers
● B.p.: lowercase
● global allows you to modify the variable outside of the current scope
Strings
● String: series of characters
● Can use “ or ‘, doesn’t matter.
● Special functions:
○ title() - capitalize every initial word letter
○ capitalize() - capitalize first letter of first word
○ upper() - uppercase for all letters
○ lower() - lowercase for all letters
○ lstrip(), rstrip(), strip() - remove left, right or both ‘white spaces’
● Format strings using letter f as prefix (i.e. f”hello world”)
○ Works for python 3.6 and above
○ Before it was used “{}”.format(variable_name)
● Special escape values:
○ \t - tab
○ \n - new line
Numbers
● They can be integers & floats
● Python defaults to a float in any operation that use a float
● Dividing two integers results always in a float
● You can use ‘_’ underscore in numbers to make them more readable
○ Works for python 3.6 and above
● You can assign values to more than one variable in a single line
○ a, b, c = 1, 2, 3
● Constants variables use all capital letters.
Operators
● / classic division
○ >>> 5/2
○ 2.5
● // floor division
○ >>> 5//2
○ 2
● % modulo (division)
○ >>> 5 % 2
○ 1
● The order of operations (precedence) is similar to that of mathematics:
○ the ** operator is evaluated first;
○ the *, /, //, and % operators are evaluated next, from left to right;
○ and the + and - operators are evaluated last (also from left to right).
○ You can use parentheses to override the usual precedence if you need to
Booleans
● when used in conditions,
○ 0 (int), 0.0 (float), and '' (empty string) are considered False
○ all other values are considered True
Comments
● Use # for a comment in one line
Indexes
● positions starts at 0
● Negative index positions starts at the end of the list
Manipulating a list
● .append(new_element) - Add element at the end of a list
● .extend(list_element) - Add a list of elements (list_element) to the list
● .insert(i, new_element) - inserts element at index i
● Removing items
○ del list[i] - removes item at index i
○ list.remove(xxx) - removes item with value xxx
● item = list.pop() - removes last item and assigns it to a variable
Organizing a list
● .sort() - from A to Z
● .sort(reverse=True) - from Z to A
● sorted(list) - sort temporarily a list without modifying it
● .reverse() - reverse a list
● len(list) - returns number of items in the list
● sorted(list,reverse=True) - reverse a list temporarly
Looping
for item in list:
code
else:
code
Special functions
● range(start, end, step) - generate a series of numbers
○ Remember that range stops when reach ‘end’ (doesn’t process it)
○ Step size - value to bypass numbers when generating them
● Maths
○ min()
○ max()
○ sum()
Slicing a list
● List[start:end]
○ start is inclusive, end is excluded
○ If start is empty, starts at the beginning of the list
○ If end is empty, finish at the end of the list
○ If using a negative index, starts at the end of the list
● [::n]
○ nothing for the first argument, nothing for the second, and jump by n
○ i.e.
■ nums = [1, 2, 3, 4, 5, 6, 7]
■ print(nums[::-3])
■ >> [7, 4, 1]
Copying a list
● We can use an empty slice like list[:] and assign to a variable
○ i.e. newlist = oldlist[:]
○ If dont slicing -> var1 will link to var2 instead of copying.
Tuples
● They are immutable lists (can’t change)
○ Can’t change but we can assign to the variable a new tuple
● Use parentheses () instead of square brackets []
● For a one item tuple you need to add a comma
○ i.e. new_tuple = (4,)
Chapter 05 - If Statements
● == to check equality
● != to check inequality
● and
● or
● item in list - check if an item is in a list
● item not in list - check if an item is not in a list
if Statements
if conditional_test:
do something
elif conditional_test:
do something
else:
do something
Chapter 06 - Dictionaries
● Dictionaries are wrapped in braces {}
● Collection of key-value pairs.
● Creating a dictionary like:
○ ndict = {‘keya’: 1, ‘keyb’: 2}
○ or
○ ndict = {}
○ ndict[‘keya’] = 1
○ ndict[‘keyb’] = 2
● Accessing values
○ through the key
■ ndict[‘keya’]
○ through .get() function
■ ndict.get(‘keyz’,’value if key doesn’t exist’)
● Removing a key-value pair
○ del ndict[‘keya’]
Looping
for k, v in ndict.items():
print(‘Key is {k}’)
print(‘Value is {v}’)
Nesting
● A list of dictionaries
● A dictionary with lists
● A dictionary with dictionaries
● Use while loops with lists / dictionaries when you need to modify them (instead of for
loops)
○ Specially when removing items
Chapter 08 - Functions
def function_name(arguments):
code
Type of arguments
● Positional arguments: maintains the order of arguments
● Keyword arguments: name-value pair passed to a function.
● Undefined arguments (Must be placed the last in the function definition)
○ Tuple: *args
○ Dictionary: **kwargs (key-word args)
Optional arguments
● Use default value to make an argument optional
● Must go at the end of the arguments
Passing a list
● Inside the function, the list can be updated
● If you want to not update the list, pass a copy of the list
○ i.e. function_name(list[:])
Functions in Modules
● import module_name
○ python opens the file and copy all functions into the program
○ use module_name.function_name()
● import module_name as alias
○ similar to the previous one but giving an alias
○ use alias.function_name()
Chapter 09 - Classes
class Name_class:
def __init__(self):
code
Inheritance
class Name_class(MasterClass):
def __init__(self):
super().__init__(self)
code