๐Ÿ Week 1: Python Foundations

Day 2: Variables & Data Types

Duration: 5 Hours

๐Ÿ“š Learning Objectives

By the end of this session, you will be able to:

  • Create and use variables in Python
  • Understand the four basic data types: int, float, str, bool
  • Convert between data types (type casting)
  • Get user input with the input() function
  • Perform string operations and formatting

๐Ÿ“– Core Concepts (2 Hours)

What are Variables?

Variables are containers for storing data. Think of them as labeled boxes where you keep information.

# Creating variables (no declaration needed!) name = "DevOps Engineer" age = 25 salary = 75000.50 is_employed = True # Using variables print(name) # DevOps Engineer print(age) # 25 # Changing values age = 26 # Now age is 26 print(age) # 26 # Variable naming rules user_name = "alice" # snake_case (Python standard) serverCount = 10 # camelCase (works but not preferred) MAX_RETRIES = 3 # CAPS for constants # Invalid names: # 2name = "error" # Can't start with number # my-var = "error" # No hyphens # class = "error" # Can't use reserved words

Data Type: Integers (int)

# Integers are whole numbers (no decimals) server_count = 10 port = 8080 error_code = -1 large_num = 1_000_000 # Underscores for readability # Integer operations a = 15 b = 4 print(a + b) # 19 (addition) print(a - b) # 11 (subtraction) print(a * b) # 60 (multiplication) print(a / b) # 3.75 (division - returns float!) print(a // b) # 3 (integer division) print(a % b) # 3 (modulo/remainder) print(a ** b) # 50625 (power: 15^4) # Check type print(type(server_count)) #

Data Type: Floats (float)

# Floats are decimal numbers cpu_usage = 75.5 temperature = -10.8 pi = 3.14159 # Float operations price = 19.99 quantity = 3 total = price * quantity print(total) # 59.97 # Scientific notation distance = 1.5e10 # 1.5 ร— 10^10 tiny = 2.5e-5 # 0.000025 # Rounding value = 3.14159 print(round(value)) # 3 print(round(value, 2)) # 3.14 # Check type print(type(cpu_usage)) #

Data Type: Strings (str)

# Strings are text - use quotes name = "Alice" message = 'Hello, World!' path = "/var/log/syslog" # Multi-line strings description = """This is a multi-line string""" # String operations first = "Hello" last = "World" # Concatenation full = first + " " + last print(full) # Hello World # Repetition line = "-" * 20 print(line) # -------------------- # Length print(len("Python")) # 6 # Indexing (starts at 0!) text = "Python" print(text[0]) # P print(text[-1]) # n (last character) # Slicing print(text[0:3]) # Pyt print(text[2:]) # thon print(text[:4]) # Pyth # String methods msg = " hello world " print(msg.upper()) # " HELLO WORLD " print(msg.lower()) # " hello world " print(msg.strip()) # "hello world" print(msg.replace("world", "python")) # " hello python " print(msg.split()) # ['hello', 'world'] # Check type print(type(name)) #

Data Type: Booleans (bool)

# Booleans are True or False is_running = True has_error = False # Comparison operators return booleans x = 10 y = 5 print(x > y) # True print(x < y) # False print(x == y) # False print(x != y) # True print(x >= 10) # True print(x <= 5) # False # Boolean operations a = True b = False print(a and b) # False (both must be True) print(a or b) # True (at least one True) print(not a) # False (opposite) # Truthy and Falsy values print(bool(1)) # True print(bool(0)) # False print(bool("text")) # True print(bool("")) # False print(bool([1,2])) # True print(bool([])) # False # Check type print(type(is_running)) #

Type Conversion

# Converting between types # String to Integer age_str = "25" age_int = int(age_str) print(age_int + 5) # 30 # String to Float price_str = "19.99" price_float = float(price_str) print(price_float * 2) # 39.98 # Number to String count = 42 count_str = str(count) print("Count: " + count_str) # Count: 42 # Float to Integer (truncates!) value = 3.9 print(int(value)) # 3 (not rounded!) # Integer to Float num = 10 print(float(num)) # 10.0 # Check the type data = "100" print(type(data)) # print(type(int(data))) #

User Input with input()

# input() always returns a string! # Basic input name = input("Enter your name: ") print("Hello, " + name + "!") # Input with type conversion age = int(input("Enter your age: ")) print("Next year you'll be", age + 1) # Multiple inputs first = input("First name: ") last = input("Last name: ") full_name = first + " " + last print("Welcome,", full_name) # DevOps example server = input("Enter server name: ") port = int(input("Enter port number: ")) print(f"Connecting to {server}:{port}")

