Skip to main content

Python

References

Serve Files Locally - SimpleHttpServer

https://stackabuse.com/serving-files-with-pythons-simplehttpserver-module/

Serve up a directory

CD to the specific directory and run this command

Python 2

python -m SimpleHTTPServer 8000

Python 3

python3 -m http.server 8000

Cheat Sheets

Notes

Common Imports

import math
import collections

import numpy as np
import pandas as pd
import matplotlib.pyplot as pp

%matplotlib inline

Comments

Single-line comments are designated with the pound sign

  # A single-line Comment

For multiline comments, you can use the pound sign in front of each line or surround the text with tripple quotes

  # First line of a multiline comment.
# This is the second line.

"""
This is the first line of a multiline comment.

Here is another line.
"""

Variables

You can use “ or ' when creating strings

msg = "Hello"
number = 50
character = 'A'

Determine a Variable’s Type

type()

Convert a Variable to a Specific Type

str()
int()
float()
# Print a string
msg = "Some string"
print(msg)

# Include a numeric value
itemCount = 100
print("Item count: " + str(itemCount))

# Use the string format() function
user = {"firstName": "Samuel", "lastName": "Jackson"}
print('Attendee: {} {}'.format(user['firstName'], user['lastName']))

Strings

String + String Concatenation

str1 = "aaa"
str2 = "bbb"
str3 = str1 + str2
=> "aaabbb"

String + Number Concatenation

Use str() to convert a number to a string

str1 = "aaa"
num1 = 5
concat1 = str1 + str(num1)
=> "aaa5"

Access a character of a string at a specific location

str1 = "hello"
str1[0] ==> "h"

Get a sub-string

str1 = "hello"
str1[1:3] ==> "ell"

Find string length

str1 = "hello"
len(str1) ==> 5

Remove leading and trailing whitespace

str1 = " hello "
str1.strip() ==> "hello"

String format()

The format() method formats the specified value(s) and insert them inside the string's placeholder. The values are either a list of values separated by commas, a key=value list, or a combination of both.

string.format(value1, value2...)

Examples

txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)

See the Formatting Types section on the W3 Schools: Python String Format page for different format type tokens that indicate how the values should be formatted. The list below is referenced from that page.

TypeDescription
:<Left aligns the result (within the available space)
:>Right aligns the result (within the available space)
:^Center aligns the result (within the available space)
:=Places the sign to the left most position
:+Use a plus sign to indicate if the result is positive or negative
:-Use a minus sign for negative values only
:Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers)
:,Use a comma as a thousand separator
:_Use a underscore as a thousand separator
:bBinary format
:cConverts the value into the corresponding unicode character
:dDecimal format
:eScientific format, with a lower case e
:EScientific format, with an upper case E
:fFix point number format
:FFix point number format, in uppercase format (show inf and nan as INF and NAN)
:gGeneral format
:GGeneral format (using a upper case E for scientific notations)
:oOctal format
:xHex format, lower case
:XHex format, upper case
:nNumber format
:%Percentage format
# Use "," to add a comma as a thousand separator:

txt = "The universe is {:,} years old."

print(txt.format(13800000000))

Getting Input from the User

Use input()

msg = "Your name: "
print(msg)
userName = input()
print("Hello" + userName)

If/Else

Note: Python uses tabs to determine statement hierarchy so be sure to place a tab in front of the ‘statements’ lines.

if condition:
statements
elif condition:
statements
else:
statements

Python Loops

for i in range(0, 10):
print(i)

for i in range(5):
print(i)

for i in range(0, 10, 2):
print(i)

for dItem in someDictionary:
print("==>Some value: " + dItem["somePropertyName"])

Looping through dictionaries

  • Use for key, value in some_dictionary.items(): to iterate over both the keys and values of dictionary items using tuple expansion.
  • Other variations: for key in some_dictionary.keys(): and for value in some_dictionary.values():
  • Calling the .keys(), .values(), .items() functions of a dictionary don't return a list but a type of iterator. You can convert these iterators to lists by passing the iterator to the list type. For example, list(some_dictionary.items())

Dictionaries, Sets, Tuples

Sets

  • A set is structured similar to a dictionary in that it only contains keys but no values: e.g. `some_set = {"one", "two", "four"}
  • Duplicate keys in a set will only be reflected once when the set is referenced.
  • You iterate over a set similar to other iterables.
  • Call add and remove to manipulate a set. E.g. some_set.add("five")

Sorting a Dictionary

GitHub - Question: How to sort a list of dictionaries by value

Dictionary

newlist = sorted(list_to_be_sorted, key=lambda d: d['name'], reverse=False)

Tuples

from operator import itemgetter

newlist = sorted(list_to_be_sorted, key=itemgetter('name'))

# or
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)

Comprehensions

Comprehensions offer a shorter syntax when you want to create a new list based on the values of another list. This is similar to filter and map in other functional languages.

newlist = [expression for item in iterable if condition == True]
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

Dataclass

from dataclasses import dataclass

@dataclass
Class personclass:
firstname: str
lastname: str
birthday: str = "unknown"

def fullname(self):
return self.firstname + " " + self.lastname

michelle = personclass("Michelle", "Vallisneri")

print(michelle.fullname())