Basics Flashcards
1
Q
Python
A
- popular OOP language
- used for :
- web development
- scripting (sorta)
- software development
- mathematical operations (such as data science)
- it can be used on lots of platforms (windows, linux, mac, raspberry, pi, etc)
- its syntax is similar to english
- uses new line to execute codes
- uses indentiation
- interpreted language (no compiler needed)
2
Q
Comments
A
- used to explain code
- use to prevent line of code from executing
- # - to comment single line of code
- ””” used to comment
bolck of codes””” - multiline string
3
Q
Variables
A
- placeholders/containers for storing data values
- no variable decleration in python
- variable is created when a value is assigned to it
- can only be alpha-numeric
- cannot start with number
- is case-sensitive
- cnoot use space or ‘-‘
-
GLOBAL variables
- create outside of functions and can be access anywhere in the file
- to create a global variable inside a function, use keyword global
- example:
- def myfunc():
global x
x = “fantastic”
- def myfunc():
-
LOCAL variables
- created inside a function and can only be accessed inside that function
4
Q
Data Types
A
- Text Type: str
- Numeric Types: int, float, complex
- Sequence Types: list, tuple, range
- Mapping Type: dict
- Set Types: set, frozenset
- Boolean Type: bool
- Binary Types: bytes, bytearray, memoryview
5
Q
Numbers
A
- 3 types of number:
-
int
- whole number without decimals, can be + or -
- convert to interger using int(x)
-
float
- decimal number, can be + or - or scientific (number with ‘e’ for power of 10)
- convert to float using float(x)
-
complex
- number with imaginary part written with a ‘j’
- x = 3+5j
- convert to complex using complex(x)
- cannot convert from complex to other number type
-
int
- random numbers a randomely generated using functions from python random library such as random.randrange
6
Q
Casting
A
- converting one data type to another
- int() - converts variable to integer
- float() - converts variable to float
- str() - converts variable to string
7
Q
String
A
- assign string to a variable using either single quote or double quotes
- strings are arrays which mean they can be filtered via index
- string[index_number]
- uses methods such as .lower(), .strip()
- can be concacted: string1 + string2
- use escape character to include insert illegal characters (")
- or block of string using triple single quotes or triple double quotes
- explame:
- x = ‘string’
- x = “string”
- x = ‘'’block
- of
- string’’’
- x = “"”block
- of
- string”””
8
Q
Boolean
A
- True or False values
- bool(x) to evaluate values
- most values are true except for 0 (or any empty collections such as list dict set etc)
9
Q
Operators
A
- performs operations on variables/values
- Arithmetic operators:
- used on numbers to do mathematical operations:
- Addition x + y
- Subtraction x - y
- * Multiplication x * y
- / Division x / y
- % Modulus x % y
- ** Exponentiation x ** y
- // Floor division x // y
- used on numbers to do mathematical operations:
- Assignment operators:
- used to assign values to variables:
- = x = 5 / x = 5
- += x += 3 / x = x + 3
- -= x -= 3 / x = x - 3
- *= x *= 3 / x = x * 3
- /= x /= 3 / x = x / 3
- %= x %= 3 / x = x % 3
- //= x //= 3 / x = x // 3
- **= x **= 3 / x = x ** 3
- &= x &= 3 / x = x & 3
- |= x |= 3 / x = x | 3
- ^= x ^= 3 / x = x ^ 3
- >>= x >>= 3 / x = x >> 3
- <<= x <<= 3 / x = x << 3
- used to assign values to variables:
- Comparison operators:
- used to compare 2 values/variables:
- == Equal x == y
- != Not equal x != y
- > Greater than x > y
- < Less than x < y
- >= Greater than or equal to x >= y
- <= Less than or equal to x <= y
- used to compare 2 values/variables:
- Logical operators:
- used to combine conditional statements:
- and Returns True if both statements are true - x < 5 and x < 10
- or Returns True if one of the statements is true - x < 5 or x < 4
- not Reverse the result, returns False if the result is true - not(x < 5 and x < 10)
- used to combine conditional statements:
- Identity operators:
- used to compare object values (if they are the same or not):
- is Returns True if both variables are the same object - x is y
- is not Returns True if both variables are not the same object - x is not y
- used to compare object values (if they are the same or not):
- Membership operators:
- used to test if values are present or absent:
- 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
- used to test if values are present or absent:
- Bitwise operators:
- used to compare binary numbers:
- & AND - Sets each bit to 1 if both bits are 1
- | OR - Sets each bit to 1 if one of two bits is 1
- ^ XOR - Sets each bit to 1 if only one of two bits is 1
- ~ NOT - Inverts all the bits
- << Zero fill left shift - Shift left by pushing zeros in from the right and let the leftmost bits fall off
- >> Signed right shift - Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
- used to compare binary numbers:
10
Q
Lists
A
collection that is:
- mutable (can be changed/edited)
- list_name.append() - to add item
- list_name[position_number] - to edit
- list_name.insert(indiex, object) - add object at specified position
- list_name.remove(item_to_remove)
- del list_name[index]
- list_name.clear() - remove all items
- list_name.pop() - move last or psecified index
- allows duplicate
- written with squarish brackets []
- indexed
- to make a copy of list, use .copy() metod or list will onl be referenced
11
Q
Tuples
A
collection that is:
- unmutable (cannot be changed/edited)
- written with round brackets ()
- allows duplicate
- indexed
- to create tuple with 1 item: (item, )
- tuple() - constructor to make a tuple
- tuple methods:
- count()
- index()
12
Q
Sets
A
collection that is:
- written with curly brackets
- unordered and unindexed
- no duplicates allowed
- cannot change/edit items but can add new items
- .add() - add 1 item
- .update() - add more than 1 items
- can remove items:
- .remove() - will raise error is item doesn’t exist
- .discard() - won’t error out if item doesn’t exist
- .pop() - to remove last item
- combine 2 sets into a 3rd one using set3 = set1.union(set2) or .update()
- this will remove duplicates
13
Q
Dictionaries
A
collection that is:
- key/value pair
- mutable
- indexed and unordered
- written with curly brackets
- access values by referring to key name or call .get(key_name) method
- loop through a dict:
- for x in thisdict: - loop though keys in dict
- for x in thisdict.values(): - loop through values
- for x, y in thisdict.items(): - loop through both keys and values
- add/edit item to dict: dict_name[“key”] = “value”
- remove item: dict_name.pop(‘key’) or del dic_name[‘key’]
- duplicate dict using .copy() method
14
Q
If Else
A
If:
- if conditions are met then execute the following codes
- uses python operators (logical, comparison, etc)
ElIf
- if previous if or elif statement is not met, try this 1
Else
- if none of the previous conditions are met then execute this
example:
if a == b:
print(‘a equal b’)
elif a < b:
print(‘a less than b’)
else:
print(‘a greater than b’)
- conditional expression:
- print(“A”) if a > b else print(“B”)
15
Q
While Loops
A
- execute code(s) until looping codition is no longer true
- use break to stop loop early
- use continue to stop/skip current iteration and move on to next one
- use else to execute code when while loop is done, treats the while loop like an if else statement
- use pass to replace code(s) in loop block
- example:
while a < b:
# code here
else:
# code here
16
Q
For Loops
A
- iterator that goes through a sequence such as a list, dict, set, tuples, string
- execute code(s)/statement(s) for each item in the sequence
- use break to stop loop early
- use continue to stop/skip current iteration and move on to next one
- use pass to replace code(s) in loop block
- use else to execute code when while loop is done, treats the while loop like an if else statement
- example:
for a in sequence/range():
# code here
else:
# code here
17
Q
Functions
A
- block of code that runs only when called
- can take data as parameters
- returns data as result
- use keyword def to create a function
- use function name follwed by parenthesis to call/execute a function
- pass arguments to function speperated by commas
- exact number of arguments/parameters must be used/pass to function
- if exact number of arguments is not knowm, use *argument_name to refer to a tuple of arguments (e.i. python documentation uses *args)
- use **argument_name to pass in a dict of key/value as arguments of unknown sze and items (e.i. python documentation uses **kwargs)
- default parameters are used when function is called without passing value for a parameter
- any datatype can be passed as parameter or result
- use pass for empty functions
- functions can be recursive - call on itself
18
Q
Lambda
A
- small anonymous function taking argument(s) but only have 1 expession
- syntax: lambda argument(s): expression
- use lambda when an anonymous function is required
- example:
x = lambda a, b, c : a + b + c - anonymous functions are called lambda functions and defined with the keyword lambda
- lambda allows you to create “inline” functions which is useful for functional programming.Works well with functions such as Map, Filter and Reduce
- example:
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
new_list = list(map(lambda x: x * 2 , my_list))
19
Q
Arrays
A
- Python has no arrays, uses Lists instead
- see List
- to support arrays python uses the NumPy library
- arrays are used to store multiple values in a single variable
20
Q
Classes/Objects
A
- Everything in python is an object
- class is an object constructor (blueprint to create an object)
- create a class using keyword class (class myClass(): pass)
- once created , can use it to create a class object (c1 = myClass())
- __init__() - function that is called when a class is initialized. it assignes values to proerties and execute other operatioins as defined. It is called automatically when a class is being used to create new class object.
-
self is used to access variables belonging to the class wen defining the class.
- it refers to the current instance of the class
- doesn’t have to be called self, can be called anything but has to be 1st parameter in any function
- delete a class object using del keyword
21
Q
Inheritance
A
- allows us to define a class that inherits all the methods and properties from another class.
- Parent class is the class being inherited from, also called base class.
-
Child class is the class that inherits from another class, also called derived class.
- Use the pass keyword when you do not want to add any other properties or methods to the class.
- When you add the __init__() function, the child class will no longer inherit the parent’s __init__() function and overrides it
- use the super() function to automatically inherit the methods and properties from parent:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
def welcome(self): print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear) * adding a method in the child class with the same name as a function in the parent class will override the parent's function
22
Q
Iterators
A
- object you can iterate upon (list, tuples, sets, dicts, etc)
- iter() method is used to iterate an object
- use next() function to get next item in the sequence
- can use for loop to iterate through a sequence
- use StopIteration to stop iterating
23
Q
Scope
A
- local scope - can only be used iinside the function it was created
- global scope - can be used anywhere
- use global keyword to create a global variable in a local environment/function
24
Q
Modules
A
- a module is a .py file containing set of functions
- add module using import (import module_name)
- use a function from a module: module_name.function_name
- modules can contain variables
- use as keyword to rename a module
- dir() - list all functions and variables names in a module
- use from module_name import module_function/variable - to import part of a module
25
Q
Dates
A
- import datatime
- datetime module has many functions and methods for date/time manipulation
- not a datatype
- use datatime class to create a datatime object (it takes year month and day parameters)
- .strftime() - to specify datetime format
- .year - to extract year part of the date
26
Q
JSON
A
- javascript JSON object
- import json
- written in form of a dictionary { key: value, …}
- json.dumps() - convert object/datatypes to json - y = json.dumps(x)
- parse json string using json.loads()
27
Q
RegEx
A
- Regular Expression
- import re
- use to check if string conatins specific search patterns
- build-in functions:
- findall - Returns a list containing all matches
- search - Returns a Match object if there is a match anywhere in the string
- split - Returns a list where the string has been split at each match
- sub - Replaces one or many matches with a string
28
Q
PIP
A
- package manager for Python packages
- allows you to install python libraries
- pip install package_name - to install new package
- pip uninstall package_name - to uninstall existing package
- pip freeze - list installed packages and their versions
29
Q
Try… Except
A
- try-except-finally block is used to make make sure your next block of codes doesn’t break the program
- try - test.try to execute your block of code
- except - catches the error is any
-
finally - code block to be executed whether ir errors out or not
- example:
try:
f = open(“demofile.txt”)
f.write(“Lorum Ipsum”)
except:
print(“Something went wrong when writing to the file”)
finally:
f.close()
- example:
-
raise keyword is used to raise exception
- example:
if x < 0:
raise Exception(“Sorry, no numbers below zero”)
- example:
30
Q
User Input
A
- python allows user input
- python 3.6 uses input()
- python 2.7 uses raw_input()
- python stops executing until user gives input
- example:
username = input(“Enter username:”)
print(“Username is: “ + username)
31
Q
String Formatting
A
- .format() - format selected part of a string
- {} as placeholders in the string
- can add parameters inside the brackets for further modification to the value such as floating decimal point, index if multiple entries
- example:
myorder = “I want {0} pieces of item number {1} for {2:.2f} dollars.”
print(myorder.format(quantity, itemno, price))
32
Q
Files
A
- can create, read, update and delete files
-
open() - to hadle files, takes 2 parameters: filename and mode:
- “r” - Read - Default value. Opens a file for reading, error if the file does not exist
- “a” - Append - Opens a file for appending, creates the file if it does not exist
- f = open(“demofile2.txt”, “a”)
f. write(“Now the file has more content!”)
f. close() - a method will write new lines at the end of file
- f = open(“demofile2.txt”, “a”)
- “w” - Write - Opens a file for writing, creates the file if it does not exist
- f = open(“demofile3.txt”, “w”)
f. write(“Woops! I have deleted the content!”)
f. close() - w method will overwrite the entire file
- f = open(“demofile3.txt”, “w”)
- “x” - Create - Creates the specified file, returns an error if the file exists
- f = open(“myfile.txt”, “x”)
f. close()
- f = open(“myfile.txt”, “x”)
- additional modes:
- “t” - Text - Default value. Text mode
- “b” - Binary - Binary mode (e.g. images)
- Make sure the file exists, or else you will get an error.
- example:
f = open(“demofile.txt”, “rt“) - f.read()
- returns the whole text, but you can also specify how many characters you want to return
- f.readline() - returns 1 line
- use for to loop a file reading each line:
f = open(“demofile.txt”, “r”)
for x in f:
print(x) - f.close() - to close file when done, should always close files (sometimes changes made won’t show until file is close due to buffering, good for finally block)
- to delete a file, need to import os and use os.remove()
- example:
import os
if os.path.exists(“demofile.txt”):
os.remove(“demofile.txt”)
else:
print(“The file does not exist”)
- example:
33
Q
NumPy
A
- python library to work with arrays
- stands for Numerical Python
- arrays in numpy are called ndarray
- it is stored in 1 continuous place in memory (so it is faster than list)
- written in c/c++
- code base is in github
- import numpy as np
- np.array([1, 2, 3, 4, 5]) - defined new array
- dimensions:
- 0-D - element in an array at lowest level
- 1-D - list/array of elements
- 2-D - array of array of elements
- use array_name.ndim to check dimension of array or to create an array of higher dimension (np.array([1, 2, 3, 4], ndmin=5))
- can access elements in array via index
- use comma seperated values for higher index:
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
- use comma seperated values for higher index:
- can use index slicing array_name[start:end:step]
- arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2]) - arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])
- arr = np.array([1, 2, 3, 4, 5, 6, 7])
-
datatypes
- use array_name.dtype - returns the data type
- can create arrays with specific data types:
- arr = np.array([1, 2, 3, 4], dtype=’S’)
- use array_name.astype() - to cast an array datatype to something else:
- arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype(‘i’)
or newarr = arr.astype(int)
- arr = np.array([1.1, 2.1, 3.1])
-
copy() vs view()
- array_name.copy() - change made to copy won’t affect original
- array_name.view() - change made to view will affect original
- check if an array is a view by using the array_name.base method
- array_name.shape - returns number of elements per dimension in an array
- array_name.reshape() - reshape the array into different dimension(s)
- number of elements sould match the dimension:
- arr.reshape(2, 3, 2) - needs to have 2*3*2 = 12 elements exactly
- use -1 for unknown dimension, can be used no more than once
- arr.reshape(2, 2, -1)
- reshape(-1) - flattens and array into a 1D array or .flatten()
- number of elements sould match the dimension:
- can use for to loop through an array
- for x in np.nditer(arr): - numpy build-in iter()
- for x in arr:
- for idx, x in np.ndenumerate(arr): - numpy build-in enumerate() which returns both index and value
- can use np.concatenate(array1, array2) - to join 2 arrays
- can also use np.stack() - which is done along the axis
- np.hstack() - along the horizontal axis (join by rows)
- np.vstack() - along the vertical axis (join by columns)
- np.array_split() - split an array into a list of sub_arrays
- arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
result - [array([1, 2]), array([3, 4]), array([5, 6])] - If the array has less elements than required, it will adjust from the end accordingly.
- alos as .hsplit .vsplit
- arr = np.array([1, 2, 3, 4, 5, 6])
- use np.where() to return index(es) of a given search
- arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4)
result - (array([3, 5, 6]),)
- use np.sor() to sort an array
- it returns a copy of the array, original is unchanged
- arr = np.array([‘banana’, ‘cherry’, ‘apple’])
np.sort(arr)
result - [‘apple’ ‘banana’ ‘cherry’]
- can filter through an array using boolean indexing
- usu condition to generate a list of bool based of array, returning true for element in array matching specified condition:
- arr = np.array([1, 2, 3, 4, 5, 6, 7])
filter_arr = arr % 2 == 0 <= filter condition
newarr = arr[filter_arr] - results:
filter_arr = [False True False True False True False]
newarr = [2 4 6]
- arr = np.array([1, 2, 3, 4, 5, 6, 7])
- usu condition to generate a list of bool based of array, returning true for element in array matching specified condition:
- Numpy has its own version of random module which generates random numbers in arrays of given shape
- NumPy also has ufunc“universal functions” which let you use mathematical operations on elements of array like adding 2 arrays by elements
34
Q
NumPy
Numpy_sub
A
testing