|||

Notes on Python

This post is a quick summary of the Python language. This is for version 3 and above.

python logo

Basics

  • Python standard library docs can be found at: docs.python.org/3/library
  • Python can be written in a script file with the extension .py or in the interactive shell.
  • To run code just run python my-script.py in the terminal.
  • use print function to print to the console.
  • print function can also take args. example print("You owe", total). This results in You owe 100. It adds space automatically
  • To change the separator use sep arg. example print("You owe $", total, sep=''). This results in You owe $100
  • by default print statements end with a newline to change that use end arg. example print("You owe $", total, end=''). This results in You owe $100 without a newline.
  • use input to get user input. example name = input("Enter your name: \n")
  • an f string in python is like a template string in JavaScript. example print(f"Hello {name}")
  • to separate float with thousands separator use :,.2f in the f string. example print(f"Hello {name}, your total is ${total:,.2f}"). This will make it look like a currency.

Data types

  • Python can infer data type from the value assigned. For example, x = 1 will make x an integer.
  • Here is an example of float. x = 10.50
  • To convert float to an int. use the int function. x = int(10.50)
  • Likewise use float function to convert to float. example x = float(10)
  • Strings can be represented with single or double quotes. example x = "Hello World"
  • To check if a string is a substring of another, use the in keyword. for example: if "e" in "Hello": would evaluate to true
  • example of apostrophe in a string x = "Don't". Using single quote with apostrophe will cause an error.
  • Use + to concatenate strings. example x = "Hello" + "World". Use space between as necessary.
  • Use * to repeat a string. example x = "Hello" * 3
  • Use // to perform a whole integer division. example x = 10 // 3 would yield 3. Whereas x = 10 / 3 would yield 3.33
  • Use % for the remainder of a division. example x = 10 % 3 would yield 1

Conditionals

all conditional statements

if condition1 or condition2: # can also use `and`
    print("do something")
elif:
    print("do something else")
else:
    print("cant do something")
  • You can also use the not operator to negate a condition. example if not condition:

List and Loops

lists

  • use append method to add to the list
  • to delete an item either use list.remote(item) or del list[index]
  • use in to check if an item is in the list. example if item in list:
  • to loop use for in loop. example for item in list:
  • use built-in sum function to add all elements of a list.
  • use the range function to generate a list. for example range(0, 10, 2) would result in [0, 2, 4, 6, 8], where 10 is the stop value and 2 is the step/increment value.

Dictionaries

dictionaries

  • Dictionaries in python are like objects in JavaScript.
  • use del keyword to delete a key/value pair. example del dict[key]
  • Looking up key that doesnt exists results in a KeyError. Use get method on dictionary for safe lookup. example dict.get(key, default_value)
  • get method can be chained to get nested values. example dict.get(key1).get(key2)
  • if a default_value is not specified then None is returned, this is equivalent to null in JavaScript and evaluates to false in a conditional statement.
  • use the items method on a dictionary to extract both key and value. example for key, value in dict.items():

Virtual Environments

  • use virtual envs to ensure packages installed using pip are isolated from other projects. By default pip installs packages globally.
  • to create a new virtual env use python -m venv my_venv
  • to activate the virtual env use source my_venv/bin/activate
  • to deactivate the virtual env just use deactivate
  • for more details see: https://docs.python.org/3/library/venv.html

Functions

  • function definition starts with the def keyword
  • example below:
def greet(name):
    print("Hello", name)
  • variable defined inside a function is local to that function
  • variables defined outside a function are global
  • to return a value from a function use the return keyword

Classes

  • class definition starts with the class keyword, followed by name and colon. ex: class MyClass:
  • the __init__ method is the constructor. ex: def __init__(self, name, age):
  • self is always the first param of the init method. It refers to the current instance of the class. somewhat equivalent to this in JavaScript.
  • Methods in classes also have self as the first param.
  • To inherit from a parent class, pass parent class name to the class args. for example: class MyClass(ParentClass):
  • re-defining the methods in the child class will override the parent class methods.
  • use the super() function to call parent classes methods. example: super().__init__(name, age)
  • new keyword is not required to instantiate a class object. for ex: my_obj = MyClass() is sufficient.

Modules

Packages

Exceptions

  • use try, catch and finally blocks to handle exceptions
  • example:
try:
    # do something
except:
    # handle exception
finally:
    # do something
  • to raise custom exceptions use the raise keyword. ex: - raise Exception("Invalid value")
  • to capture the exception object use the as keyword. ex: except FileNotFoundError as e:

File I/O

  • use the open function to open a file. example: file = open("file.txt")
  • use the close method to close the file. example: file.close()
  • use can also use the with keyword to open a file. example: with open("file.txt") as file: This will ensure the file is closed automatically.
  • read method can be used to read the contents of the file. example: file.read()
  • readlines method can be used to read the contents of the file as a list. example: file.readlines() This will return a list of lines in the file that can be looped over using the for-in loop.
  • We can also loop over the file object itself. example: for line in file:
  • To open file in write mode specify the mode as w. example: file = open("file.txt", "w"). This will overwrite the contents of the file, so be careful. use param 'a' to append to the file instead.
  • use the write method on the file to write to the file. example: file.write("Hello")

write mode

  • the os python module provides methods to work with the operating system and file system. example: os.remove("file.txt") will delete the file.
Up next Threat Modelling - Using Microsoft STRIDE Model Refactor react code to use state store instead of multiple useState hooks
Latest posts Refactor react code to use state store instead of multiple useState hooks Notes on Python Threat Modelling - Using Microsoft STRIDE Model WCAG - Notes Flutter CI/CD with Azure Devops & Firebase - iOS - Part 1 Flutter CI/CD with Azure Devops & Firebase - Android - Part 2 How to samples with AWS CDK A hashicorp packer project to provision an AWS AMI with node, pm2 & mongodb Some notes on Zeebe (A scalable process orchestrator) Docker-Compose in AWS ECS with EFS volume mounts Domain Driven Design Core Principles Apple Push Notifications With Amazon SNS AWS VPC Notes Building and Deploying apps using VSTS and HockeyApp - Part 3 : Windows Phone Building and Deploying apps using VSTS and HockeyApp - Part 2 : Android Building and Deploying apps using VSTS and HockeyApp - Part 1 : iOS How I diagnosed High CPU usage using Windbg WCF service NETBIOS name resolution woes The troublesome Git-Svn Marriage GTD (Getting things done) — A simplified view Javascript Refresher Sharing common connection strings between projects A simple image carousel prototype using Asp.net webforms and SignalR Simple logging with NLog Application logger SVN Externals — Share common assembly code between solutions Simple async in .net 2.0 & Winforms Clean sources Plus Console 2 — A tabbed console window