String Formatting (f-strings)

# f-strings (Python 3.6+) - the modern way! name = "Alice" age = 25 salary = 75000.50 # Basic f-string print(f"Name: {name}") print(f"Age: {age}") # Expressions inside print(f"Next year: {age + 1}") print(f"Double salary: ${salary * 2}") # Formatting numbers pi = 3.14159 print(f"Pi: {pi:.2f}") # Pi: 3.14 price = 1234567.89 print(f"Price: ${price:,.2f}") # Price: $1,234,567.89 # Padding for i in range(1, 4): print(f"Server{i:02d}") # Server01, Server02, Server03 # DevOps example status = "running" uptime = 99.95 print(f"Service Status: {status.upper()}") print(f"Uptime: {uptime:.1f}%")

๐Ÿ”ฌ Hands-on Lab (2.5 Hours)

Lab 1: Variable Practice

  • Create variables for: name, age, height, is_student
  • Print all variables with their types
  • Perform operations on numeric variables
# Lab 1: variables.py # Create your profile name = "Your Name" age = 25 height = 5.9 is_student = False # Print with types print(f"Name: {name} ({type(name).__name__})") print(f"Age: {age} ({type(age).__name__})") print(f"Height: {height} ({type(height).__name__})") print(f"Student: {is_student} ({type(is_student).__name__})") # Calculations birth_year = 2024 - age print(f"Birth year: {birth_year}")

Lab 2: Type Conversion

  • Convert strings to numbers
  • Convert numbers to strings
  • Handle conversion errors
# Lab 2: conversion.py # String to number port_str = "8080" port = int(port_str) print(f"Port + 1: {port + 1}") cpu_str = "75.5" cpu = float(cpu_str) print(f"CPU Usage: {cpu}%") # Number to string error_code = 404 message = "Error " + str(error_code) + " - Not Found" print(message) # Building connection string host = "localhost" port = 5432 db = "myapp" connection = f"{host}:{port}/{db}" print(f"Database: {connection}")

Lab 3: User Input Calculator

  • Get two numbers from user
  • Perform all math operations
  • Display formatted results
# Lab 3: calculator.py print("=== Simple Calculator ===") print() # Get input num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) # Calculations print() print("Results:") print(f" {num1} + {num2} = {num1 + num2}") print(f" {num1} - {num2} = {num1 - num2}") print(f" {num1} ร— {num2} = {num1 * num2}") print(f" {num1} รท {num2} = {num1 / num2:.2f}") print(f" {num1} ^ {num2} = {num1 ** num2}")

Lab 4: Server Info Script

  • Create a DevOps-style info script
  • Use all four data types
  • Format output professionally
# Lab 4: server_info.py print("=" * 40) print(" SERVER STATUS REPORT") print("=" * 40) # Server details (all data types!) hostname = "web-server-01" # str cpu_cores = 4 # int memory_gb = 16.0 # float is_healthy = True # bool # User input uptime_hours = int(input("Enter uptime (hours): ")) disk_usage = float(input("Enter disk usage (%): ")) # Display report print() print(f"Hostname: {hostname}") print(f"CPU Cores: {cpu_cores}") print(f"Memory: {memory_gb} GB") print(f"Uptime: {uptime_hours} hours ({uptime_hours // 24} days)") print(f"Disk Usage: {disk_usage:.1f}%") print(f"Health: {'โœ“ Healthy' if is_healthy else 'โœ— Unhealthy'}") print("=" * 40)

๐Ÿ“ Practice Exercises

  1. Create a "Mad Libs" program that asks for nouns, verbs, adjectives
  2. Build a temperature converter (Celsius to Fahrenheit)
  3. Write a program that calculates BMI from user input
  4. Create a formatted receipt with item names and prices

๐Ÿ’ก DevOps Relevance

Why this matters:

  • Variables: Store config values, API keys, server info
  • Strings: File paths, URLs, log messages
  • Numbers: Ports, thresholds, metrics
  • Booleans: Feature flags, health checks
  • input(): Interactive deployment scripts

โœ… Day 2 Checklist

  • Can create and use variables
  • Understand int, float, str, bool types
  • Can convert between types
  • Know how to get user input
  • Can format strings with f-strings
  • Understand string methods