Everything on these pages is explained properly in the chapters. This is the “I know I’ve seen it somewhere” version.
# Values and variablesPython ▶ Watch it run Copy
1 name = "Sara" # str (text)
2 age = 29 # int (whole number)
3 height = 1.68 # float (decimal)
4 member = True # bool (True or False)
5 nothing = None # no value at all
6
7 type (age) # <class 'int'>
8 int ("42" ), float ("3.5" ), str (42 ) # converting
# TextPython Copy
1 f"{name} is {age}" # f-string
2 f"{price:.2f}" # two decimal places
3 len (name) # 4
4 name.upper (), name.lower (), name.title ()
5 name.strip () # remove spaces at both ends
6 name.replace ("a" , "o" )
7 name.split ("," ) # text -> list
8 ", " .join (names) # list -> text
9 name.startswith ("S" ), name.endswith (".py" )
10 "ar" in name # True
11 name[0 ], name[-1 ], name[1 :3 ]
# Arithmetic and comparisonPython Copy
1 7 + 2, 7 - 2, 7 * 2, 7 / 2 # 9 5 14 3.5
2 7 // 2, 7 % 2, 7 ** 2 # 3 1 49
3 round(3.14159, 2) # 3.14
4 == != < <= > >= # comparisons
5 and or not # combining them
# Decisions and loopsPython Copy
1 if score >= 80 :
2 print ("great" )
3 elif score >= 50 :
4 print ("pass" )
5 else :
6 print ("try again" )
7
8 for item in items:
9 print (item)
10
11 for i in range (5 ): # 0, 1, 2, 3, 4
12 print (i)
13
14 for i, item in enumerate (items, start=1 ):
15 print (i, item)
16
17 while count > 0 :
18 count -= 1
19
20 break # leave the loop now
21 continue # skip to the next round
# Lists, tuples, dictionaries and setsPython ▶ Watch it run Copy
1 items = ["a" , "b" , "c" ]
2 items.append ("d" ); items.remove ("a" ); items.sort ()
3 items[0 ], items[-1 ], items[1 :3 ], len (items)
4 point = (3 , 4 ) # tuple: can't change
5 phones = {"Ana" : "0412" , "Raj" : "0499" }
6 phones["Zoe" ] = "0455" # add or change
7 phones.get ("Tom" , "unknown" ) # safe lookup
8 for name, number in phones.items ():
9 print (name, number)
10 seen = {"red" , "blue" } # set: no duplicates
11 seen.add ("red" ) # still two items
12 squares = [n * n for n in range (5 )] # list comprehension
# FunctionsPython ▶ Watch it run Copy
1 def area (width, height=1 ):
2 """Return the area of a rectangle."""
3 return width * height
4
5 area (3 , 4 )
6 area (width=3 ) # height uses its default
# ErrorsPython ▶ Watch it run Copy
1 try :
2 age = int (text)
3 except ValueError:
4 print ("Please type a number." )
5 else :
6 print ("Thanks" )
7 finally :
8 print ("This always runs" )
9
10 raise ValueError ("age must be positive" )
# Files and foldersPython ◇ See the flowchart Copy
1 from pathlib import Path
2
3 HERE = Path (__file__).parent
4 path = HERE / "data" / "notes.txt"
5 text = path.read_text (encoding="utf-8" )
6 path.write_text ("hello\n" , encoding="utf-8" )
7
8 with open (path, "a" , encoding="utf-8" ) as f:
9 f.write ("one more line\n" )
10
11 path.exists (), path.name, path.stem, path.suffix
12 for p in HERE.glob ("*.csv" ):
13 print (p.name)
# ClassesPython ▶ Watch it run Copy
1 class Remote:
2 MAX_VOLUME = 100 # class variable
3
4 def __init__ (self, name): # factory settings
5 self.name = name # instance variable
6 self.volume = 10
7
8 def volume_up (self): # a method
9 self.volume += 1
10
11 def __str__ (self): # used by print()
12 return f"{self.name}: {self.volume}"
13
14 bedroom = Remote ("Bedroom" ) # an object
15 bedroom.volume_up ()
# ModulesPython ◇ See the flowchart Copy
1 import math # use as math.sqrt(16)
2 from random import choice # use as choice(items)
3 import pandas as pd # a short nickname
4
5 if __name__ == "__main__" : # only when run directly
6 main ()
# Terminal commandsTask Windows macOS and Linux Which Python? python --version or py --versionpython3 --versionRun a script python hello.pypython3 hello.pyWhere am I? cdpwdList files dirlsGo into a folder cd python-projectscd python-projectsGo up one folder cd ..cd ..Make a virtual environment python -m venv .venvpython3 -m venv .venvSwitch it on .venv\Scripts\activatesource .venv/bin/activateSwitch it off deactivatedeactivateInstall a package python -m pip install requestspython3 -m pip install requestsSave your package list pip freeze > requirements.txtpip freeze > requirements.txtInstall from the list pip install -r requirements.txtpip install -r requirements.txtStop a running program Ctrl+C Ctrl+C
# VS Code shortcutsTask Windows and Linux macOS Command Palette Ctrl+Shift+P Cmd+Shift+P Choose which Python Command Palette, then Python: Select Interpreter the same Open or close the terminal Ctrl and the backtick key Ctrl and the backtick key Save Ctrl+S Cmd+S Comment or uncomment lines Ctrl+/ Cmd+/ Find in this file Ctrl+F Cmd+F Rename a variable everywhere F2 F2 Start debugging F5 F5 Zoom in or out Ctrl+= and Ctrl+- Cmd+= and Cmd+-