Week 3: Python Basics & Control Flow
There are three main ways to execute Python code, each with different use cases:
python script.py
- Execute a Python filepython -c "print('Hello World')"
- Run a single commandpython
- Start interactive Python shellPython development has evolved with modern tools that make coding faster and more reliable:
pip
for installing packagesuv run script.py
- Run scripts with automatic dependency management=
) to put data into variablessnake_case
for variable names (PEP 8 Style Guide)snake_case
(words separated by underscores)
user_name
, calculate_total
, is_valid
SCREAMING_SNAKE_CASE
(all caps)
MAX_ATTEMPTS = 3
, PI = 3.14159
PascalCase
(capitalize each word)
StudentRecord
, BankAccount
, WeatherData
lowercase
or snake_case
math
, user_authentication
# Multiple assignment
name, age, grade = "Alice", 20, "A"
# Tuple unpacking from a function return
def get_student_info():
return "Bob", 21, 3.8
student_name, student_age, gpa = get_student_info()
# Chained assignment
x = y = z = 0
# Augmented assignment operators
score = 85
score += 10 # Same as: score = score + 10
score *= 2 # Same as: score = score * 2
str
(string): Text data, enclosed in quotes ('
or "
)int
(integer): Whole numbers, positive or negativefloat
(floating-point): Numbers with decimal pointsbool
(boolean): Truth values (True
or False
)type()
function: Use this to check what type a variable is# Python automatically determines types
student_name = "Ada Lovelace" # str
student_id = 12345 # int
gpa = 3.95 # float
is_honors_student = True # bool
graduation_year = None # NoneType
# Check types
print(type(student_name)) # <class 'str'>
print(type(gpa)) # <class 'float'>
print(type(is_honors_student)) # <class 'bool'>
\n
(newline), \t
(tab).upper()
, .lower()
, .strip()
, .replace()
# Different ways to create strings
name = 'Alan Turing'
name = "Alan Turing" # Equivalent
quote = """Computing machinery and intelligence
was published in 1950 by Alan Turing."""
# Escape sequences
message = "Hello\nWorld\t!" # Hello(newline)World(tab)!
file_path = "C:\\Users\\Documents\\file.txt" # Windows path
# String methods
name = " alan turing "
print(name.strip().title()) # "Alan Turing"
print(name.upper()) # " ALAN TURING "
print(name.replace("alan", "Alan")) # " Alan turing "
1.5e3
means 1.5 × 10³ = 1500
+
, -
, *
, /
, //
(floor division), %
(modulo), **
(exponent)int()
, float()
, str()
# Integer examples
students_enrolled = 150
temperature_celsius = -5
big_number = 123456789012345678901234567890 # No limits!
# Float examples
pi = 3.14159
temperature_fahrenheit = 23.0
scientific = 1.5e6 # 1,500,000
# Arithmetic operations
result = 17 / 3 # 5.666666666666667 (regular division)
result = 17 // 3 # 5 (floor division)
result = 17 % 3 # 2 (remainder)
result = 2 ** 10 # 1024 (exponentiation)
# Type conversions
age_str = "21"
age_int = int(age_str) # Convert string to integer
pi_str = str(3.14159) # Convert float to string
input()
function: Gets text from user via keyboardint()
or float()
for numeric input# Simple string input
name = input("What is your name? ")
print(f"Hello, {name}!")
# Numeric input with conversion
age_str = input("What is your age? ")
age = int(age_str) # Convert to integer
# One-liner for numeric input
grade = float(input("Enter your grade (0-100): "))
# Multiple inputs
print("Tell me about yourself:")
name = input("Name: ")
age = int(input("Age: "))
favorite_color = input("Favorite color: ")
print(f"Hi {name}! You're {age} and love {favorite_color}.")
f"Hello {name}!"
- preferred method.format()
method: "Hello {}!".format(name)
- older but still common"Hello %s!" % name
- legacy, avoid in new codename = "Katherine Johnson"
salary = 75000.50
accuracy = 0.99999
# f-string examples (Python 3.6+)
print(f"Employee: {name}")
print(f"Salary: ${salary:,.2f}") # $75,000.50
print(f"Accuracy: {accuracy:.2%}") # 99.99%
print(f"Name width: {name:>20}") # Right-aligned
# .format() method examples
print("Hello {}! You earned ${:,.2f}".format(name, salary))
print("Accuracy: {:.1%}".format(accuracy))
# Complex f-string expressions
items = ["apple", "banana", "cherry"]
print(f"We have {len(items)} fruits: {', '.join(items)}")
# Multi-line f-strings
report = f"""
Employee Report:
Name: {name}
Salary: ${salary:,.2f}
Performance: {accuracy:.1%}
"""
type()
and print()
to inspect values# Common debugging techniques
name = input("Enter name: ")
print(f"Debug: name = '{name}', type = {type(name)}")
# Check if conversion worked
age_str = input("Enter age: ")
try:
age = int(age_str)
print(f"Successfully converted '{age_str}' to {age}")
except ValueError:
print(f"Couldn't convert '{age_str}' to a number")
Mad Libs Generator Preview:
def generate_mad_lib(adjective, noun, verb):
"""
Generates a short story using the provided words.
This function is testable and reusable!
"""
# Your task: Create a story using f-string formatting
# Must include all three parameters in the returned string
# Example structure: f"Once upon a time, a {adjective} {noun}..."
pass
# How it will be used (conceptual - you'll implement the function)
# word1 = input("Give me an adjective: ")
# word2 = input("Give me a noun: ")
# word3 = input("Give me a past-tense verb: ")
# result = generate_mad_lib(word1, word2, word3)
# print(result) # Should print your creative story!
Suggested reading before our next class:
Why this matters: - These are the same tools used by professional development teams - Understanding CI/CD workflows is increasingly expected by employers - You’ll set up your first automated workflow in Lab 03
True
or False
==
, !=
, <
, >
, <=
, >=
# Simple condition
temperature = 75
if temperature > 70:
print("It's warm outside!")
print("Perfect for a walk.")
# Multiple conditions
age = 20
has_id = True
if age >= 21 and has_id:
print("Welcome to the club!")
elif age >= 18:
print("You can vote, but can't enter the club.")
else:
print("Too young for either.")
==
(equal), !=
(not equal), <
, >
, <=
, >=
and
, or
, not
is
, is not
(check if same object)in
, not in
(check if item in collection)not
→ comparisons → and
→ or
# Comparison examples
score = 85
grade = "B"
is_passing = score >= 60 # True
is_excellent = score >= 90 # False
is_b_grade = grade == "B" # True
# Logical operators
has_homework = True
studied_hard = False
can_pass = has_homework and studied_hard # False
should_study = not studied_hard # True
might_pass = has_homework or studied_hard # True
# Membership testing
fruits = ["apple", "banana", "cherry"]
has_apple = "apple" in fruits # True
has_orange = "orange" not in fruits # True
# Complex conditions
username = "alice"
password = "secret123"
is_admin = False
if username == "alice" and password == "secret123" and not is_admin:
print("Regular user login successful")
for
loops: When you know what you want to iterate overwhile
loops: When you want to repeat until a condition changesbreak
(exit loop), continue
(skip to next iteration)# For loop with range()
print("Countdown:")
for i in range(5, 0, -1):
print(f"{i}...")
print("Blast off!")
# For loop with collections
students = ["Alice", "Bob", "Charlie"]
for student in students:
print(f"Hello, {student}!")
# While loop for user input
total = 0
while total < 100:
number = int(input("Enter a number (goal: reach 100): "))
total += number
print(f"Current total: {total}")
print("Goal reached!")
# Loop with break and continue
for i in range(10):
if i == 3:
continue # Skip 3
if i == 7:
break # Stop at 7
print(i) # Prints: 0, 1, 2, 4, 5, 6
range()
function: Your loop companion 📏range(stop)
: Numbers from 0 to stop-1range(start, stop)
: Numbers from start to stop-1range(start, stop, step)
: Numbers from start to stop-1, incrementing by steplist(range(5))
to see all values# Basic range patterns
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(1, 6))) # [1, 2, 3, 4, 5]
print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8]
print(list(range(10, 0, -1))) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# Practical examples
# Print multiplication table
number = 7
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
# Process items with indices
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(f"Item {i}: {fruits[i]}")
# Better way: enumerate()
for i, fruit in enumerate(fruits):
print(f"Item {i}: {fruit}")
Number Guessing Game Preview:
import random
def guessing_game():
"""
Plays a number guessing game with the user.
Demonstrates while loops, conditionals, and user interaction.
"""
secret = random.randint(1, 100)
attempts = 0
print("I'm thinking of a number between 1 and 100!")
while True: # Continue until user guesses correctly
guess = int(input("Enter your guess: "))
attempts += 1
if guess < secret:
print("Too low! Try again.")
elif guess > secret:
print("Too high! Try again.")
else:
print(f"Correct! You guessed it in {attempts} attempts!")
break # Exit the loop when correct
# This allows the game to run when script is executed directly
if __name__ == '__main__':
guessing_game()
random
, math
, datetime
pip install package_name
to add functionalityrequests
(web), pandas
(data), flask
(web apps)# Standard library examples
import random
import math
import datetime
# Random numbers for games, simulations
lucky_number = random.randint(1, 10)
coin_flip = random.choice(["heads", "tails"])
# Mathematical functions
area = math.pi * (radius ** 2)
square_root = math.sqrt(16)
# Date and time operations
today = datetime.date.today()
formatted = today.strftime("%B %d, %Y")
# Coming later: third-party packages
# pip install requests
# import requests
# response = requests.get("https://api.github.com/users/bgreenwell")
pytest
🧪test_
, functions start with test_
assert
statements to check results# In your lab03.py file
def add_numbers(a, b):
"""Add two numbers and return the result."""
return a + b
# In test_lab03.py file
def test_add_numbers():
"""Test that add_numbers works correctly."""
result = add_numbers(2, 3)
assert result == 5
result = add_numbers(-1, 1)
assert result == 0
result = add_numbers(0, 0)
assert result == 0
# .github/workflows/main.yml
name: run-pytest
on: [push] # Run when code is pushed
jobs:
build:
runs-on: ubuntu-latest # Fresh Linux machine
steps:
- uses: actions/checkout@v3 # Get your code
- uses: actions/setup-python@v4 # Install Python
- name: Install dependencies
run: pip install pytest # Install testing tools
- name: Test with pytest
run: pytest # Run all tests
What you’ll build:
Key learning outcomes: - Master Python fundamentals through practical application - Set up automated testing and continuous integration - Create interactive, user-friendly programs - Follow professional development practices
Your comprehensive Python fundamentals lab awaits:
labs/lab03/README.md
Remember: This is your first step into professional Python development!
IS4010: App Development with AI