Python Scripting Basics
You need enough Python to understand the Flask backend. If you already know Python, skim this.
Running Python
# Interactive mode
python3
>>> print("hello")
hello
>>> exit()
# Run a script
python3 myscript.py
Variables and Types
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
hobbies = ["reading", "coding"] # List
person = {"name": "Alice", "age": 25} # Dictionary
print(type(name)) # <class 'str'>
Strings
name = "Alice"
greeting = f"Hello, {name}!" # f-string — use this!
print(greeting) # Hello, Alice!
# String operations
text = " hello world "
print(text.strip()) # "hello world"
print(text.upper()) # " HELLO WORLD "
print(len(text)) # 15
print(text.split()) # ["hello", "world"]
Lists
fruits = ["apple", "banana", "cherry"]
fruits.append("date") # Add to end
fruits[0] # "apple" (index starts at 0)
fruits[-1] # "date" (last item)
len(fruits) # 4
for fruit in fruits:
print(fruit)
Dictionaries
person = {
"name": "Alice",
"age": 25,
"city": "NYC"
}
print(person["name"]) # "Alice"
person["job"] = "engineer" # Add key
person["age"] = 26 # Update value
Conditionals
age = 18
if age >= 18:
print("Adult")
elif age >= 13:
print("Teen")
else:
print("Child")
Loops
# For loop over a range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# For loop over a list
for fruit in ["apple", "banana"]:
print(fruit)
# While loop
count = 0
while count < 3:
print(count)
count += 1
Functions
def greet(name, greeting="Hello"):
"""Return a greeting string."""
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!
Reading and Writing Files
# Write to a file
with open("output.txt", "w") as f:
f.write("Hello file!\n")
# Read from a file
with open("output.txt", "r") as f:
content = f.read()
print(content)
# Read line by line
with open("output.txt", "r") as f:
for line in f:
print(line.strip())
Importing Modules
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.14159...
import random
print(random.randint(1, 10)) # Random number 1-10
from datetime import datetime
print(datetime.now()) # Current date/time
Try/Except (Error Handling)
try:
number = int(input("Enter a number: "))
print(100 / number)
except ValueError:
print("That's not a number!")
except ZeroDivisionError:
print("Can't divide by zero!")
except Exception as e:
print(f"Something went wrong: {e}")
Pip (Installing Packages)
pip install requests # Install a package
pip install flask # Install Flask
pip list # List installed packages
pip freeze > requirements.txt # Save dependencies
pip install -r requirements.txt # Install from file
Your Turn — Mini Script
Create analyze.py:
import sys
def count_words(filename):
"""Count words in a file."""
with open(filename, 'r') as f:
content = f.read()
words = content.split()
return len(words)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python analyze.py <filename>")
else:
count = count_words(sys.argv[1])
print(f"Word count: {count}")
Run it:
echo "Hello world this is a test" > test.txt
python analyze.py test.txt
# → Word count: 6