Python
Python RegEx
-A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. -RegEx can be used to check if a string contains the specified search pattern. import re
Dictionaries
A dictionary is a collection which is ordered*, changeable and do not allow duplicates -print(len(thisdict))
What is a Package?
A package contains all the files you need for a module. Modules are Python code libraries you can include in your project.
Python sets
A set is a collection which is unordered, unchangeable*, and unindexed. -Duplicates Not Allowed -curly bracket thisset = {"apple", "banana", "cherry"}
Break statement
A statement that terminates a loop or switch statement. i = 1 while i < 6: print(i) if i == 3: break i += 1
python tuples
A tuple is a collection which is ordered and unchangeable. rounded brackets thistuple = ("apple", "banana", "cherry") creating tuples with one item thistuple = ("apple",) -must have a comma after length of tuple: print(len(thistuple)) can have different data types: tuple1 = ("abc", 34, True, 40, "male")
Changing list items
Changing value mylist[1]="fruit" changing range of items my list[1:2] =["lol","hehe"] Insert items without replacing existing my list.insert(2,"watermelon")
finding All Indices of a Substring in a String
Using list comprehension indices = [index for index in range(len(a_string)) if a_string.startswith('the', index)] print(indices) # Returns: [0, 31, 45, 76]
shorthand if else
print("A") if a > b else print("B")
python functions
def my_function(): print("Hello from a function") my_function()
comments
#This is a comment.
Python Lambda
-A lambda function is a small anonymous function. -A lambda function can take any number of arguments, but can only have one expression. lambda arguments : expression -x = lambda a : a + 10print(x(5))-Add 10 to argument a, and return the result: -x = lambda a, b : a * bprint(x(5, 6)) -Multiply argument a with argument b and return the result: -The power of lambda is better shown when you use them as an anonymous function inside another function. def myfunc(n): return lambda a : a * n
Naming variables
-A variable name must start with a letter or the underscore character -A variable name cannot start with a number -A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) -Variable names are case-sensitive (age, Age and AGE are three different variables)
Python Modules
-Consider a module to be the same as a code library. -A file containing a set of functions you want to include in your application. To create a module just save the code you want in a file with the file extension .py: mymodule.py in order to use the module, you must import it: import mymodule mymodule.greeting("Jonathan")
add set items
-Once a set is created, you cannot change its items, but you can add new items. thisset.add("orange") -To add items from another set(tuple, list dict) into the current set, use the update() method . thisset.update(tropical)
PIP
-PIP is a package manager for Python packages, or modules if you like. -If you have Python version 3.4 or later, PIP is included by default.
find()
-The find() method finds the first occurrence of the specified value. -The find() method returns -1 if the value is not found. -The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found. (See example below) Example: txt = "Hello, welcome to my world."x = txt.find("welcome")
Access Items in set
-You cannot access items in a set by referring to an index. -But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword. -for x in thisset: print(x) -print("banana" in thisset)
Looping through a list
-for x in bikes:print(x) -for I in range(len(this list)):print(thislist[I]) -while loops -short hand for loop: [print(x) for x in thislist]
Join two lists
-list3=list1+list2 -for loop and append -extend()
Copy Dictionaries
-mydict = thisdict.copy() -mydict = dict(thisdict)
Adding to list
-mylist.append("oranges") -my list.insert(2,"watermelon") -to append elements from another list, tuple,set,dict to the current list use extend() my list.insert(2,"watermelon")
Copy a list
-mylist=thislist.copy -mylist=list(this list)
Join Two Sets
-set3 = set1.union(set2) -set1.update(set2)
Remove Dictionary Items
-thisdict.pop("model") -thisdict.popitem() -del thisdict["model"] -thisdict.clear() -del thisdict. delete entire dict
Removing from list
-thislist.remove("banana") -thislist.pop(1) OR this list.pop() -del thislist[0] -delting the entire list: del thislist -Clear the list(but list remains) thislist.clear()
Remove Set Items
-thisset.remove("banana") -thisset.discard("banana") - will work even if banana is not present -x = thisset.pop() -thisset.clear() -del thisset
Access Dictionary Items
-x = thisdict["model"] -x = thisdict.get("model") -x = thisdict.keys() get a list of keys
Updating Tuples
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. BUT You can convert the tuple into a list, change the list, and convert the list back into a tuple. x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y)
Multiline string
Use three quotes a = """Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididuntut labore et dolore magna aliqua.""" print(a)
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is finished: for x in range(6): print(x) else: print("Finally finished!")
Python Collections (Arrays)
There are four collection data types in the Python programming language: List is a collection which is ordered and changeable. Allows duplicate members. Tuple is a collection which is ordered and unchangeable. Allows duplicate members. Set is a collection which is unordered and unindexed. No duplicate members. Dictionary is a collection which is unordered and changeable. No duplicate members. -in python 3.7, dict are ordered
Built in modules
There are several built-in modules in Python, which you can import whenever you like.
Outputting multiple items with one statement
Use a comma x = 5 y = "John" print(x, y)
inheritance: Creating a child class
Use the pass keyword when you do not want to add any other properties or methods to the class. class Student(Person): pass The child's __init__() function overrides the inheritance of the parent's __init__() function. class Student(Person): def __init__(self, fname, lname): #add properties etc. To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function: class Student(Person): def __init__(self, fname, lname): Person.__init__(self, fname, lname)
Booleans
Valid print(10 > 9) print(10 == 9) print(10 < 9) Valid x = "Hello" y = 15 print(bool(x)) print(bool(y)) #output for both is true Valid -using is instance x = 200 print(isinstance(x, int)) Note empty values (),[],{},''' = false
continue Statement
With the continue statement we can stop the current iteration of the loop, and continue with the next fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x)
Is python case sensitive
Yes. Python is a case sensitive language.
Changing strings
a = "Hello, World!" -print(a.upper()) -print(a.lower()) removing whitespace print(a.strip()) replacing print(a.replace("H", "J")) splitting into substrings print(a.split(",")) # returns ['Hello', ' World!']
Add Dictionary Items
add -thisdict["color"] = "red" -thisdict.update({"color": "red"})
Formating strings
age = 36 txt = "My name is John, and I am {}" print(txt.format(age))
Slicing a string
b = "Hello, World! "print(b[2:5]) # output is llo
Change Dictionary Items
change -thisdict["year"] = 2018 -thisdict.update({"year": 2020})
classes, objects, and __init__()
class MyClass: x = 5 p1 = MyClass() print(p1.x) -Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created: class Person: def __init__(self, name, age): self.name = name self.age = age
add properties: inheritance
class Student(Person): def __init__(self, fname, lname): super().__init__(fname, lname) self.graduationyear = 2019 #adding function def welcome(self): print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
pass Statement
for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. for x in [0, 1, 2]: pass
Loop Through a Dictionary
for x in thisdict: print(x) - prints key words for x in thisdict: print(thisdict[x]) - prints values for x in thisdict.values(): print(x) for x in thisdict.keys(): print(x) for x, y in thisdict.items(): print(x, y) - prints both keys and values
Multiply tuples
fruits = ("apple", "banana", "cherry") mytuple = fruits * 2 print(mytuple) #output ( 'apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
Super() Function
function that will make the child class inherit all the methods and properties from its parent: class Student(Person): def __init__(self, fname, lname): super().__init__(fname, lname
Checking if an item exists in list
if "apple" in my list: print("yes bestie")
if, else, elif
if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b")
Python JSON
import json
Python Math
import math -x = min(5, 10, 25) -y = max(5, 10, 25) -abs() -pow(x, y) -math.sqrt() -math.ceil() -math.floor() -math.pi
random
import random print(random.randrange(1,10)) Choose a random item from a sequence. Here seq can be a list, tuple, string, or any iterable like range. random.choice(list)
Python Membership Operators
in Returns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object X not in y
Creating a list with Len of 10....
inThere=[1]*10)
Indents
indents are part of the syntax
sort list
list.sort() sort descending list.sort(reverse=True) customized sort def myfunc(n): return abs(n - 50) thislist.sort(key = myfunc) case insensitive sorting thislist.sort(key = str.lower) reverse regardless of alphabet: thislist.reverse
Nested Dictionaries
myfamily = { "child1" : { "name" : "Emil", "year" : 2004 }, "child2" : { "name" : "Tobias", "year" : 2007 }, "child3" : { "name" : "Linus", "year" : 2011 }}
Lists - Python arrays
mylist=["apple","banana","cherry"] -lists allow duplicates -a list can be string, int, boolean -length of list print(len(my list))
printing
print("Hello, World!")
Accessing item in list
print(my list[1]) -a negative index means start from the end
Python Try Except
try, except, else,finally try: print(x) except: print("An exception occurred")
Including illegal characters in strings... We are the so-called "Vikings" from the north.
txt = "We are the so-called \"Vikings\" from the north." print(txt) output:We are the so-called "Vikings" from the north.
User Input
username = input("Enter username:") print("Username is: " + username)
Raise an exception
x = -1 if x < 0: raise Exception("Sorry, no numbers below zero")
Python numeric types
x = 1 # int y = 2.8 # float z = 1j # complex
Getting data type
x = 5 print(type(x))
Variables
x = 5 y = "John" a, b, c = "Orange", "Banana", "Cherry"
Casting data types
x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0