Python / Django Flashcards
Python console I/O
Input:
def input(“String appears to prompt user to input”)
This function returns string from what user type
Output:
def print(“What to show in console”)
Python type casting
Cast to int: int( / some string for float etc / )
Python conditional statement
if boolean_expression: some expression elif another_boolean_expression: some expression else: some expression
Python sequence type
Python provides different array-like data structure for handling multiple related element with different feature: string, list, set, tuple, dict (key : value)
Mutable / Immutable sequence: whether the sequence or the sequence’s element can be modified, (ex: add element to sequence, change value in particular index)
Ordered / Unordered: whether swaping two position inside a sequence create a new sequence or it is still considered the same one
Some sequences have supported function, syntax:
vector.sort()
all_sequence.len()
Python lists
Ordered: Yes Mutable: Yes Syntax: names = ["Harry", "Ron", "Hermione"] Lists behave similar to C++ vector, can insert / append / remove elements, swap elements create a new python lists, elements can be modified. Can contains multiple similar elements. Supported function: append() insert() operator[] sort()
Python tuples
Ordered: Yes
Mutable: No
Syntax: point = (1.3, 4.2, 0.1)
Tuples behave like constant list, order matters and can contain multiple similar element, but when created cannot be modified anymore.
Python set
Ordered: No Mutable: Yes Set only store each value once, if add multiple simlar value, set only display that value once and ignore the others Syntax: sign = set() / create empty set / Support function: set.add(5) set.add(4) set.add(3) print(set) --- > {5, 4, 3} set.remove(4)
Python dict
Ordered: No
Mutable: Yes
Dictionary is Set of < Key : Value > pairs, each key in dictionary has corresponding value.
Syntax:
info = {
“name” : “Harry”,
“age” : 19,
“school” : “Hogwarts” / last one doesn’t need semi colon /
}
Support function:
Adding Key-Value: info[“degree”] = “bachelor”
Access value through key from dictionary:
print(info[“name”]) — > Harry
Python loops
Element wise loop
names = [“Harry”, “Ron”, “Hermione”]
for name in names:
print(name)
for char in “Harry”:
print(char)
Range loop
for i in range(6): / Loop from 0 to 6 - 1 /
print(i)
Python function and modules
Function defined in function.py def func(parameter): some statement return value In main.py to use function func, have 2 option name = "Harry" 1) from function import func print(func(name)) 2) import function print(function.func(name))
Python Object-Oriented Programming
Create User-defined class having attribute and behaviour method. Ex: class Flight(): / self is reference to that particular instance, not including self means static function (represent for whole class) cannot access to that instance attribute / def \_\_init\_\_(self, id, from, to, capacity): self.id = id self.from = from self.to = to self.capacity = 100 self.passengers = []
def add_passenger(self, passenger) if not seat_available(): return False else: self.passengers.append(passenger) return True
def seat_available(self): return self.capacity - len(self.passengers)
# Create a new flight with o=up to 3 passengers flight = Flight(3)
# Create a list of people people = ["Harry", "Ron", "Hermione", "Ginny"]
Attempt to add each person in the list to a flight
for person in people:
if flight.add_passenger(person):
print(f”Added {person} to flight successfully”)
else:
print(f”No available seats for {person}”)
""" Output: Added Harry to flight successfully Added Ron to flight successfully Added Hermione to flight successfully No available seats for Ginny """
Python Functional Programming
Decorator: function receive a function parameter, return a wrapper function, adding some preprocess and postprocess code for original function. Example: def fun(name): return f"Hello, {name}!"
def checking(name): def wrapper(name): if is_alpha(name): print(fun(name)) else: print("Invalid name, no hello") return wrapper
name = input(“Name: “)
/ decorator means running the modified version return from “checking” function /
@checking
fun(name)
Lambda function: short notation for input variable and return some element or modification of input. Syntax: square = lambda x : x * x Example: Nesting dicts inside a list people = [ {name: "Harry", house: "Gryffindor"}, {name: "Cho", house: "Ravenclaw"}, {name: "Draco", house: "Slytherin"}, ] Cannot use people.sort() since " operator < " not defined between dict and dict. Have to pass in function as variable for sort() to figure out the order.
name.sort(key = lambda person : person[“name”])
sort() will traverse whole list with the function from key parameter to get keys and sorting on those keys
Django
Python framework providing modules and feature helping ease the process of writing fully-fledge dynamics web applications by handling all the protocol and building blocks that every type of web applications does so that the programmers can focus on the intersting logic of building their web apps – > improve productivity
HTTP protocol
The protocol that defined has standard method for communication between clients and server by sending message for verification and routing then receive the demanded package from the server. An structure of the typical HTTP protocol signal:
From client: / GET is one type of HTTP message beside POST 1.1 is the HTTP version, host will be the URL client trying to access to/ GET / HTTP / 1.1 Host: www.example.com Server respond: HTTP / 1.1 200 OK Content-type: text / html
/ The 200 code means the GET process works well, no error happening, and the server respond with the right package in the type of html pages that the client browser will render to display /
Some prevalent HTTP protocol code
200: OK
301: Move page permantly
403: Access denied
404: Not found
500: Internet Server Error, the web applications having bugs so the programmer have to dive in and fix it
Starting Django project
Django project must be created and deploy inside an Python Virtual Machines for servering with localhost:
mkvirtual VM-names
Command for starting to create Django apps:
“django-admin startproject PROJECT_NAME”