Concepts for Python
Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility. Created by Guido van Rossum and first released in 1991, Python emphasizes code readability and productivity, with a clear and concise syntax that favors readability and reduces the cost of program maintenance. Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming styles. Key features include dynamic typing, automatic memory management (garbage collection), extensive standard libraries, and a vibrant ecosystem of third-party packages through the Python Package Index (PyPI). Python is widely used in various domains such as web development, data science, artificial intelligence, scientific computing, and automation, making it one of the most popular and widely adopted programming languages today.
Print Text
print('Hello World!') print("Hello World!")
Comments
# one line comment """ multi line comment """
Variables
carCount = 2 name = 'Joe' isPurple = true
Data Types
carCount = 2 age = 15 seaLevel = -10000 usBudget = 11000000000 lightSpeed = 11799312874 myGPA = 3.45 piValue = 3.14159265 lastLetter = 'Z' isMale = true myName = 'Joe'
Math Op
carCount = 6; truckCount = 3; total = carCount + truckCount; print(total); subtract = carCount - truckCount; print(subtract); multiple = carCount * truckCount; print(multiple); divisible = carCount / truckCount; print(divisible); # performs division and gets remainder which is 0 modulo = carCount % truckCount; print(modulo);
Math Functions
import math from random import randint power = math.pow(3, 6); print(power); root = math.sqrt(16); print(root); floorVal = math.floor(3.14); print(floorVal); ceilVal = math.ceil(4.3); print(ceilVal); roundVal = round(3.4); print(roundVal); # random number from 0 to 100 ranNum = randint(0, 100) print(ranNum)
If/Else
carCount = 6 if carCount > 3: print("More than three cars") elif: print("Equal to three cars") else: print("Less than or equal to three cars")
Ternary
carCount = 3 result = "Yes" if carCount > 2 else "No" print(result)
Switch
carCount = 3 match carCount: case 1: print("One car") case 2: print("Two cars") case 3: print("Three cars") case _: print("More than three")
Functions
def handleCars(cars, wheels): total = cars * wheels return total result = handleCars(3, 4) print(result)
Interpolation
name = 'Joe' car = 'Mazda' result = f"{name} drives a {car}" print(result)
Type Casting
def squareA(length): result = length ** 2 return str(result) squareL = "4" convertedVal = int(squareL) area = squareA(convertedVal) print(area)
Date and Time
import datetime # current date and time today = datetime.datetime.now() print(today) #setup date time instance strDate = datetime.datetime(2023, 11, 20) # Full numeric month month = strDate.strftime("%m") # get word version of month strMonth = strDate.strftime("%B") # grabs day from date obj day = strDate.strftime("%d") # grabs year form date obj year = strDate.strftime("%Y") # concatenate to produce a full date fullDate = f"{month}/{day}/{year}" strFull = f"{strMonth} {day}, {year}" print(year) print(fullDate) print(strFull)
Classes
class Cars: def __init__ (self): self.carList = [] def addCar(self, name): self.carList.append(name) def removeFirst(self): self.carList.pop(0) def getFirstVal(self): if len(self.carList) > 0: return self.carList[0] return ''; newList = Cars() newList.addCar('Honda') newList.addCar('Mazda') newList.addCar('Toyota') newList.removeFirst() firstCar = newList.getFirstVal() print(firstCar)
Inheritance
class User: def __init__ (self, username, password): self.username = username self.password = password class Admin(User): def __init__ (self, id, password, username): super().__init__(username, password) self.id = id def getUsername(self): return f"{self.username}" def getAdminID(self): return self.id newAdmin = Admin('alpha 0', 'pw1', '1FE') print(newAdmin.getUsername()) print(newAdmin.getAdminID())
Method Overload
// No Native Support or Implementation
Abstract Class
from abc import ABC, abstractmethod class Animation (ABC): @abstractmethod def walk(self): pass @abstractmethod def run(self): pass @abstractmethod def idle(self): pass class Human(Animation): def walk(self): print('Human walks') def run(self): print('Human runs') def idle(self): print('Human idles') class Zombie(Animation): def walk(self): print('Zombie walks') def run(self): print('Zombie runs') def idle(self): print('Zombie idles') player = Human() player.walk() zombie = Zombie() zombie.run()
Static Class
class Helper: @staticmethod def circleA(radius): return (3.14 * (radius ** 2)) @staticmethod def squareA(length): return length ** 2 circle = Helper.circleA(3) print(circle) square = Helper.squareA(4) print(square)
Arrays/Lists
names = ["Joe", "Alex", "Bob"] names[1] = "Tom" name = names[1] numItems = len(names) print(name) print(numItems)
Array Methods
cars = ['Honda', 'Mazda', 'Toyota'] // number of elements initLength = len(cars) print(initLength) // removes element at index one cars.pop(1) print(cars[1]) // adds element at end cars.append('Tesla') print(cars[2]) // removes element with Tesla cars.remove('Tesla') print(len(cars)) // reverses current order of elements cars.reverse() print(cars)
Concatenation
import numpy as n carsListKr = ['Kia', 'Hyundai', 'Daewoo'] carsListJp = ['Honda', 'Mazda', 'Toyota'] combined = n.concatenate([carsListKr, carsListJp]) print(combined[1]) print(combined[4])
Sort Method
ages = [5, 3, 1, 6, 7, 4, 19] ages.sort() print(ages)
Objects
class User: def __init__( self, first, last, age, retired, carBrands, ): self.first = first self.last = last self.age = age self.retired = retired self.carBrands = carBrands def fullName(self): return f"{self.first} {self.last}" carBrands = ["Mazda", "Toyota"]; user = User( "Joe", "Doe", 23, False, carBrands ) print(user.first) print(user.carBrands[1]) print(user.fullName())
Maps (Key/Value)
carMap = {} carMap["Joe"] = "Toyota" carMap["Bob"] = "Mazda" carMap["Tom"] = "Ford" print(carMap.get("Tom")) carMap.pop("Tom") print(carMap.keys())
Sets
cars = set(); cars.add('Mazda') cars.add('Toyota') cars.add('Honda') print('Honda' in cars) cars.remove('Honda') print('Honda' in cars)
Stack
cars = [] cars.append('Mazda') cars.append('Toyota') cars.append('Honda') print(cars[len(cars) - 1]) cars.pop(len(cars) - 1); print(cars[len(cars) - 1])
Queues
cars = [] cars.append('Mazda') cars.append('Toyota') cars.append('Honda') print(cars[0]) cars.pop(0) print(cars[0])
Linked List
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def add(self, value): newNode = Node(value) if self.head == None: self.head = newNode else: current = self.head while(current.next): current = current.next current.next = newNode def returnHead(self): return self.head.value def traverse(self): current = self.head while(current): print(current.value) current = current.next carList = LinkedList() carList.add('Mazda') carList.add('Toyota') carList.add('Honda') print(carList.returnHead()) carList.traverse()
Graphs
class Graph: def __init__(self): self.graphMap = {} def addNode(self, val): self.graphMap[val] = [] def addVertices(self, node1, node2): if node1 not in self.graphMap: self.graphMap[node1] = [] if node2 not in self.graphMap: self.graphMap[node2] = [] self.graphMap[node1].append(node2) self.graphMap[node2].append(node1) def breadthTraverse(self, start): queue = [start] visited = {} visited[start] = True while(len(queue) > 0): val = queue[0] print(val) queue.pop(0) tempArr = self.graphMap[val] for i in tempArr: if i not in visited: queue.append(i) visited[i] = True def depthTraverse(self, start): stack = [start] visited = {} visited[start] = True while(len(stack) > 0): val = stack[len(stack) - 1] print(val) stack.pop(len(stack) - 1) tempArr = self.graphMap[val] for i in tempArr: if i not in visited: stack.append(i) visited[i] = True newGraph = Graph() newGraph.addNode('a'); newGraph.addVertices('a', 'b'); newGraph.addVertices('a', 'c'); newGraph.addVertices('b', 'd'); newGraph.addVertices('b', 'e'); newGraph.addVertices('d', 'f'); newGraph.addVertices('d', 'g'); newGraph.addVertices('d', 'h'); newGraph.addVertices('e', 'i'); newGraph.addVertices('e', 'j'); newGraph.breadthTraverse("a"); newGraph.depthTraverse("a");
For Loops
names = ['Joe', 'Alex', 'Bob'] for name in names: print(name)
While Loops
carList = ['Mazda', 'Toyota', 'Honda'] while(len(carList) > 0): print(carList[0]) carList.pop(0) print(len(carList))
Loop Breaks
cars = ['Toyota', 'Honda', 'Mazda'] for index, car in enumerate(cars): if car == 'Honda': print(f"Found at index {index}") break print(f"Visited index {index}")
Recursion
def getSum(arr): if len(arr) == 0: return 0 firstVal = arr[0] arr.pop(0) return firstVal + getSum(arr) testArr = [1, 2, 4, 5] sum = getSum(testArr) print(sum)
Regex Words
import re pattern = '\w+' phrase = 'I am legend' result = re.search(pattern, phrase) print(result[0])
Regex Numbers
import re pattern = '\d+' phrase = 'I am 23' result = re.search(pattern, phrase) print(result[0])
Regex Test
import re name = 'Bob Lee' pattern = 'Lee' result = bool(re.search(pattern, name)) print(result)
Regex Characters
import re pattern = '#+\w?' phrase = '##I am legend##' result = re.search(pattern, phrase) print(result[0])