Python Refresher

INFO 153B/253B: Backend Web Architecture

Kay Ashaolu - Instructor

Aishwarya Sriram - TA

What Is in This Lesson?

  • Overview of Python Variables
  • String Formatting Techniques
  • User Input and Conversion
  • Core Data Structures (Lists, Tuples, Sets, Dictionaries)
  • Conditional Statements and Loops
  • Function Basics, Parameters, and Return Values

Variables in Python

  • A variable is a “name” for a value
  • Example:
 x = 15
 price = 9.99
  • Variable references a location in memory
  • Right side (value) is created first, then left side (name) assigned

Variables in Depth

  • Variables are references, not strictly boxes
  • Types:
    • int (e.g., 1500)
    • float (e.g., 9.99)
    • str (e.g., "Hello")
  • Reassignment:
  name = "Rolf"
  name = "Bob"  # Now `name` points to "Bob"

Variables in Action

discount = 0.2
price = 9.99
result = price * (1 - discount)
print(result)  # 7.992
  • Shows variable usage, arithmetic, and print function
  • price * (1 - discount) is evaluated, then stored

String Formatting: f-Strings

  • Available in Python 3.6+
  • Embed variables directly:
 name = "Bob"
 greeting = f"Hello, {name}"
 print(greeting)  # Outputs: Hello, Bob
  • Simplifies building user-friendly strings

String Formatting: str.format()

  • Template approach:
 greeting = "Hello, {}!"
 with_name = greeting.format("Rolf")
 print(with_name)  # Hello, Rolf!
  • Useful when reusing templates with multiple placeholders:
 message = "Hello, {}. Today is {}."
 print(message.format("Alice", "Monday"))

Getting User Input

  • input() reads a string from the console
  • Example:
 name = input("Enter your name: ")
 print(f"Nice to meet you, {name}!")
  • Always returns a str, even if the user types numbers

Combining Input & Type Conversion

  • Convert string to int/float:
 user_input = input("Enter a number: ")
 number = int(user_input)
 print(number * 2)
  • Example usage:
 square_feet = int(input("Size in sq ft: "))
 sq_metres = square_feet / 10.8
 print(f"{square_feet} sq ft is {sq_metres:.2f} sq m")

Writing Our First Python App

  • Simple age-to-months example:
 user_age = int(input("Enter your age: "))
 months = user_age * 12
 print(f"Your age, {user_age}, equals {months} months.")

Lists, Tuples, and Sets

  • Lists: Ordered, mutable, [1, 2, 3]
  • Tuples: Ordered, immutable, (1, 2, 3)
  • Sets: Unordered, no duplicates, {"a", "b"}
  • Choose based on your data’s needs

Lists vs. Tuples vs. Sets

  • Lists:
    • Append/remove elements freely
 friends = ["Bob", "Rolf"]
 friends.append("Anne")
  • Tuples:
    • Fixed once created
 names = ("Bob", "Anne")
 # Can't modify!
  • Sets:
    • Fast membership tests ("Bob" in my_set)
    • No duplicate items

Manipulating Lists in Python

  • Subscript notation: friends[0] for the first element
  • Adding/removing:
 friends = ["Bob", "Rolf"]
 friends.append("Anne")
 friends.remove("Bob")
  • Lists are heavily used for ordered collections

Example: List & Indices

grades = [35, 67, 98, 100, 100]
total = sum(grades)
average = total / len(grades)
print(f"Average grade: {average}")
  • Summation and length demonstrate list utility

Booleans & Comparisons

  • True / False
  • Common operators: ==, !=, >, <, >=, <=
  • The is keyword checks if two references are the exact same object:
 a = [1, 2]
 b = [1, 2]
 print(a == b)  # True
 print(a is b)  # False

If Statements

day = input("Enter the day: ").lower()

if day == "monday":
    print("Have a great start to your week!")
elif day == "tuesday":
    print("Keep going!")
else:
    print("Full speed ahead!")
  • Indentation defines blocks
  • if/elif/else chain covers multiple conditions

Nested If & Elif

  • More complex checks:
if age >= 18:
    if has_permission:
        print("Access granted")
    elif age >= 21:
        print("Special privileges for 21+!")
    else:
        print("Permission denied")
else:
    print("Underage")

Loops: While

  • Repeat code while condition is True
 user_input = ""
 while user_input != "n":
     user_input = input("Play again? (Y/n): ")
     if user_input == "n":
         print("Goodbye!")
  • Caution: Must ensure condition eventually becomes false or break out

Loops: For

  • Iterate over collections:
# Iterating over a list
friends = ["Bob", "Rolf", "Anne"]
for friend in friends:
    print(f"{friend} is my friend")

# Using range() with default start=0
for i in range(3):
    print(i) 
# Outputs: 0, 1, 2
  • Use range() to loop a certain number of times

List Comprehensions

  • Concise way to transform lists
 numbers = [1, 2, 3]
 doubled = [x * 2 for x in numbers]
 # doubled -> [2, 4, 6]
  • Syntax: [<expression> for <var> in <iterable>]

List Comprehensions with Conditionals

friends = ["Sam", "Samantha", "Bob", "Anne"]
starts_s = [friend for friend in friends if friend.startswith("S")]
print(starts_s)  # ["Sam", "Samantha"]
  • Filter elements using an if clause

Dictionaries

  • Key-value mapping:
 friend_ages = {
     "Rolf": 24,
     "Adam": 30,
     "Anne": 27
 }
  • Access via keys: friend_ages["Adam"] -> 30

Iterating Over Dictionaries

for name, age in friend_ages.items():
    print(f"{name} is {age} years old.")
  • .items() returns key-value pairs
  • .values() returns just values
  • .keys() returns just keys

Functions in Python

def say_hello():
    print("Hello!")
  • Define using def keyword
  • Call with say_hello()
  • Allows code reuse & organization

Function Parameters & Return Values

def add(x, y):
    return x + y

result = add(5, 8)
print(result)  # 13
  • Positional arguments: add(5, 8)
  • Keyword arguments: add(x=5, y=8)
  • If no return, function returns None by default

Summary

  • Python Refresher: Variables, data structures, conditionals, loops, functions
  • Why It Matters:
    1. Forms the foundation for backend logic
    2. Essential for handling data & building RESTful APIs

Questions?