python filename.py
pip install module
pip install camelcase
a = 1 # int b = 2.5 # float first_name = 'Brad' # str is_great = True # bool
x, y, name, is_cool = (10, 2.5, 'Brad', True) print(x) print(x, y, name, is_cool)
a = x + y print(a) a += 2 a -= 2 a *= 2
x = str(x) y = int(y) z = float(y)
print(type(z)) # <class 'float'></class>
a = "helloooooooo" if (n:= len(a) > 10): print(f'too long {n} elements')
#1 - start with local #2 - Parent local - for variables in function inside function #3 - Global #4 - build in Python functions ############### nonlocal # used for variables in function inside function ############## global - not a good solution total = 0 def count(): global total # global total variable will be used here total += 1 return total print(count())
res = 10 / 3 # 3.3333333333333335 res = 10 % 3 # 1 modulo = remainder of the division res = 10 ** 3 # 1000 - power of 10 res = 10 / 3 # 3.3333333333333335 res = 10 // 3 # 3 - result of the division rounded down to an integer x = 10 x += 3 x -= 3 # x = x - 3 x *= 2 x /= 2
import math x = 2.9 round(x) # 3 y = -5.3 abs(y) # 5.3 math.ceil(x) # 3 math.floor(x) # 2
# int # float # bool True or False # str # list numbers = [6,10,1,2,6] # ordered and changeable # [1, 2, 'be', True, 2] # tuple # set fruit_set = {'Apples', 'Oranges', 'Mango'} # dict {'name': 'John', 'age': 36} # ordered, changeable. No duplicate members. # None bin(5) # 0b101 - a binary representation int('0b101', 2) - # 5 - converts base 2 value into an int
Classes
packages / modules
name = input('What is your name? ') print('Hello, ' + name)
year = input('What year were you born? ') age = 2022 - int(year) print('You are ' + str(age) + ' years old.')
weight = input('What is your weight in pounds? ') weight_kg = float(weight) * 0.45 print('Your weight in kilograms is ' + str(weight_kg))
print("Hello World")
print('*' * 10) # Prints 10 asterisks
price = 10 print(f' {price} dollars')
# Print and don't add a new line for i in range(10): # gives a sequence of numbers 0 to 9 print(i, end=' ')
# This is a comment
''' This is a multiline comment or docstring (used to define a functions purpose) can be single or double quotes. '''
""" This is a multiline comment too. """
Strings in python are surrounded by either single or double quotation marks. Strings are immutable, so my_str[1]='a' will give an error. Instead reassign a value. my_str.replace('be', 'me') creates a new string.
name = 'Raya' city = "Haifa" long_string_on_multiple_lines = ''' WOW 0 0 --- ''' first_name = 'John' last_name = 'Doe' full_name = first_name + ' ' + last_name print(f'My name is {name}') len(name) # 4 name.upper() # uppercase 'RAYA' name.lower() # lowercase name.title() # title case 'Raya', 'Hello World' name.find('a') # 1 - index of a name.replace('a', 'e') # Raye 'ra' in name # True # in print('R' in name, '!!!') # True age = 28 # String Concatenation print('Hello I am ' + name + ' is ' + str(age)) # Escape sequence weather = "It's sunny" weather = 'It\'s sunny' weather = "It\'s \"kind of\" sunny" # String Formatting # F-Strings = Formatted Strings (only in 3.6+)!!!!!! print(f'My name is {name}') # Arguments by position - old way print('{}, {}, {}'.format('a', 'b', 'c')) print('{1}, {2}, {0}'.format('a', 'b', 'c')) # Arguments by name - old way # print('My name is {name} and I am {age}'.format(name='Raya', age='37')) # print('My name is {name} and I am {age}'.format(name=name, age=age)) # String Methods # https://www.w3schools.com/python/python_ref_string.asp s = 'hello there world' # Capitalize first letter print(s.capitalize()) # Make all uppercase print(s.upper()) # Make all lowercase print(s.lower()) # Swap case print(s.swapcase()) # Get length print(len(s)) # Replace print(s.replace('world', 'everyone')) # Count sub = 'h' print(s.count(sub)) # String Comparison s1 = 'String' s2 = 'String' if s1.lower() == s2.lower(): print('Equal') # Starts with print(s.startswith('hello')) # Ends with print(s.endswith('d')) # Starts with print(s.startswith('hello')) # Split into a list print(s.split()) # Find position print(s.find('ra')) # Is all alphanumeric - numbers and letters print(s.isalnum()) # Is all alphabetic - all letters, no numbers print(s.isalpha()) # Is all numeric print(s.isnumeric()) # String indexes # [start:stop] - stop is not included # [start:stop:stepover_by] - stop is not included s[0:len(s)] # from start to the end print(s[0]) # First character is 0 print(s[-1]) # Last character is -1 print(s[-2]) # Second to last character is -2 print(s[0:5]) # Characters from 0 to 5 print(s[:5]) # Characters from 0 to 5 print(s[5:]) # Characters from 5 to end print(s[0:]) # Characters from 0 to end print(s[0:5:2]) # Characters from 0 to 5, every 2nd character print(s[::-1]) # Characters from end to 0, backwards == reverse of the string print(s[::-2]) # Characters from end to 0, every 2nd character backwards print(s[::-3]) # Characters from end to 0, every 3rd character backwards print(s[::-4]) # Characters from end to 0, every 4th character backwards another = s[:] # Copy of string print('Another ' , another) # Characters from 0 to end print(another[1:-1]) # Characters from 1 to the last, not included first = 'John' last = 'Smith' message = f'{first} [{last}] is a coder' print(message) message1 = first + ' [' + last + '] is a coder' # Phone task phone = input('Phone: ') for ch in phone: print(ch)
A List is a collection which is ordered and changeable. Allows duplicate members. List is like an array.
# Create list numbers = [6,10,1,2,6] list2 = [1, 2, 'be', True] fruits = ['Apples', 'Oranges', 'Grapes', 'Pears'] # List slicing - creates a new copy of the list # [start:stop:stepover] fruits[0::2] print(type(numbers)) ;"""<class 'list'>""" numbers.index(10) # index of 3 # in operator print(5 in numbers) # True or False # how many times an item occurs numbers.count(2) # counts a number of 2 # Get value print(fruits[1]) # Create a list using a constructor numbers = list((1,2,3,4,5)) print(numbers) ; # [1, 2, 3, 4, 5] # Get last value (the first element from the end) print(numbers[-1]) # 5 # Get second to last value print(numbers[-2]) # 4 # Get length print(len(fruits)) ; # 4 # Append to the end of the list fruits.append('Mangos') # Insert into position fruits.insert(2, 'Strawberries') # Remove a value from list fruits.remove('Grapes') # Remove the last item fruits.pop() # 'Mangos' # Remove the last item fruits.pop(-1) # 'Pears' # Remove from position fruits.pop(2) # Remove an item by position del fruits[0] # doesn't return anything # Index - get index of value fruits.index('Apples') fruits.index('Apples', 0, 4) # value, start index, stop index, stop is not included # Reverse list fruits.reverse() ################################# # Sort list fruits.sort() # ascending order. Now it's ['Apples', 'Grapes', 'Oranges', 'Pears'] # Sort list in descending order fruits.sort(reverse=True) # Now it's ['Pears', 'Oranges', 'Grapes', 'Apples'] # Create a new sorted list list3 = sorted(fruits) ################################# # Update value fruits[0] = 'Blueberries' # ['Blueberries', 'Grapes', 'Oranges', 'Pears'] ################################# # Extend a list by adding several values at the end numbers.extend([100, 101]) # [1, 2, 3, 4, 5, 100, 101] # List of many numbers my_list = list(range(1,100)) # 1 - 99, 100 is not included my_list = list(range(101)) # 0 - 100 # Join two lists list1 = [1,2,3] list2 = [4,5,6] list3 = list1 + list2 # [1, 2, 3, 4, 5, 6] # Split a string into a list sentence = 'My name is John' sentence.split() # ['My', 'name', 'is', 'John'] # Join list into a string list1 = ['My', 'name', 'is', 'John'] sentence = ' '.join(list1) # 'My name is John' # a string of items separated by space # Nested lists matrix = [ [1,2,3], [4,5,6], [7,8,9] ] ################################# # Copy a list list2 = fruits.copy() list3 = list(fruits) list4 = fruits[:] # copy of whole the list ################################# # Slicing # my_list[start:stop] # stop is not included # my_list[start:stop:stepover] # Get first two values numbers = list((1,2,3,4,5)) print(numbers[:2]) # [1, 2] # Get from second to last element print(numbers[1:]) # [2, 3, 4, 5] # Get from the beginning to the second element print(numbers[:2]) # [1, 2] # Unpacking coordinates = [1, 2, 3] # x = coordinates[0] # y = coordinates[1] # z = coordinates[2] # This is the same: x, y, z = coordinates a,b, c, *other = [1,2,3,4,5,6,7,8,9] # other = [4,5,6,7,8,9] a,b, c, *other, d = [1,2,3,4,5,6,7,8,9] # other = [4,5,6,7,8] , d = 9 # List Comprehensions my_list = [ch for ch in 'hello'] # ['h', 'e', 'l', 'l', 'o'] my_list2 = [num for num in range(0,100)] # [0, 1, 2, ..., 99] my_list3 = [num*2 for num in range(0,100)] # [2, 4, 6 ..., 196, 198] my_list4 = [num**2 for num in range(0,100) if num % 2 == 0] # [0, 4, 16 ..., 9216, 9604] # Remove the duplicates in the list numbers = [6,10,1,2, 6, 3,4,5,2,1] unique_list = [] for item in numbers: if item not in unique_list: unique_list.append(item) print(f'Unique: {unique_list}') ####################### # Find duplicates only some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] duplicates = [] for item in some_list: if some_list.count(item) > 1 and item not in duplicates: duplicates.append(item) print(duplicates) ##################### # Find duplicates only - using list comprehension some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] duplicates_2 = list(set([ch for ch in some_list if (some_list.count(ch) > 1)])) print(f'My duplicates: {duplicates_2}') ####################### # Reverse a list reversed_numbers = numbers[::-1] print(f'Reversed numbers: { reversed_numbers}')
class Utils: @staticmethod def merge_two_lists(list_1, list_2): return list_1 + list_2
my_matrix = [ [1,2,30], [4,5,6], [7,8,9] ] print(my_matrix[0][2]) # Example picture = [ [0,0,0,1,0,0,0], [0,0,1,1,1,0,0], [0,1,1,1,1,1,0], [1,1,1,1,1,1,1], [0,0,0,1,0,0,0], [0,0,0,1,0,0,0]] for row in picture: for pixel in row: if pixel: print('*', end='') else: print(' ', end='') print('')
A Dictionary is an ordered key - value pairs. Recently, the Python has made Dictionaries ordered by default! So unless you need to maintain older version of Python (older than 3.7), you no longer need to use ordered dict, you can just use regular dictionaries! You can read more about it here: https://softwaremaniacs.org/blog/2020/02/05/dicts-ordered/en/
# Simple dictionary person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 30 } mapping = { "a": "One", "b": [1,2,3], "c": True } mapping['b'][1] # 2 # Create a dictionary empty_dict = dict() # Using a constructor person = dict( first_name='John',last_name= 'Doe', age=30 ) # Access value print(person['first_name']) print(person.get('last_name')) print(person.get('color', "blue")) # default value # Add key and value person['phone'] = '555-555-555' ######################################## # Get dict keys print(person.keys()) # dict_keys(['first_name', 'last_name', 'age', 'phone']) # Get dict values print(person.values()) # dict_values(['John', 'Doe', 30, '555-555-555']) # Get items - keys and values - list of tuples print(person.items()) # dict_items([('first_name', 'John'), ('last_name', 'Doe'), ('age', 30), ('phone', '555-555-555')]) ######################################## # Get keys - the second way for item in person: print(item) print('-----------------') for key, value in person.items(): print(key, value) # Make copy person2 = person.copy() # Add person2['city'] = 'Boston' # Update value person2.update({'city': 'Haifa'}) ################################## # Remove item person.pop('phone') # '555-555-555' # Remove item del (person2['age']) # Clear person.clear() # {} - removes all keys - values pairs ################################## # Get length print(len(person)) # List of dictionaries people = [ { 'name': 'Martha', 'age': 30 }, { 'name': 'Kevin', 'age': 25 } ] print(people) print(people[1]) print(people[1]['name']) simple_dict = { 'a': 1, 'b': 2 } my_dict = { key:value**2 for key, value in simple_dict.items() } # {'a': 1, 'b': 4} my_dict1 = { key:value**2 for key, value in simple_dict.items() if value % 2 == 0} # {'b': 4} - only even values my_dict2 = { num: num*2 for num in [1,2,3]} # { 1: 2, 2: 4, 3: 6 } # Phone task digits_mapping = { "1": "One", "2": "Two", "3": "Three", "4": "Four" } phone = input('Phone: ') output = '' for ch in phone: output += digits_mapping.get(ch, "My default value") + ' ' print(output) # Emoji Converter emojis = { ":)": "😀", ":(": "😔" } message = input('>') words = message.split(' ') # create a list output = '' for word in words: output += emojis.get(word, word) + ' ' print(output)
# Create a new dictionary from the old one with keys in lowercase my_dictionary = {'One': 1, 'Two': 2, 'Three': 3} new_dictionary = {key.lower(): value for key, value in my_dictionary.items()} # Print the new dictionary print(new_dictionary)
A Tuple is a collection which is ordered and unchangeable. Allows duplicate members. Tuple is immutable - constant values
# Simple tuple fruit_tuple = ('Apples', 'Oranges', 'Mango') # Using a constructor # fruit_tuple = tuple(('Apples', 'Oranges', 'Mango')) # Get a single value print(fruit_tuple[1]) # Can't change value # fruit_tuple[1] = 'Grapes' # Error print(fruit_tuple) # Get the length of a tuple print(len(fruit_tuple)) # Number of times a specified value occurs in a tuple fruit_tuple.count('Apples') # Index fruit_tuple.index('Apples') # Tuples with one value should have a trailing comma fruit_tuple_2 = ('Apples',) del fruit_tuple_2 # Delete tuple # Unpacking coordinates = (1, 2, 3) # x = coordinates[0] # y = coordinates[1] # z = coordinates[2] # This is the same: x, y, z = coordinates x,y,z, *other = (1,2,3,4,5) # other = [4,5] # Slicing my_tuple = (1,2,3,4,5) new_tuple = my_tuple[1:4] # (2,3,4) print(new_tuple)
A Set is a collection which is unordered and unindexed. No duplicate members.
# Create a set fruit_set = {'Apples', 'Oranges', 'Mango'} print(fruit_set) # Check if in set print('Apples' in fruit_set) # True # Add to set fruit_set.add('Grapes') # Remove from set fruit_set.remove('Grapes') # Copy new_set = fruit_set.copy() # Clear set fruit_set.clear() # Delete set del fruit_set my_set = {1,2,3,4,5} your_set = {4,5,6,7,8,9,10} # Difference my_set.difference(your_set) # {1,2,3} # Discard - remove if it's a member my_set.discard(5) # {1,2,3,4} # Difference_update - remove all elements of another set from this set my_set.difference_update(your_set) # Intersection my_set.intersection(your_set) # {4,5} new_set = my_set & your_set # Is disjoint - True if two sets have null intersection - nothing in common my_set.isdisjoint(your_set) # Union my_set.union(your_set) all_values = my_set | your_set # union # Is sub set my_set.issubset(your_set) # Is super set - contains everything that other set has my_set.issuperset(your_set) # Set Comprehensions my_set = {ch for ch in 'hello'} # {'h', 'e', 'l', 'l', 'o'} my_set2 = {num for num in range(0,100)} # {0, 1, 2, ..., 99} my_set3 = {num*2 for num in range(0,100)} # {2, 4, 6 ..., 196, 198} my_set4 = {num**2 for num in range(0,100) if num % 2 == 0} # {0, 4, 16 ..., 9216, 9604} ################### # Return only unique items my_list = [1,2,2,3,4,4] unique_values = set(my_list) print(unique_values)
# Set fruit_set = {'Apples', 'Oranges', 'Banana', 'Mango'} # Check if 'Banana' is present in the set case insensitively for fruit in fruit_set: if fruit.lower() == 'banana': print('Banana is present in the set') break
# If/ Else conditions are used to decide to do something based on something being true or false x = 10 y = 106 # Comparison Operators (==, !=, >, <, >=, <=) - Used to compare values ################################## if x > y: print(f'{x} is greater than {y}') elif x == y: print(f'{x} is equal to {y}') else: print(f'{x} is less than {y}') ################################## # Logical operators (and, or, not) - Used to combine conditional statements # and if x > 2 and x <= 10: print(f'{x} is less than 2 and greater than 10') # or if x > 2 or x <= 10: print(f'{x} is less than 2 or greater than 10') # not if not(x == y): print(f'{x} is not equal to {y}') # Membership Operators (not, not in) - Membership operators are used to test if a sequence is presented in an object numbers = [1,2,3,4,5] # in if x in numbers: print(f'{x} is in {numbers}') # not in if x not in numbers: print(f'{x} is not in {numbers}') # Identity Operators (is, is not) - Compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: # is if x is y: print(f'{x} is the same as {y}') print(x is y) # is not if x is not y: print(f'{x} is not the same as {y}') print(x is not y) # Ternary Operator is_friend = True can_message = "message allowed" if is_friend else "not allowed" ############################################ # Simple if if x == y: print(f'{x} is equal to {y}') if x > y: print(f'{x} is greater than {y}') elif x == y: print(f'{x} is equal to {y}') else: print(f'{x} is less than {y}') # If/else if x > y: print(f'{x} is greater than {y}') else: print(f'{x} is less than {y}') # elif if x > y: print(f'{x} is greater than {y}') elif x == y: print(f'{x} is equal to {y}') else: print(f'{x} is less than {y}') # Nested if if x > 2: if x <= 10: print(f'{x} is less than 2 and greater than 10') # Logical operators (and, or, not) - Used to combine conditional statements # and if x > 2 and x <= 10: print(f'{x} is less than 2 and greater than 10') # or if x > 2 or x <= 10: print(f'{x} is less than 2 or greater than 10') # not if not(x == y): print(f'{x} is not equal to {y}') # Membership Operators (not, not in) - Membership operators are used to test if a sequence is presented in an object numbers = [1,2,3,4,5] # in if x in numbers: print(f'{x} is in {numbers}') # not in if x not in numbers: print(f'{x} is not in {numbers}') # Identity Operators (is, is not) - Compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: # is if x is y: print(f'{x} is the same as {y}') print(x is y) # is not if x is not y: print(f'{x} is not the same as {y}') print(x is not y) #################################### price = 1000000 has_good_credit = True if has_good_credit: down_payment = 0.1 * price else: down_payment = 0.2 * price print(f'Down payment: ${down_payment}')
enumerate is used when we need an index counter
for indx, char in enumerate('Hellloooo'): print(indx, char) ############### Task find the index of number 50 for i, number in enumerate(list(range(100))): if number == 50: print(f'The index of 50 is {i}')
for <variable> in <iterable>: <code>#######################################
for <variable> in <list>: <code>#######################################
countries = ['Usa', 'Canada', 'Mexico', 'France', 'Germany'] # List for indx, country in enumerate(countries): # enumerate returns a tuple of index and value <code>#######################################
my_dict = {'name': 'John', 'age': 30, 'country': 'Norway'} # Dictionary for key, value in my_dict.items(): # list of tuples of index and value print(key) # prints the key: name, age, country print(value) # prints the value: John, 30, Norway#######################################
people = ['Dr. Christopher Brooks', 'John', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero'] # Simple for loop for person in people: print('Current person: ', person) print('============') # Break out of loop for person in people: print('Current person: ', person) if person == 'John': break print('============') # Continue in loop for person in people: if person == 'John': continue print('Current person: ', person) print('============') # range - the max is not included for i in range(len(people)): # a sequence of numbers from 0 to len(people) print('Current person: ',i, people[i]) for i in range(0, 11): # - the max is not included print('Number: ', i) for name in ['Raya', 'John', 'Mosh']: print(name) prices = [10, 20, 30] total = 0 for item in prices: total += item print(f'Total: {total}') for _ in range(10): # _ is used instead of defining a variable print(_) # While loops execute a set of statements as long as a condition is true. count = 0 while count < 10: print('Count: ', count) count += 1 # While with break and else count = 0 while count < 10: print('Count: ', count) count += 1 if count == 5: break # will lead to finish while and step over the else else: print('While is done!!!') # only if while was fully done # F shape numbers = [5, 2, 5, 2, 2] for i in numbers: print('*' * i) print() # F shape for i in numbers: line = '' for j in range(i): line += 'x' print(line) # Find max in a list my_list = [5, 7, 40, 2] max = my_list[0] for item in my_list: if max < item: max = item print(f'Max: {max}')
# Create function def sayHello(name='John Doe'): """ Prints Hello and then the name. """ print('Hello ' + name) return name # Run a function sayHello() sayHello('Brad') # Return values def getSum(num1, num2): total = num1 + num2 return total print(getSum(1, 4)) numSum = getSum(2, 5) print(numSum) def addOneToNum(num): num += 1 return num print(addOneToNum(5)) # *args - Any number of arguments def myfunc(*args): return sum(args) print(f'Sum: {myfunc(1,2,3,4,5)}') # **kwargs - keywords arguments # Rule: the order is: params, *args, default parameters, **kwargs def myfunc1(*args, **kwargs): total = 0 for item in kwargs.values(): total += item return sum(args) + total print(f'Next Sum: {myfunc1(1,2,3,4,5, num1=5, num2=10)}') # A lambda function is a small anonymous function. # A lambda function can take any number of arguments, but can only have one expression. Very similar to JS arrow functions getSum = lambda num1, num2 : num1 + num2 print(getSum(9,2)) addOneToNum = lambda num: num + 1 print(addOneToNum(8)) # docstrings def my_func(a): ''' Info: this function tests and prints param a ''' print(a) print(help(my_func)) # prints info of the function print(my_func.__doc__) # prints info of the function
range(start, stop, step)
range(stop)
range(start, stop)
range(1, 10, 2) # 1, 3, 5, 7, 9 for i in range(1, 10, 2): print(i) # 1, 3, 5, 7, 9
# map(action, iterable)
def multiply_by2(item): return item*2 res = list(map(multiply_by2, [1,2,3])) print(res)
def is_odd(item): return item % 2 != 0 my_list = [1,2,3] res = list(filter(is_odd, my_list)) print(res) # [1, 3]
my_list = [1,2,3] your_list = [10,20,30] their_list = (5, 10, 15) res = list(zip(my_list, your_list)) print(res) # [(1, 10), (2, 20), (3, 30)] res = list(zip(my_list, your_list, their_list )) print(res) # [(1, 10, 5), (2, 20, 10), (3, 30, 15)]
from functools import reduce # !!! important to do my_list = [1,2,3] def accumulator(acc, item): print(acc, item) return acc + item res = reduce(accumulator, my_list, 0) print(res)
lambda expression is a one time anonymous function lambda param: action(param)
from functools import reduce # !!! important to do my_list = [1,2,3] # def multiply_by2(item): # return item*2 # res = list(map(multiply_by2, my_list)) res = list(map(lambda item: item*2, my_list)) print(res) # Have only odd values res = list(filter(lambda item: item % 2 != 0, my_list)) print(res) res = reduce(lambda acc, item: acc + item, my_list, 0) print(res) # Exercise: power of 2 res = list(map(lambda item: item**2, my_list)) print(res) # Exercise: # List Sorting based on the second value a = [(9,9), (0,2), (4,3), (10, -1)] a.sort(key=lambda x: x[1]) # the second value in the tuple print(a)
from time import time def my_performance(fn): def wrapper_func(*args, **kwargs): t1 = time() result = fn(*args, **kwargs) t2 = time() print(f'Took {t2 - t1} seconds') return result return wrapper_func @my_performance # this is a decorator !!! def long_time(): for i in range(1000000): i*5 print('Done!') long_time()
# def check_number(self, number): def check_number( number): match number: case 0: return 'zero' case 1: return 'one' case 2: return 'two' case _: return "Invalid num" print(check_number(2))
try: age = int(input(' What is your age? ')) except ValueError: print('Please enter a number') except Exception as e: print(e) except: print("Something went wrong") else: print("Nothing went wrong") finally: print("The 'try except' is finished")
x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed")
while True: try: age = int(input(' What is your age? ')) num = 10/age print(age) except ValueError: print('Please enter a number') except ZeroDivisionError: print('Please enter age higher than 0') else: print('Thank you!') break finally: print('Ok, I am finally done')
def my_sum(num1, num2): try: return num1 + num2 except TypeError as err: print(f'Please enter numbers!!! {err}') print(err) except (TypeError, ZeroDivisionError): # just an example print('Ooops') except (TypeError, ZeroDivisionError) as error: # just an example print(error) except: print('Something is wrong!!!') print(my_sum('1', 2))
# Throw my error using raise def my_func(num1, num2): try: num1 / num2 # raise ValueError('hey cut it out') # example raise Exception('hey cut it out') except TypeError as err: print(f'Please enter numbers!!! {err}') print(err) my_func(4, 10)
# Generator # Example: range def gen_fun(num): for i in range(num): yield i
A module is basically a file containing a set of functions to include in your application. There are core python modules, modules you can install using the pip package manager (including Django) as well as custom modules.
# import datetime from datetime import date import email # import time from time import time
import camelcase
from my_validator import validate_email # today = datetime.date.today() today = date.today() # timestamp = time.time() timestamp = time() camel = camelcase.CamelCase() text = "hello there world" # print(camel.hump(text)) # print(today) # print(timestamp) email = 'test@test.com.' # if validator.validate_email(email): if validate_email(email): print(f'The email address {email} is valid.') else: print(f'The email address {email}
my_validator.py file: import re def validate_email(email): if len(email) > 7: return bool(re.match("^.+@(\[?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", email))
import random # from random import shuffle # import random as aaa print(random.random()) print(random.randint(1, 20)) # random integer between 1 and 20 print(random.choice([1,2,3,4,5])) my_list = [1,2,3,4,5] random.shuffle(my_list) print(my_list)
from collections import Counter, defaultdict, OrderedDict li = [1,2,3,4,5,6,7, 7] sentence = 'blah blah blah thinking about counter' print(Counter(li)) # Creates a dictionary - Counter({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1}) print(Counter(sentence)) # Creates a dictionary - Counter({' ': 5, 'b': 4, 'a': 4, 'h': 4, 'l': 3, 't': 3, 'n': 3, 'i': 2, 'o': 2, 'u': 2, 'k': 1, 'g': 1, 'c': 1, 'e': 1, 'r': 1}) dictionary = defaultdict(lambda: 'Does not exist', {'a': 1, 'b': 2}) # If value doesn't exist, use the default value print(dictionary['d']) d = OrderedDict() d['a'] = 1 d['b'] = 2 d2 = OrderedDict() d2['a'] = 1 d2['b'] = 2 print(d2 == d) # True d3 = OrderedDict() d3['b'] = 2 d3['a'] = 1 print(d3 == d2) # False
from array import array # array takes less memory than list and perform faster arr = array('i', [1,2,3]) # i unsigned int print(arr[0])
import sys first = sys.argv[1] last = sys.argv[2] print(f'Hello {first} {last}!')
import os print(os.getcwd()) # current working directory - /Users/james/python_course print(os.listdir('.')) # list files in current directory - ['my_file1.py', 'my_func.py'] os.chdir('/Users/james/Desktop') # change directory - /Users/james/Desktop os.mkdir('my_new_folder') # create a new folder - /Users/james/Desktop/my_new_folder
To install external packages use pip Pip comes with Python installation Run from the terminal to see the version: pip -V pip install some_package pip install some_package==0.4.0 pip uninstall some_package pipenv
import datetime print(datetime.time()) # 00:00:00 print(datetime.time(5,45,22)) # 05:45:22 print(datetime.date.today()) # 2022-03-25 from time import time print(time()) # 1648221746.0547843
from datetime import datetime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Start, Current Time =", current_time)
# The better way # We don't need to close the file # 'r+' mode is for read and write # 'w' mode is for creating a file and writing to a file # 'a' mode is for append with open('myfile.txt', 'r+') as myFile: print(myFile.readlines()) # list of lines myFile.write('\n I love you!') try: with open('app/myfile.txt', 'r+') as myFile: print(myFile.readlines()) # list of lines except FileNotFoundError as err: print('File does not exist') except IOError as err: print('IO error') ############### # Create / open a file myFile = open('myfile.txt', 'w') # w = write, r = read, a = append # Get some info print('Name: ', myFile.name) print('Is Closed: ', myFile.closed) print('Opening mode: ', myFile.mode) # Write to a file myFile.write('I love Python\n') myFile.write(' and JavaScript') # Append to a file myFile = open('myfile.txt', 'a') # 'a' for append myFile.write(' I also like PHP') myFile.close() # Read from a file myFile = open('myfile.txt', 'r+') text = myFile.read() # Read the content text = myFile.read(10) # Read 10 characters print(text) # Move courser to some place (index) in the file myFile.seek(0) text = myFile.read() # Read a line text = myFile.readline() # Read lines text = myFile.readlines() # list of lines # Close the file myFile.close() # pathlib - filesystem paths - use '/' for both
import os folder = 'test_folder' print(os.path.exists(folder)) # True or False # Create a folder if it doesn't exist if not os.path.exists(folder): os.makedirs(folder) # Create a folder # Loop through the folder for filename in os.listdir(folder): print(filename) # Remove a folder if it exists and not empty if os.path.exists(folder) and not os.listdir(folder): os.rmdir(folder) # Remove a folder
# pip install translate from translate import Translator translator= Translator(to_lang="ja") try: with open('./myfile.txt', 'r') as my_file: text = my_file.read() print(text) translation = translator.translate(text) print(translation) with open('./myfile-ja.txt', 'w', encoding='utf-8') as my_trans_file: my_trans_file.write(translation) except FileNotFoundError as err: print('file not found')
import sys # Grab first argument folder = sys.argv[1] # Grab second argument output_file = sys.argv[2] print(folder, output_file)
import json # Sample JSON userJson = '{ "name":"John", "age":30, "city":"New York"}' # Parse to dict # In JavaScript, we would do: const user = JSON.parse(userJson); user = json.loads(userJson) print(user) print(user['name']) # from dict to JSON car = {'make': 'Ford', 'model': 'Mustang', 'year': 1970} carJson = json.dumps(car) # In JavaScript, we would do: JSON.stringify(car); print(carJson)
r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
Recheck this: + - one or more . - any character except newline \. - literal period ? - zero or one * - zero or more $ - end of string ^ - beginning of string \d - any digit () - group [] - character set {} - repetition | - or \ - escape / - search \n - newline \r - carriage return \t - tab \b - backspace \f - form feed \0 - null
string = '0.0.0.0' OR string = '504.30.0.123' pattern = r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$' if re.match(pattern, string): print('Match found') else: print('No match found')
# Match a string that starts with 'a' and ends with 'z' import re pattern = r'^a[a-z]*z$' if re.match(pattern, 'az'): print('Match found') else: print('No match found')
# Regex for 3 letters followed by 6 digits string = 'ROB000201' pattern = r'^[A-Z]{3}\d{6}$' print(f'Checking string ' + string) if re.match(pattern, string, re.IGNORECASE): print('Match found') else: print('No match found')
string = '2022-11-01 00:00:00' pattern = r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$' print(f'Checking string ' + string) if re.match(pattern, string): print('Match found') else: print('No match found')
string = 'NA' pattern = r'^na$' print(f'Checking string ' + string) if re.match(pattern, string, re.IGNORECASE): print('Match found') else: print('No match found')
import re re.search(PATTERN, STRING, FLAGS)
import re my_string = 'Hello World Hello' my_pattern = re.compile('llo') res = my_pattern.search(my_string) print(res.group()) # returns the matched string (llo)
my_string = 'Hello World Hellooooooooooooo' my_pattern = re.compile('llo') res = my_pattern.findall(my_string) print(res) # returns a list of all matches (['llo', 'llo'])
my_string = 'Hello World Hellooooooooooooo' my_pattern = re.compile('llo') res = my_pattern.fullmatch(my_string) # should to be the exact string that matches the pattern. If not, returns None. print(res) # returns a match object if the pattern is found at the beginning of the string.
my_string = 'Hello World' my_pattern = re.compile('Hello') # returns a match object if the pattern is found at the beginning of the string res = my_pattern.match(my_string) print(res) <re.Match object; span=(0, 5), match='Hello'>
my_string = 'Hello World' my_pattern = re.compile(r"([a-zA-Z]).(\w)") res = my_pattern.match(my_string) print(res.group(1)) # returns the first group (H)
import re my_string = 'Hello World' my_pattern = 'llo' res = re.my_pattern.search(my_string) # returns None if not found, otherwise returns a match object
import re my_string = 'Hello World' my_pattern = 'llo' res = re.search(my_pattern, my_string) # returns a match object print(res.span()) # returns a tuple (start, end) of the match (2,4) print(res.start()) # returns the start index of the match (2) print(res.end()) # returns the end index of the match (4) print(res.group()) # returns the matched string (llo) # group is used for multiple searches
my_string = 'Hello World' my_pattern = 'LLO' res = re.search(my_pattern, my_string) print(res.group()) # Error because res is None
# Match a string re.match(PATTERN, STRING, FLAGS) # Search a string re.search(PATTERN, STRING, FLAGS) # Find all occurrences of a string re.findall(PATTERN, STRING, FLAGS) # Split a string into substrings re.split(PATTERN, STRING, FLAGS) # Find the start and end indexes of a string re.finditer(PATTERN, STRING, FLAGS) # Replace all occurrences of a string re.sub(PATTERN, REPLACEMENT, STRING, FLAGS) # Split a string into substrings re.subn(PATTERN, REPLACEMENT, STRING, FLAGS)
class Utils: @staticmethod def merge_two_lists(list_1, list_2): return list_1 + list_2
class Utils: # Merge two dictionaries. The keys are case sensitive. @staticmethod def merge_two_dictionaries(dict1, dict2): for key in dict2.keys(): if key in dict1: dict1[key] = dict1[key].union(dict2[key]) else: dict1[key] = dict2[key] return dict1
@staticmethod def copy_dict_keys_to_lower_case(dictionary): # Doesn't work when keys are in both upper and lower case !!!!!!!!!!!!!!!! # return {key.lower(): value for key, value in dictionary.items()} new_dict = dict() for key in dictionary: value = dictionary[key] # print(value) # Merge two dictionaries together into a new one when value is a set of unique values new_dict[key.lower()] = set().union( new_dict.get(key.lower(), set()), value) return new_dict
# Merge two dictionaries together when a key is insensitive to case @staticmethod def merge_two_dictionaries_keys_insensitive(dict1, dict2): dict1_lower = Utils.copy_dict_keys_to_lower_case(dict1) dict2_lower = Utils.copy_dict_keys_to_lower_case(dict2) return Utils.merge_two_dictionaries(dict1_lower, dict2_lower)