OrgPad logo

Python - CS50 and the basics

Created by Tâm Lại Thị Thúy

Python - CS50 and the basics

filter

filter() is a function to return a subset of a sequence under certain condition.

filter(function, iterable)

* Where function can be pre-defined using def or under lambda 

generators and iterators

Generators is a way of generate a small bit of information at a time to preserve the computation power instead of returning massive amount of information at the same time (iterators)

yield is used insteal of return

attributes

global variables

global variable is the way to use the globally declared variable inside of each functions

Example:

balance = 0
def deposit(n):
global balance
balance -=n

map

map() is a function allows you to implement some kind of function mapped to a sequence of value.

Map document

Example:

...

uppercased.append(word.upper())

map can be used to map the upper function to each of the word from the words[] list as follow:

uppercased = map(str.upper, words)

unpacking

unpacking is a way of unpack values in a list or a dictionary without having to access to the index (of the list) or the key (of the dict)

methods

set / enumerate

1.1 set() is a class that help create a list with no duplicates value

set is actually a class in python that can be accessed via set()

Example:

house = set()

house.add(student["house"])

1.2 enumerate(): is a way of getting the index value of a list

ex: range(len(students))  can be written as enumerate(students)

class

objects

inheritance

*args and **kwargs

*args is positional argument. In a function, *args indicate that it can take any number of arguments and parse all of them to the function being used.

**kwargs is named argument or key word argument. This quite similar to *args but **kwargs require any arguments that are keyworded (i.e. a dict)

reference

argparse

argparse is a library which comes with different functions:

this help to parsing all command-line arguments with specified condition. Instead of using if condition and manually iterate user args

W9_Python: Et Cetera

This lecture covers many kinds of topic which are practical but have not yet been covered in previous ones.

W8_object-oriented programming

Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications

docstrings

docstrings is a way of commenting your function's purpose very clearly so that it can be extracted into another file and used as documentation of your code.

Tools such as Sphinx can be use for those extraction

list

list is a set of values that are presented in [] and seperated by comma ","

example:

students = ["Hermione", "Harry", "Ron"]

The  list() constructor can also be used to convert any type of iteratable data like string, tuples, set, dictionary into a list

list/dictionary comprehension

list/ dict comprehension is a way of creating a list/dict on the fly without having to seperately writing a loop and append value into a list or a dict.

Example:

name = [student["name"] for student in students 
if student["house"] == "Gryffindor"]
house = {student: "Gryffindor" for student in students}

common regex

image

image

tuple

range

dictionary

dictionary is a data type that comes with keys and their values

example:

students ={
"Harry" : "Gryffindor",
"Draco" : "Slytherin",
}

match objects

match = re.search(pattern, string)
if match:
process(match)

re. match() searches for matches from the beginning of a string while re.search() searches for matches anywhere in the string.

Match can be utilized to return certain specified/named groups in strings. A group can be named using

(?P<name>group_of_patterns)

bytes

W7_regex

Regular expressions or “regexes” will enable us to examine patterns within our code

Regex can be implemented via  re library

📃Sequence

set

set is a collection with no duplicates element

🗂️Mapping

boolean

Set

bytearray

0️⃣1️⃣ Binary

open

open function allows you to open a file to read or write to it

file = open("names.txt", "a")

Mode of open:

image

string

✅❌ Boolean

memoryview

with open

with open allows you to open file to read and write and handle the closing file without losing your data.

💬Text

None

W6_file I/O

csv library

csv is a built-in Python library where it helps to handle the CSV file with functions like:

Numpy

Quick summary on Numpy: https://www.notion.so/Numpy-2fbe613040bc43e890f83f31cf345869?pvs=4

Pandas

Pandas quick summary: https://www.notion.so/Pandas-5e6324bddb17481a8f42dd5890da6145?pvs=4

Data analysis with Pandas: https://wesmckinney.com/book/

int

assert

Assert statements are a convenient way to insert debugging assertions into a program

https://docs.python.org/3/reference/simple_stmts.html#assert

third-party library

float

🔢Numeric

data types

reference Thu Vu Analytics

Matplotlib

Quick summary on Matplotlib:

https://www.notion.so/Matplotlib-aa388aaa864e4c91a94c3df8c7484750?pvs=4

f string

the f comes with some special syntax:

f"{n:02}" -> adding 0 before 1 digit number

f"{z:,}" → using comma (,) as thousand seperator

f"{z:.2f}" → rounding the number by 2 decimal points

variables

variables are way to contain value of the program.

ex: name = input("Your name: ") is a variable contains the user's name input

fuction

functions are actions that the program performs

Ex: print("Hello, world") → print is a function which prints out the text "Hello, world"

functions take in their parameters to define correct actions

Python CS50

Python tutorials:

https://docs.python.org/3/tutorial/

W5_unit test

Unit test means testing your program by each unit.

It is also suggested that your program must be written into units that are testable.

pytest

pytest is a third-party library that allows you to unit test your program

W4_libraries

Libraries are bits of code written by you or others that can be shared and reused.

Python module is a file containing Python definitions and statements defining functions, classes, and variables.

A Python library is a collection of related modules

complex

W2-loops

def

def is a way to create your own function to perform customized action(s)

the def function need to be created and called on the code so that it can performed

return is the key word to get back values from def

W3_exceptions handling

Errors and exceptions happens when there are something wrong with the code written.

popular libraries

packages

Python is somewhat a folder that contains related Python files (modules) that work together to provide certain functionality

PyPI is a repository or directory of all available third-party packages currently available.

Some useful packages:

image

code style

PEP 8 (Python Enhancement Proposal) - writing code with readability and consistency

pylint

pycodestyle

black

W1_Basic concepts

while loops

the while loops are used to repeat certain actions

example:

i = 1
while i ≤ 3:
print("hello")
i +=1

for loops

for loops are used for looping through a list or a range with each element of that list/range get assigned to the variable

ex:

for i in [0,1,2]

or

for i in range(3)

sys

sys is a module allowing to take arguments at the command line.

argv is a function within the sys module that allows us to learn about what the user typed in at the command line.

More about sys

managing packages

conditionals (if)

if statement use boolean or bool values (True or False) to decide whether or not to execute

control flow

elif, else enable logic flow to check certain conditions in code before excecute and return expected values

or, and are also used alongside to group some conditions

try/ except

try and except are ways of testing out user input before something goes wrong.

except comes with specific type of errors that need to handled.

else can also be used to improve the flow of code.

raise exceptions

raise allows the programmer to force a specified exception to occur

loop control statement

statistics

This module provides functions for calculating mathematical statistics of numeric (Real-valued) data

match

match statements can be used to conditionally run code match certain values

ex:

match variable:

case "var1":

print("value1")

case "var2":

print("value2")

operators

Source from Thu Vu Analytics

random

import random

https://docs.python.org/3/library/random.html

import package/module

If package is a part of standard library, it can be imported via:

# import whole package

import random

# import specific functions/ modules

from random import choice

If package is not standard, it need to be installed first via package manager like pip or conda

i.e. pip install panda

continue

break

pass

Arithmetic

Arithmetic operators are used with numeric values to perform common mathematical operations:

image

Membership

Membership operators are used to test if a sequence is presented in an object:

image

Bitwise

Bitwise operator in Python that acts on bits and performs bit-by-bit operations

image

Comparison

Comparison operators are used to compare 2 values:

image

Identity

Indentity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

image

Assignment

Assignment operators are operators used to assign values to variables

image

Logical

Logical operators are used to combine conditional statements

image