Python syntax
Concatenate "hello" and "there"
"".join(["hello", "there"])
"Hi [name], my favorite color is [color]" - format
"Hi {0}, my favorite color is {1}".format("Kara", "blue")
String interpolation syntax - "Hi, #{name}"
"Hi, %s" % (name)
Push to the end of a list
.append()
String method to convert to lowercase
.lower()
String method to convert to uppercase
.upper()
Tuple
Immutable sequence of arbitrary objects. Like a list, but cannot add or change. Often used for multiple return values.
Variable for module's name
__name__
Switch values of a and b
a,b = b,a
&& operator
and
Rewrite border("Hello there", "*") to rearrange argument order (first argument is message, second is border)
border(border="*", message="Hello there")
Set default argument b to 5
def someFunction(b=5):
Object
dict
For loop syntax
for color in colors: (indent) print(color)
Iterate over keys and values in colors dict
for key, value in colors.items():
Get current time
from datetime import datetime datetime.now()
Import fetch_words and print_words from words.py
from words import (fetch_words, print_words)
Import all functions from words.py
from words import *
Check if runtime context is script or module
if __name__ is "__main__":
Control state syntax
if something: elif something: else something
Import module in repl (words.py)
import words
Break up "en-ca" by the hyphen. Save as language and country
language, country = "en-ca".partition("-")
Function to get length of string
len()
Array
list
Create an array of numbers 0 to 10, by twos
list(range(0,12,2))
! operator
not
order of ops between and, not, or
not, and, or
|| operator
or
is vs ==
p = [1,2] q = [1,2] p == q --> true p is q --> false
Create a new set
p = set()
Create new tuple "t" with one item - "hi"
t = ("hi",)
Set
unordered collection of immutable objects p = {10, 20, 30}
Create a new list
x = []
Create a new dict
x = {}
Copy a list "x" using slicing
x[:]