Olympus Blog

In the Olympus blog you'll find the latest news about the community, tutorials, helpful resources and much more! React to the news with the emotion stickers and have fun!

Python Functions: Default Arguments, *args, and **kwargs

Python Functions: Default Arguments, *args, and **kwargs

Python functions support advanced features like default values, variable-length arguments, and keyword arguments. In this guide, you’ll learn how to use default arguments, *args, and **kwargs to write flexible and reusable code.

Default Arguments

Function with Default Argument

def greet(name="Guest"):
    return f"Hello, {name}!"

Explanation

  • Default arguments provide a fallback value if the caller doesn’t supply one.
  • In this example, name defaults to "Guest".

Example Usage

print(greet())          # Output: "Hello, Guest!"
print(greet("Alice"))   # Output: "Hello, Alice!"

Variable-Length Arguments: *args

Function with *args

def calculate_sum(*args):
    return sum(args)

Explanation

  • *args collects extra positional arguments into a tuple.
  • Useful for functions that handle an unknown number of inputs.

Example Usage

print(calculate_sum(10, 20, 30))  # Output: 60

Keyword Arguments: **kwargs

Function with **kwargs

def describe_server(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

Explanation

  • **kwargs collects extra keyword arguments into a dictionary.
  • Ideal for functions requiring dynamic or named parameters.

Example Usage

describe_server(name="server1", status="running")

Output:

name: server1
status: running

Practice Work

Exercise 1: Default Arguments

Create a function create_user with default parameters for username (default: “guest”) and role (default: “user”).

# Your code here
Solution:

def create_user(username="guest", role="user"):
    return f"User '{username}' created as {role}"

Exercise 2: Use *args

Write a function multiply_all that multiplies all input numbers.

print(multiply_all(2, 3, 4))  # Expected Output: 24
Solution:

def multiply_all(*args):
    result = 1
    for num in args:
        result *= num
    return result

Exercise 3: Use **kwargs

Create a function build_profile that prints user details dynamically.

build_profile(name="Alice", age=30, role="Admin")
Solution:

def build_profile(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

Workshop: Real-World Applications

Workshop 1: Configuring Servers

Use **kwargs to dynamically configure server settings:

def configure_server(**settings):
    for setting, value in settings.items():
        print(f"Setting {setting} to {value}")

configure_server(host="192.168.1.1", port=8080, https=True)

Workshop 2: Shopping Cart

Use *args to calculate the total price of items:

def calculate_total(*prices):
    return sum(prices)

print(calculate_total(10.5, 20.0, 15.75))  # Output: 46.25

Best Practices

  • Avoid Mutable Defaults: Default arguments like def func(arg=[]) can lead to unexpected behavior.
  • Order of Parameters: Define parameters in this order: positional, *args, keyword, **kwargs.
  • Clarity Over Cleverness: Use *args/**kwargs judiciously to keep code readable.

Summary and Key Takeaways

  • Default Arguments: Provide fallback values for parameters.
  • *args: Handle variable positional arguments as a tuple.
  • **kwargs: Handle variable keyword arguments as a dictionary.
  • Flexibility: These features make functions adaptable to diverse use cases.

Conclusion

Mastering default arguments, *args, and **kwargs empowers you to write versatile and reusable functions. Practice these concepts to handle dynamic inputs and build robust Python applications.

Next Steps: Explore Python Decorators or Object-Oriented Programming in Python.

 

Python Functions: Reusable and Modular Code

Python Functions: Reusable and Modular Code

Functions are the building blocks of reusable and organized code in Python. In this guide, you’ll learn how to define functions, use parameters, return values, and apply best practices for writing clean and efficient code.

Defining a Simple Function

Basic Structure

def greet():
    return "Hello, World"

Explanation:

  • def keyword: Defines a function.
  • greet(): Function name and parentheses (no parameters here).
  • return keyword: Sends a result back to the caller.

Example Usage

print(greet())  # Output: "Hello, World"

Function Parameters

Adding Parameters

def greet_user(name):
    return f"Hello, {name}!"

Explanation:

  • name is a parameter: Allows passing values into the function.
  • Enables personalized output based on input.

Example Usage

print(greet_user("Alice"))  # Output: "Hello, Alice!"

Return Values in Functions

Purpose of Return Values

  • Compute and send data back to the caller.
  • Use functions in larger expressions (e.g., calculations).

Example: Add Two Numbers

def add(a, b):
    return a + b

Explanation:

  • Parameters a and b accept input values.
  • return a + b sends the sum back to the caller.

Example Usage

result = add(5, 3)
print(result)  # Output: 8

Practice Work

Exercise 1: Fix the Function

Correct the syntax errors in the code below:

def multiply(a b)
return a * b

Solution:

def multiply(a, b):
    return a * b

Exercise 2: Create a Temperature Converter

Write a function to convert Celsius to Fahrenheit using the formula: F = (C * 9/5) + 32.

Solution:

def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

Exercise 3: User Validation

Write a function that checks if a user is older than 18:

def is_adult(age):
    # Your code here

Solution:

def is_adult(age):
    return age >= 18

Workshop: Real-World Applications

Workshop 1: Calculator Function

Create a function that accepts two numbers and an operator (+, -, *, /) and returns the result.

def calculate(a, b, operator):
    if operator == '+':
        return a + b
    elif operator == '-':
        return a - b
    # Add more operators...

Workshop 2: Email Formatter

Write a function to format a user’s email address:

def format_email(first_name, last_name, domain):
    return f"{first_name}.{last_name}@{domain}"

Best Practices

  • Use Descriptive Names: e.g., calculate_discount instead of func1.
  • Keep Functions Short: Aim for single-responsibility functions.
  • Avoid Side Effects: Functions should return values, not modify global variables.

Summary and Key Takeaways

  • Reusability: Functions reduce code duplication.
  • Parameters: Customize function behavior with inputs.
  • Return Values: Send data back for use in larger workflows.
  • Modularity: Break complex tasks into smaller functions.

Conclusion

Mastering functions is essential for writing clean, efficient, and scalable Python code. Practice creating functions for everyday tasks to build modular applications.

Next Steps: Explore Python Classes and OOP or Error Handling in Python.

 

Working with Python Collections and Iterables

Working with Python Collections and Iterables

Python’s iterables and functional programming tools like map(), filter(), and reduce() enable efficient data processing. In this guide, you’ll learn to master iterators, lambda functions, and the itertools module for advanced workflows.

Iterables vs. Iterators

Definitions

  • Iterable: An object that can return its elements one at a time (e.g., lists, tuples, strings).
  • Iterator: An object representing a data stream. It implements __next__() to fetch items.

Using iter() and next()

my_list = [10, 20, 30]
iterator = iter(my_list)  # Convert iterable to iterator
print(next(iterator))     # 10
print(next(iterator))     # 20

Built-In Functions

map(): Apply a Function to Items

# Double each number in a list
numbers = [1, 2, 3]
doubled = map(lambda x: x * 2, numbers)  # Returns iterator
print(list(doubled))  # [2, 4, 6]

filter(): Select Items Conditionally

# Filter even numbers
numbers = [1, 2, 3, 4, 5]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))  # [2, 4]

reduce(): Aggregate Values

from functools import reduce
# Sum all numbers
total = reduce(lambda x, y: x + y, [1, 2, 3, 4])
print(total)  # 10

Lambda Functions

Anonymous functions for concise one-liners:

# Syntax: lambda arguments: expression
add = lambda x, y: x + y
print(add(5, 3))  # 8

The itertools Module

Advanced tools for working with iterables:

1. chain(): Combine Iterables

from itertools import chain
list1 = [1, 2]
list2 = ['a', 'b']
all_items = chain(list1, list2)  # 1, 2, 'a', 'b'

2. cycle(): Repeat Indefinitely

from itertools import cycle
count = 0
for item in cycle(['a', 'b']):
    print(item)  # a, b, a, b, ...
    count += 1
    if count == 4: break

3. islice(): Slice Iterators

from itertools import islice
numbers = range(10)
sliced = islice(numbers, 2, 6)  # 2, 3, 4, 5

4. groupby(): Group by Key

from itertools import groupby
data = [("a", 1), ("a", 2), ("b", 3)]
for key, group in groupby(data, lambda x: x[0]):
    print(key, list(group))  # a [('a',1), ('a',2)], b [('b',3)]

Practice Work

Exercise 1: Convert Loop to map()

Convert this loop to use map():

numbers = [1, 2, 3]
squared = []
for num in numbers:
    squared.append(num ** 2)
Solution:

squared = list(map(lambda x: x**2, numbers))

Exercise 2: Filter with Lambda

Use filter() to extract words longer than 3 characters:

words = ["apple", "cat", "dog", "elephant"]
Solution:

long_words = list(filter(lambda x: len(x) > 3, words))

Exercise 3: Use groupby()

Group numbers by even/odd:

numbers = [1, 2, 3, 4, 5, 6]
Solution:

from itertools import groupby
sorted_numbers = sorted(numbers, key=lambda x: x % 2)
for key, group in groupby(sorted_numbers, lambda x: x % 2):
    print("Even" if key == 0 else "Odd", list(group))

Workshop: Real-World Applications

Workshop 1: Data Pipeline

Process log files using itertools:

from itertools import chain
# Read multiple log files
logs = chain(open("log1.txt"), open("log2.txt"))
errors = [line for line in logs if "ERROR" in line]

Workshop 2: Aggregate Sales Data

Use reduce() to calculate total sales:

from functools import reduce
sales = [100, 200, 150]
total_sales = reduce(lambda x, y: x + y, sales)

Best Practices

  • Prefer List Comprehensions for Simplicity: Use map()/filter() when readability improves.
  • Avoid Complex Lambdas: Use named functions for multi-step logic.
  • Use itertools for Memory Efficiency: Iterators save memory with large datasets.

Conclusion

Mastering iterables, functional tools, and itertools unlocks efficient data processing in Python. Practice with the exercises to streamline your workflows!

Next Steps: Explore Python Generators or Data Classes.

 

How to Fix “Error mounting /dev/sdb2 at /media/ubuntu” in Ubuntu

How to Fix “Error mounting /dev/sdb2 at /media/ubuntu” in Ubuntu

This error typically occurs when Ubuntu can’t mount a partition due to filesystem issues. Follow these steps to resolve it:

🔧 Prerequisites

  • Administrative access (sudo privileges)
  • Backup critical data if possible

📌 Step 1: Identify the Partition

sudo fdisk -l

Look for your problematic partition (e.g., /dev/sdb2) and note its filesystem type.

📌 Step 2: Install Required Tools

sudo apt update
sudo apt install ntfs-3g exfat-fuse exfat-utils

📌 Step 3: Manual Mounting Attempt

sudo mkdir -p /media/ubuntu/drive
sudo mount -t ntfs /dev/sdb2 /media/ubuntu/drive

📌 Step 4: Repair Filesystem

For NTFS Partitions:

sudo ntfsfix -d /dev/sdb2

For ext4/ext3/ext2:

sudo umount /dev/sdb2
sudo fsck -y /dev/sdb2
⚠️ Important: Always unmount the drive before running repair commands!

📌 Step 5: Superblock Recovery (ext4)

sudo mke2fs -n /dev/sdb2  # Find backups
sudo fsck -b 32768 /dev/sdb2

📌 Step 6: Last Resort – Reformat

sudo mkfs.ntfs /dev/sdb2  # Erases all data!

💡 Summary

  1. Confirm partition details with fdisk -l
  2. Use ntfsfix or fsck for repairs
  3. Restore superblocks if needed
  4. Reformat only as last option

🔗 Additional Tips

  • Check disk health: sudo smartctl -a /dev/sdb
  • Always safely eject drives

 

Python List Comprehensions and Generator Expressions

Python List Comprehensions and Generator Expressions

List comprehensions and generator expressions are concise, efficient tools for creating and manipulating sequences in Python. In this guide, you’ll learn their syntax, benefits, and practical applications for writing clean and memory-efficient code.

List Comprehensions

List comprehensions provide a compact way to create lists by applying expressions to iterable items.

Syntax

[expression for item in iterable if condition]

Examples

# Squared numbers from 0 to 9
squared_numbers = [x**2 for x in range(10)]

# Even numbers between 0 and 9
even_numbers = [x for x in range(10) if x % 2 == 0]

Benefits

  • More concise and readable than traditional loops.
  • Often faster due to optimized internal implementation.

Generator Expressions

Generator expressions create iterators that generate values on-the-fly. They use parentheses () instead of brackets.

Syntax

(expression for item in iterable if condition)

Example

# Process lines from a large file lazily
large_dataset = (process(line) for line in big_file)

Benefits

  • Memory-efficient: Generate items one at a time.
  • Ideal for large datasets or streaming data.

Practical Examples

1. Filter Error Logs

error_lines = [line for line in log_file if 'ERROR' in line]

2. Data Transformation

# Extract IDs of active users
user_ids = [user.id for user in users if user.is_active]

3. Lazy Processing with Generators

# Sum squares of numbers without storing the list
total = sum(x**2 for x in range(1000000))

Practice Work

Exercise 1: Convert Loop to Comprehension

Convert this loop into a list comprehension:

numbers = []
for x in range(10):
    if x % 3 != 0:
        numbers.append(x * 2)
Solution:

numbers = [x * 2 for x in range(10) if x % 3 != 0]

Exercise 2: Filter with Generator

Use a generator expression to find the first 5 numbers divisible by 7 in a range.

# Hint: itertools.islice can help
import itertools
result = itertools.islice((x for x in range(100) if x % 7 == 0), 5)

Exercise 3: Nested Comprehension

Create a flattened list from a 2D matrix using a comprehension:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Solution:

flattened = [num for row in matrix for num in row]

Workshop: Real-World Applications

Workshop 1: Log Analysis

Parse a log file to count critical errors (assume logs are loaded as a list):

logs = [
    "INFO: System started",
    "ERROR: Disk full",
    "DEBUG: Connection established",
    "ERROR: File not found"
]
critical_errors = [log for log in logs if log.startswith("ERROR")]

Workshop 2: Streaming Data

Simulate processing a large CSV file lazily with a generator:

def read_large_file(filename):
    with open(filename) as f:
        for line in f:
            yield line.strip()

data_gen = read_large_file("data.csv")
processed = (line.split(',') for line in data_gen)

Best Practices

  • Avoid Over-Nesting: Keep comprehensions simple for readability.
  • Prefer Generators for Large Data: Use () instead of [] to save memory.
  • Use Descriptive Variable Names: e.g., user_ids instead of ids.

Conclusion

List comprehensions and generator expressions are powerful tools for writing concise, efficient Python code. Use comprehensions for readability and generators for memory efficiency with large datasets.

Next Steps: Explore Python Iterators and Generators or Functional Programming in Python.

 

Python Data Structures: Lists, Tuples, Sets, and Dictionaries

Python Data Structures: Lists, Tuples, Sets, and Dictionaries

Python provides powerful built-in data structures for efficient data storage and manipulation. In this guide, you’ll learn how to use lists, tuples, sets, and dictionaries with detailed explanations, practical examples, and hands-on exercises.

Lists

Lists are ordered, mutable collections of items. They are ideal for storing sequences of data where the order matters, and you may need to modify the data later.

Creating Lists

servers = ['web1', 'web2', 'db1']

Lists are created using square brackets []. Items are separated by commas.

Accessing Elements

first_server = servers[0]  # 'web1'

You can access elements using their index. Python uses zero-based indexing, so the first element is at index 0.

Modifying Lists

Lists are mutable, meaning you can change their content after creation.

servers.append('cache1')  # Add item to the end
servers.remove('db1')     # Remove item by value
web_servers = servers[:2] # Slice to get the first two items

Common operations include adding, removing, and slicing elements.

Common List Methods

  • append(): Add an item to the end.
  • remove(): Remove an item by value.
  • sort(): Sort the list in place.
  • reverse(): Reverse the list in place.
  • insert(): Insert an item at a specific index.

Tuples

Tuples are ordered, immutable collections. Once created, their content cannot be changed. They are ideal for storing fixed data, such as configuration settings.

Creating Tuples

config = ('localhost', 8080)

Tuples are created using parentheses (). Items are separated by commas.

Accessing Elements

host = config[0]  # 'localhost'

Like lists, you can access tuple elements using their index.

Immutability

# config[0] = '127.0.0.1'  # Error: Tuples are immutable

Once a tuple is created, you cannot modify its elements. This makes tuples safer for storing data that should not change.

Sets

Sets are unordered collections of unique elements. They are useful for eliminating duplicates and performing mathematical set operations like union, intersection, and difference.

Creating Sets

unique_users = {'alice', 'bob', 'charlie'}

Sets are created using curly braces {}. Items are separated by commas.

Adding Elements

unique_users.add('david')

You can add elements to a set using the add() method.

Set Operations

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union: Combine elements from both sets
all_users = set1.union(set2)  # {1, 2, 3, 4, 5}

# Intersection: Find common elements
common_users = set1.intersection(set2)  # {3}

# Difference: Find elements in set1 but not in set2
diff_users = set1.difference(set2)  # {1, 2}

Sets are powerful for comparing and combining collections of data.

Dictionaries

Dictionaries store key-value pairs. They are ideal for mapping relationships between data, such as user roles or product prices.

Creating Dictionaries

user_roles = {'alice': 'admin', 'bob': 'user'}

Dictionaries are created using curly braces {} with key-value pairs separated by commas.

Accessing Values

role = user_roles['alice']  # 'admin'

You can access values using their keys. If the key does not exist, Python raises a KeyError.

Adding/Modifying Entries

user_roles['charlie'] = 'moderator'

You can add or modify dictionary entries by assigning a value to a key.

Practice Work

Exercise 1: List Manipulation

Create a list of fruits and perform the following:

  1. Add “banana”.
  2. Remove “apple”.
  3. Print the first two fruits.
fruits = ['apple', 'orange', 'grape']
Solution:

fruits.append('banana')
fruits.remove('apple')
print(fruits[:2])

Exercise 2: Tuple Unpacking

Unpack the following tuple into variables:

coordinates = (10.5, 20.3)
Solution:

x, y = coordinates

Exercise 3: Set Operations

Given two sets, find the union, intersection, and difference:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
Solution:

union = set1.union(set2)
intersection = set1.intersection(set2)
difference = set1.difference(set2)

Exercise 4: Dictionary Lookup

Add a new user to the dictionary and print their role:

user_roles = {'alice': 'admin', 'bob': 'user'}
Solution:

user_roles['charlie'] = 'moderator'
print(user_roles['charlie'])

Workshop: Real-World Applications

Workshop 1: Inventory Management

Use a dictionary to track product stock levels:

inventory = {'apples': 50, 'bananas': 30, 'oranges': 40}
# Add 10 more apples
# Remove bananas
# Print the updated inventory

Workshop 2: Unique Usernames

Use a set to store unique usernames and prevent duplicates:

usernames = {'alice', 'bob'}
# Add 'charlie' and 'alice'
# Print the set

Best Practices

  • Use Lists for Ordered Data: When order matters.
  • Use Tuples for Immutable Data: When data should not change.
  • Use Sets for Unique Items: When duplicates are not allowed.
  • Use Dictionaries for Key-Value Pairs: When mapping relationships.

Conclusion

Mastering Python’s core data structures—lists, tuples, sets, and dictionaries—will help you store and manipulate data efficiently. Practice the exercises and workshops to solidify your understanding.

Next Steps: Explore Python List Comprehensions or Python Functions.

 

Python Looping Constructs: For, While, and Loop Control Statements

Python Looping Constructs: For, While, and Loop Control Statements

Loops are essential for automating repetitive tasks in Python. In this guide, you’ll learn how to use for and while loops, control flow with break, continue, and pass, and apply these concepts to real-world scenarios.

For Loops with range()

The range() function generates sequences for iterating with for loops. It has three forms:

1. range(stop)

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

2. range(start, stop)

for i in range(2, 6):
    print(i)  # Output: 2, 3, 4, 5

3. range(start, stop, step)

for i in range(0, 10, 2):
    print(i)  # Output: 0, 2, 4, 6, 8

While Loops

while loops repeat code as long as a condition is True:

count = 0
while count < 3:
    print("Count is", count)
    count += 1  # Output: 0, 1, 2

Loop Control Statements

1. break: Exit the Loop Immediately

for num in [1, 2, 3, 4, 5]:
    if num == 3:
        break  # Stops the loop
    print(num)  # Output: 1, 2

2. continue: Skip to the Next Iteration

for num in range(5):
    if num % 2 == 0:
        continue  # Skip even numbers
    print(num)  # Output: 1, 3

3. pass: Placeholder for Future Code

for num in range(3):
    pass  # Do nothing (used as a placeholder)

When to Use Loop Control

  • break: Stop early when a condition is met (e.g., finding the first match).
  • continue: Skip unwanted iterations (e.g., invalid inputs).
  • pass: Temporarily fill empty code blocks during development.

Practice Work

Exercise 1: Fix the Infinite Loop

Correct this while loop to avoid running infinitely:

count = 0
while count < 5:
    print(count)
Solution:

count = 0
while count < 5:
    print(count)
    count += 1

Exercise 2: Use continue

Modify this loop to skip numbers divisible by 3:

for num in range(10):
    print(num)
Solution:

for num in range(10):
    if num % 3 == 0:
        continue
    print(num)

Exercise 3: Use break

Stop the loop when the number 5 is found:

numbers = [1, 3, 5, 7, 9]
for num in numbers:
    print(num)
Solution:

numbers = [1, 3, 5, 7, 9]
for num in numbers:
    if num == 5:
        break
    print(num)

Workshop: Real-World Applications

Workshop 1: Number Guessing Game

Use a while loop to let the user guess a secret number (e.g., 7).

secret = 7
while True:
    guess = int(input("Guess a number: "))
    if guess == secret:
        print("Correct!")
        break
    print("Try again.")

Workshop 2: Filter Invalid Data

Use continue to skip negative numbers in a list:

data = [5, -2, 10, -8, 3]
for num in data:
    # Your code here
    print(num)
Solution:

data = [5, -2, 10, -8, 3]
for num in data:
    if num < 0:
        continue
    print(num)

Workshop 3: Password Attempt Limiter

Allow 3 login attempts using a while loop and break:

attempts = 0
correct_password = "admin123"

while attempts < 3:
    password = input("Enter password: ")
    if password == correct_password:
        print("Access granted!")
        break
    attempts += 1
else:
    print("Too many failed attempts.")

Best Practices

  • Avoid Infinite Loops: Ensure while loops have an exit condition.
  • Prefer for over while: Use for when iterating over known sequences.
  • Use Descriptive Variable Names: e.g., attempts instead of n.

Conclusion

Mastering loops and control statements unlocks the power of automation in Python. Practice with the exercises and workshops to build confidence in using for, while, break, and continue effectively.

Next Steps: Explore Python List Comprehensions or Python Functions.

 

Python Conditional Statements: Comparison Operators and Control Flow

Python Conditional Statements: Comparison Operators and Control Flow

Conditional statements allow your Python programs to make decisions. In this guide, you’ll learn how to use if, elif, and else with comparison operators to control program flow. Includes examples and practice exercises.

Comparison Operators

These operators return True or False to evaluate conditions:

  • == : Equal to
  • != : Not equal to
  • > : Greater than
  • < : Less than
  • >= : Greater than or equal to
  • <= : Less than or equal to
# Example: Check if a number is positive
num = 10
if num > 0:
    print("Positive number")

Conditional Statements (if, elif, else)

Basic if Statement

disk_usage = 85
if disk_usage > 80:
    print("Warning: Disk usage is above 80%")

if-elif-else Chain

status_code = 404
if status_code == 200:
    print("OK")
elif status_code == 404:
    print("Not found")
else:
    print("Error")

Nested Conditionals

user_logged_in = True
user_role = 'admin'

if user_logged_in:
    if user_role == 'admin':
        print("Access granted to admin panel")
else:
    print("Login required")

Even/Odd Check

number = int(input("Enter a number: "))
if number % 2 == 0:
    print(f"{number} is even")
else:
    print(f"{number} is odd")

Practice Work

Exercise 1: Fix the Code

Identify and correct errors in this conditional statement:

temperature = 32
if temperature =< 0: print("Freezing") elif temperature > 0 or temperature < 30:
    print("Cold")
eles:
    print("Hot")
Solution:

temperature = 32
if temperature <= 0:
    print("Freezing")
elif 0 < temperature < 30:
    print("Cold")
else:
    print("Hot")

Exercise 2: User Authentication

Write a program that checks if:

  • Username is “admin”
  • Password is “secret123”
# Your code here
username = input("Enter username: ")
password = input("Enter password: ")
Solution:

if username == "admin" and password == "secret123":
    print("Access granted")
else:
    print("Invalid credentials")

Exercise 3: Grade Classifier

Convert a numerical score (0-100) to a letter grade:

  • A: 90-100
  • B: 80-89
  • C: 70-79
  • F: Below 70
Solution:

score = 85
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("F")

Workshop: Real-World Scenarios

Workshop 1: Discount Calculator

Apply discounts based on purchase amount:

  • $100+ : 10% off
  • $200+ : 20% off
  • $500+ : 30% off
amount = float(input("Enter purchase amount: $"))
# Your code here

Workshop 2: Leap Year Checker

A year is a leap year if:

  • Divisible by 4, but not by 100
  • Unless also divisible by 400
year = 2024
# Your code here

Best Practices

  • Avoid Deep Nesting: Use elif instead of multiple nested if statements.
  • Use Parentheses for Complex Conditions: (x > 5) and (y < 10)
  • Write Readable Conditions: Use variables like is_logged_in instead of user == True.

Conclusion

Conditional statements are the backbone of decision-making in Python. Master comparison operators and practice with real-world scenarios to write efficient, readable code.

Next: Explore Python Loops and Logical Operators.

 

Python Operators and Expressions: Statements vs. Expressions

Understanding the difference between expressions and statements is crucial for writing effective Python code. In this guide, you’ll learn how operators work, how expressions produce values, and how statements control program flow. Practice with exercises and workshops to solidify your skills.

Expressions vs. Statements

What is an Expression?

An expression is a piece of code that evaluates to a value. Examples include arithmetic operations, function calls, or comparisons.

2 + 3          # Evaluates to 5
len("Hello")   # Evaluates to 5
3 > 2          # Evaluates to True

What is a Statement?

A statement is an instruction that performs an action. Examples include loops, conditionals, and variable assignments.

if x > 0:       # if statement
    print(x)

for i in range(5):  # for loop statement
    print(i)

Python Operators

1. Arithmetic Operators

print(10 + 3)   # 13 (Addition)
print(10 - 3)   # 7 (Subtraction)
print(10 * 3)   # 30 (Multiplication)
print(10 ** 3)  # 1000 (Exponentiation)
print(10 / 3)   # 3.333... (Division)
print(10 // 3)  # 3 (Floor Division)
print(10 % 3)   # 1 (Modulus)

2. Comparison Operators

print(5 == 5)   # True
print(5 != 3)   # True
print(5 > 3)    # True
print(5 <= 5)   # True

3. Logical Operators

print(True and False)  # False
print(True or False)   # True
print(not True)        # False

4. Assignment Operators

x = 5
x += 3   # Equivalent to x = x + 3 (x becomes 8)

Practice Work

Exercise 1: Identify Expressions vs. Statements

Label the following as expression or statement:

5 * (10 - 3)
x = 25
print("Hello")
sum = 2 + 3
Solution:

  • 5 * (10 – 3) → Expression
  • x = 25 → Statement
  • print(“Hello”) → Statement
  • sum = 2 + 3 → Statement (assignment is a statement)

Exercise 2: Fix Invalid Expressions

Correct the invalid code below:

result = 10 + * 3
if 5 > 3 and < 10:
    print("Valid")
Solution:

result = 10 * 3
if 5 > 3 and 5 < 10:
    print("Valid")

Exercise 3: Evaluate Expressions

What do these expressions evaluate to?

15 % 4
(5 > 3) or (2 == 3)
not (10 <= 5)
Solution:

  • 15 % 4 → 3
  • (5 > 3) or (2 == 3) → True
  • not (10 <= 5) → True

Workshop: Real-World Applications

Workshop 1: Temperature Converter

Write a script that converts Celsius to Fahrenheit using the formula: F = (C * 9/5) + 32.

celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F")

Workshop 2: User Login Validation

Check if a user’s input meets these conditions:

  • Username is at least 5 characters long.
  • Password contains at least 8 characters.
username = input("Enter username: ")
password = input("Enter password: ")

is_valid = (len(username) >= 5) and (len(password) >= 8)
print("Valid credentials?" , is_valid)

Best Practices

  • Use Parentheses for Clarity: (5 + 3) * 2 is clearer than 5 + 3 * 2.
  • Avoid Complex One-Liners: Break complicated expressions into multiple lines.
  • Prefer Descriptive Variables: discount_rate = 0.1 instead of dr = 0.1.

Conclusion

Mastering operators and understanding the difference between expressions and statements will help you write efficient and readable Python code. Practice the exercises and workshops to reinforce these concepts.

Next Steps: Explore our posts on Python Control Flow and Python Functions.

 

Python Variables and Identifiers: Rules, Examples, and Practice

Variables and identifiers are fundamental to programming in Python. In this guide, you’ll learn how to name variables correctly, avoid syntax errors, and follow Python’s naming conventions. We’ll also explore reserved keywords and practice with hands-on exercises.

Variables and Identifiers in Python

What Are Variables?

Variables are containers for storing data. They are created using an identifier (name) and the assignment operator =.

age = 25
name = "Mourad"
user_name = 'admin'
server_ip = '192.168.1.1'

Rules for Naming Identifiers

  • Can include letters, numbers, and underscores.
  • Cannot start with a number.
  • Cannot use reserved keywords (e.g., def, class).
  • Case-sensitive (Ageage).

Invalid Identifiers Example

#def = 5  # SyntaxError: "def" is a reserved keyword

Reserved Keywords

Python has predefined keywords that cannot be used as identifiers. View them using the keyword module:

import keyword
print(keyword.kwlist)

Practice Work

Exercise 1: Fix Invalid Identifiers

Correct the invalid identifiers in the code below:

2nd_name = "Ali"
class = "Python101"
user-email = "test@example.com"
Solution:

second_name = "Ali"
course_class = "Python101"
user_email = "test@example.com"

Exercise 2: Create Valid Identifiers

Write variables for the following data:

  1. A constant for maximum login attempts (value: 3).
  2. A string storing a server’s domain name (“api.example.com”).
  3. A boolean indicating whether a user is active (True/False).
Solution:

MAX_LOGIN_ATTEMPTS = 3
server_domain = "api.example.com"
is_user_active = True

Exercise 3: Reserved Keywords Check

Write a script to check if the word "async" is a reserved keyword in Python.

Solution:

import keyword
print("async" in keyword.kwlist)  # Output: True (in Python 3.7+)

Workshop: Real-World Practice

Workshop 1: User Registration Script

Create a script that asks for a user’s first name, last name, and age. Store the data in variables and print a summary. Follow these rules:

  • Use snake_case for variable names.
  • Avoid reserved keywords.
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
user_age = int(input("Enter your age: "))

print(f"User: {first_name} {last_name}, Age: {user_age}")

Workshop 2: Data Processing

Calculate the total price of items in a shopping cart using variables:

item1_price = 20.5
item2_price = 15.75
item3_price = 5.0
total = item1_price + item2_price + item3_price
print(f"Total: ${total:.2f}")

Best Practices

  • Use Descriptive Names: user_age instead of a.
  • Follow Case Conventions:
    • snake_case for variables (e.g., server_ip).
    • UPPER_CASE for constants (e.g., MAX_USERS).
  • Avoid Abbreviations: first_name is clearer than fn.

Conclusion

Mastering variables and identifiers is the first step to writing clean, maintainable Python code. Practice the exercises and workshops to solidify your understanding, and always follow Python’s naming conventions.

Want more? Check out our post on Python Data Types or Python Functions.

 

Python Code Structure: Scripts vs. Modules, Execution, and Best Practices

Understanding Python’s code structure is essential for writing reusable, maintainable, and executable programs. In this guide, we’ll explore the differences between scripts and modules, how to use the shebang line (#!/usr/bin/env python3), and best practices for organizing and executing Python code.

Scripts vs. Modules in Python

1. Scripts: Executable Files

A script is a Python file (.py) designed to be executed directly. Scripts typically perform tasks like data processing, automation, or running applications.

#!/usr/bin/env python3
# This is a script named "greet.py"
print("Hello, World!")

2. Modules: Reusable Code Libraries

A module is a Python file intended to be imported and reused in other scripts or modules. Modules contain functions, classes, or variables.

# This is a module named "math_utils.py"
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Shebang Line and File Permissions

Shebang Line: #!/usr/bin/env python3

The shebang line tells the operating system which interpreter to use to execute the script. Place it at the top of your script:

#!/usr/bin/env python3
print("This script uses Python 3!")

Setting File Permissions

To run a script directly, you must make it executable using chmod:

chmod +x script.py  # Grant execute permission
./script.py         # Run the script

Example: Script Execution Workflow

  1. Create a script: greet.py
  2. Add the shebang line and code:
#!/usr/bin/env python3
name = input("Enter your name: ")
print(f"Hello, {name}!")
  1. Make it executable:
chmod +x greet.py
  1. Run it:
./greet.py

Practice Work

Exercise 1: Create a Script

Write a script called calculator.py that asks the user for two numbers and prints their sum. Include the shebang line and make it executable.

#!/usr/bin/env python3
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(f"Sum: {num1 + num2}")

Exercise 2: Convert Script to Module

Convert the calculator.py script into a reusable module with functions for addition, subtraction, multiplication, and division.

# Module: calculator.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b

Exercise 3: Fix Permissions

If a script returns a “Permission denied” error, what command would you use to fix it? Write the answer below.

# Answer:
chmod +x script_name.py

Best Practices

  • Use Shebang for Clarity: Always include #!/usr/bin/env python3 in scripts to specify the Python version.
  • Organize Code into Modules: Reuse functions/classes across projects by separating logic into modules.
  • Name Scripts and Modules Clearly: Use descriptive filenames like data_analysis.py or utils.py.

Conclusion

Mastering Python’s code structure—scripts, modules, and execution—is key to building scalable and maintainable applications. Practice creating scripts, converting them to modules, and using the shebang line to ensure your code runs smoothly across systems.

Need more Python tutorials? Check out our posts on Python Functions and Object-Oriented Programming in Python.

 

Basic Syntax and Semantics: Python Indentation

Python is a powerful and beginner-friendly programming language known for its simplicity and readability. One of the most distinctive features of Python is its use of indentation to define code blocks. Unlike other programming languages that use braces {}, Python relies on proper spacing and alignment to group statements. In this chapter, we’ll explore Python’s indentation rules, comments, and line continuation, along with examples, exercises, and practical work (TP) to help you master these concepts.

Why Indentation Matters in Python

In many programming languages like C, Java, or JavaScript, curly braces {} are used to define blocks of code. However, Python takes a different approach. It uses indentation (spaces or tabs) to group statements logically. This makes Python code visually clean and easy to read.

Example of Indentation

if True:
    print('This is indented properly')  # This code is indented

In the example above:

  • The if statement is followed by a colon :.
  • The print() statement is indented with 4 spaces (or a tab) to indicate that it belongs to the if block.
  • If the indentation is incorrect, Python will throw an IndentationError.

Comments in Python

Comments are essential for explaining your code. Python supports two types of comments:

  1. Single-line comments: Use the # symbol.
  2. Multi-line comments: Use triple quotes ''' or """.

Example of Comments

# This is a single-line comment

"""
This is a multi-line comment.
It can span across multiple lines.
"""

Line Continuation in Python

Sometimes, a single line of code can become too long. Python allows you to break it into multiple lines using the backslash \ for line continuation.

Example of Line Continuation

total = 1 + 2 + 3 + \
        4 + 5 + 6
print(total)  # Output: 21

Here, the backslash \ tells Python that the statement continues on the next line.

Exercises to Practice

Now that you’ve learned the basics, let’s test your understanding with some exercises.

Exercise 1: Fix the Indentation

The following code has incorrect indentation. Fix it so it runs without errors.

if 5 > 2:
print('5 is greater than 2')

Exercise 2: Add Comments

Add a single-line comment and a multi-line comment to the code below.

x = 10
y = 20
sum = x + y
print(sum)

Exercise 3: Line Continuation

Rewrite the following code using line continuation to make it more readable.

result = 10 + 20 + 30 + 40 + 50 + 60 + 70 + 80 + 90 + 100
print(result)

TP (Practical Work)

To solidify your understanding, here are some practical tasks to complete. These tasks will help you apply the concepts of indentation, comments, and line continuation in real-world scenarios.

TP 1: Create a Simple Calculator

Write a Python program that performs basic arithmetic operations (addition, subtraction, multiplication, and division) using proper indentation and comments to explain each step.

# Example structure
num1 = 10
num2 = 5

# Addition
sum = num1 + num2
print("Sum:", sum)

# Subtraction
difference = num1 - num2
print("Difference:", difference)

# Add more operations here...

TP 2: Fix and Improve Code

The following code is poorly formatted and lacks comments. Fix the indentation, add comments, and use line continuation where necessary.

if 10 > 5:
print('10 is greater than 5')
else:
print('5 is greater than 10')
total = 10 + 20 + 30 + 40 + 50 + 60 + 70 + 80 + 90 + 100
print(total)

TP 3: Write a Program with Nested Conditions

Write a Python program that uses nested if statements to check multiple conditions. Ensure proper indentation and add comments to explain the logic.

# Example structure
age = 18
has_license = True

if age >= 18:
    if has_license:
        print("You are eligible to drive.")
    else:
        print("You need a license to drive.")
else:
    print("You are too young to drive.")

Conclusion

Understanding Python’s indentation, comments, and line continuation is crucial for writing clean and error-free code. By mastering these basics and completing the exercises and practical work (TP), you’ll be well on your way to becoming a proficient Python programmer. Practice the exercises provided, and don’t forget to experiment with your own code!

If you found this post helpful, share it with your friends and leave a comment below. Happy coding!

Latest Posts