← Home

Python Lab

FOC
Basics

print() outputs to console. input() reads from keyboard. # starts a comment.

name = input("Name: ")
print(f"Hello, {name}!")  # f-string interpolation
x = 42          # int
pi = 3.14       # float
flag = True     # bool
Control Flow
# if / elif / else
if x > 10:
    print("big")
elif x > 0:
    print("small")
else:
    print("zero or negative")

# for loop
for i in range(5):      # 0,1,2,3,4
    print(i)

# while loop
while x > 0:
    x -= 1

# function
def add(a, b):
    return a + b
Data Types
# list (mutable, ordered)
nums = [1, 2, 3]
nums.append(4)         # [1,2,3,4]
nums[0]                # 1
nums[-1]               # 4

# tuple (immutable)
point = (10, 20)

# dict (key-value)
d = {"name": "Alice", "age": 25}
d["name"]              # "Alice"
d.keys()               # dict_keys(["name","age"])

# set (unique values)
s = {1, 2, 2, 3}      # {1, 2, 3}
String Methods
s = "hello world"
s.upper()              # "HELLO WORLD"
s.lower()              # "hello world"
s.split()              # ["hello", "world"]
",".join(["a","b"])    # "a,b"
s.replace("hello","hi")# "hi world"
s.strip()              # remove whitespace
s.find("world")        # 6
s[::-1]                # "dlrow olleh" (reverse)
len(s)                 # 11
List Operations
lst = [3, 1, 2]
lst.append(4)          # [3,1,2,4]
lst.pop()              # removes 4
lst.sort()             # [1,2,3]
lst.reverse()          # [3,2,1]
lst[1:3]               # [2,1] (slice)

# list comprehension
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]

sorted([5,2,8], reverse=True)  # [8,5,2]
File I/O
# read
with open("file.txt", "r") as f:
    content = f.read()

# write
with open("out.txt", "w") as f:
    f.write("hello")

# append
with open("log.txt", "a") as f:
    f.write("new line\n")

# read lines
with open("data.txt") as f:
    for line in f:
        print(line.strip())
Modules & Data
import json
data = json.loads('{"a": 1}')    # parse JSON string
text = json.dumps({"a": 1})      # to JSON string

import csv
# csv.reader, csv.writer

import os
os.getcwd()         # current directory
os.listdir(".")     # list files
os.path.exists("f") # check file

import sys
sys.argv             # command line args
SCORE: 0   STREAK: 0   1/20
SCORE: 0   STREAK: 0   1/20