Python


Beginners To Experts


The site is under development.

Basics

Introduction to Python

1.1 What is Python?

1.1.1 History and Overview

Python is a high-level, interpreted programming language. It is created by Guido van Rossum in 1991. It is known for its simple syntax, versatility, and strong community support.

Example 1: Hello World

# This is a simple Python program # Prints "Hello, World!" to the screen print("Hello, World!")
Output:
Hello, World!

Example 2: Checking Python’s Version

# Import the sys module to access system information import sys # Used for system-specific parameters # Print the Python version print("Python Version:", sys.version)
Output:
Python Version: 3.10.9 (or your installed version)

Example 3: Demonstrating Python’s simplicity

# Calculate the sum of two numbers a = 5 # Assign 5 to variable a b = 10 # Assign 10 to variable b # Add and print the result print("Sum of a and b is:", a + b)
Output:
Sum of a and b is: 15

1.1.2 Why Learn Python?

Python is beginner-friendly, used in various fields like machine learning, automation, web development, AI, data science, and app development.

Note: Indentation in Python

Indentation refers to the spaces or tabs at the beginning of a line of code. In Python, indentation is mandatory and defines the structure of code blocks.

Examples:

Correct Indentation

def greet(): print("Hello!") # Indented 4 spaces inside the function greet()

Incorrect Indentation

def greet(): print("Hello!") # Error: No indentation
Output:
IndentationError: expected an indented block

Indentation in Control Structures

age = 18 if age >= 18: print("You are an adult.") print("You can vote!") else: print("You are a minor.")

Explanation: The if and else blocks are indented to group the related code.

Indentation in Loops

for i in range(3): print(f"Number: {i}") if i == 1: print("This is one!")

Best Practices:

  • Use 4 spaces per level (never mix spaces and tabs).
  • Ensure consistency throughout the code.

Python Syntax Examples

Example 4: Easy-to-Read Syntax

# Python syntax is simple and readable name = "Michael" # Assign a name to the variable print("Hello,", name) # Print a greeting

Output:

Hello, Michael

Example 5: Cross-Platform Support

# Python works on Windows, macOS, and Linux # Demonstrate platform independence with a simple program print("Python works everywhere!") # Print a simple statement

Output:

Python works everywhere!

Installing Python and Setting Up IDEs

1.2.1 Setting Up Python for Windows, macOS, and Linux

Example 1: Verifying Python Installation

# Run this command in the terminal to check if Python is installed # This is not Python code but a terminal command python --version

Output:

Python 3.x.x

Setting Up Python & Django on Windows (Using VS Code)

Follow these steps to install and set up Python & Django on your Windows system using VS Code.

Install Python

1. Download the latest Python version from: Python.org

2. Run the installer and check "Add Python to PATH" before clicking Install Now.

3. Verify the installation by running:

python --version

If this doesn't work, try:

python3 --version

Install & Set Up a Virtual Environment

A virtual environment helps isolate dependencies.

Open Command Prompt (cmd) or PowerShell.

Navigate to your desired project folder:

mkdir my_django_project && cd my_django_project

Create a virtual environment:

python -m venv venv

Activate the virtual environment:

venv\Scripts\activate

If successful, your terminal will show (venv).

Install Django

pip install django

Verify the installation:

django-admin --version

Create a Django Project

Run:

django-admin startproject myproject .

This creates the following structure:

myproject/ │── manage.py │── myproject/ │ │── __init__.py │ │── settings.py │ │── urls.py │ │── asgi.py │ │── wsgi.py

Run the Development Server

Start the Django server:

python manage.py runserver

If successful, you'll see:

Starting development server at http://127.0.0.1:8000/

Open in VS Code

1. Download and install VS Code.

2. Install the Python extension.

3. Open your project folder in VS Code:

code .

Create a Django App

Inside your project, create a Django app:

python manage.py startapp myapp

This creates a folder structure like:

myproject/ │── myapp/ │ │── migrations/ │ │── __init__.py │ │── admin.py │ │── apps.py │ │── models.py │ │── tests.py │ │── views.py

Register the App in settings.py

Open myproject/settings.py and add 'myapp' inside INSTALLED_APPS:

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # Add this ]

Create & Apply Migrations

To create the database tables, run:

python manage.py migrate

Create a Superuser (For Admin Panel)

Run:

python manage.py createsuperuser

Enter a username, email, and password.

Test the Admin Panel

Start the server again:

python manage.py runserver

Go to http://127.0.0.1:8000/admin/ and log in using your superuser credentials.

Done!

Django has been successfully set up on Windows. You can now start building your application!

Setting Up Python & Django on MacOS

Verifying Python Installation

# Run this command in the terminal to check if Python is installed

# This is not Python code but a terminal command

python –version

Output:
Python 3.x.x

On Mac OS, if running python --version results in "command not found: python", it means Python isn't installed or isn't in the system's path. Follow these steps to fix it.

In Terminal type:

which python3

If Python is installed, this will return a path like in terminal:

/opt/homebrew/bin/python3

Otherwise, proceed with installation.

Install Python Using Homebrew (On Mac OS)

Do the following steps:

Install it using Homebrew:

A. Install Homebrew (If Not Installed)

First, check if Homebrew is installed:

brew --version

If not installed, run:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Then, add Homebrew to your shell:

echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zshrc
source ~/.zshrc

B. Install Python

Once Homebrew is ready, install Python:

brew install python

Verify the installation:

python3 --version

Create a Shortcut for python

By default, Python 3 is installed as python3. To use python, create an alias:

echo 'alias python="python3"' >> ~/.zshrc
source ~/.zshrc

Now, test it:

python --version

It should display something like:

Python 3.x.x

Install pip (If Needed)

python3 -m ensurepip --default-pip
python3 -m pip --version

Setting up Django

Install & Set Up a Virtual Environment

A virtual environment helps isolate dependencies.

Create and navigate to your project folder:

mkdir my_django_project && cd my_django_project

Create a virtual environment:

python -m venv venv

Activate the virtual environment:

# For macOS/Linux source venv/bin/activate

Your terminal should now show (venv), meaning the virtual environment is active.

Install Django

With the virtual environment activated, install Django:

pip install django

Verify the installation:

django-admin --version

Create a Django Project

Run:

django-admin startproject myproject .

This creates the following structure:

myproject/ │── manage.py │── myproject/ │ │── __init__.py │ │── settings.py │ │── urls.py │ │── asgi.py │ │── wsgi.py

Run the Development Server

Start the Django server:

python manage.py runserver

If successful, you'll see:

Starting development server at http://127.0.0.1:8000/

Open your browser and visit http://127.0.0.1:8000/ – you should see Django’s welcome page!

Open in VS Code

If you haven’t installed VS Code yet, download it from here.

Navigate to your project folder and open VS Code:

code .

Ensure the Python extension is installed in VS Code.

Create a Django App

Inside your project, create a Django app:

python manage.py startapp myapp

This creates a folder structure like:

myproject/ │── myapp/ │ │── migrations/ │ │── __init__.py │ │── admin.py │ │── apps.py │ │── models.py │ │── tests.py │ │── views.py

Register the App in settings.py

Open myproject/settings.py and add 'myapp' inside INSTALLED_APPS:

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # Add this ]

Create & Apply Migrations

To create the database tables, run:

python manage.py migrate

Create a Superuser (For Admin Panel)

Run:

python manage.py createsuperuser

Enter a username, email, and password.

Test the Admin Panel

Start the server again:

python manage.py runserver

Go to http://127.0.0.1:8000/admin/ and log in using your superuser credentials.

Done!

Django has successfully set up on your MacOS and you can now start building your application.

Setting Up Django on Linux (Using VS Code)

Install and set up Django on your Linux system using VS Code.

Install Python (If Not Installed)

Most Linux distributions come with Python pre-installed. Check your Python version by running:

python3 --version

If Python is not installed, install it using:

For Debian/Ubuntu

sudo apt update && sudo apt install python3 python3-pip python3-venv -y # For Debian/Ubuntu

For fedora

sudo dnf install python3 python3-pip python3-virtualenv -y # For Fedora

Install & Set Up a Virtual Environment

A virtual environment helps isolate dependencies.

1. Navigate to your desired project folder:

mkdir my_django_project && cd my_django_project

2. Create a virtual environment:

python3 -m venv venv

3. Activate the virtual environment:

source venv/bin/activate

If successful, your terminal will show (venv).

Install Django

With the virtual environment activated, install Django:

pip install django

Verify the installation:

django-admin --version

Create a Django Project

Run:

django-admin startproject myproject .

This creates the following structure:

myproject/ │── manage.py │── myproject/ │ │── __init__.py │ │── settings.py │ │── urls.py │ │── asgi.py │ │── wsgi.py

Run the Development Server

Start the Django server:

python manage.py runserver

If successful, you'll see:

Starting development server at http://127.0.0.1:8000/

Open your browser and visit http://127.0.0.1:8000/ – you should see Django’s welcome page!

Open in VS Code

1. Download and install VS Code.

2. Install the Python extension in VS Code.

3. Navigate to your project folder and open VS Code:

code .

Create a Django App

Inside your project, create a Django app:

python manage.py startapp myapp

This creates a folder structure like:

myproject/ │── myapp/ │ │── migrations/ │ │── __init__.py │ │── admin.py │ │── apps.py │ │── models.py │ │── tests.py │ │── views.py

Register the App in settings.py

Open myproject/settings.py and add 'myapp' inside INSTALLED_APPS:

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # Add this ]

Create & Apply Migrations

To create the database tables, run:

python manage.py migrate

Create a Superuser (For Admin Panel)

Run:

python manage.py createsuperuser

Enter a username, email, and password.

Test the Admin Panel

Start the server again:

python manage.py runserver

Go to http://127.0.0.1:8000/admin/ and log in using your superuser credentials.

Done!

Django has been successfully set up on Linux, and you can now start building your application!

1.2.2 Introduction to IDEs (Integrated Development Environment)

An IDE such as VSCode helps write, debug, and run code.

Example 2: VSCode Setup

  1. Install Visual Studio Code.
  2. Add the Python extension.
  3. Write this code and run it:
# This program is written and run in VSCode print("This is running in VSCode")

Output:

This is running in VSCode

Example 3: PyCharm (Another IDE)

  1. Install PyCharm Community Edition.
  2. Create a new Python project.
  3. Run the code:
# This program is run using PyCharm print("Welcome to PyCharm!")

Output:

Welcome to PyCharm!

Example 4: Jupyter Notebook (Another IDE)

  1. Install Jupyter with the command:
  2. pip install notebook
  3. Launch with jupyter notebook.
  4. Write this in a Jupyter cell:
# Jupyter supports inline visualization print("Welcome to Jupyter Notebook")

Output:

Welcome to Jupyter Notebook

Example 5: Checking Installed Modules

# List all installed Python modules import pkg_resources # Import package management tool installed_packages = pkg_resources.working_set for package in installed_packages: print(package.key, package.version) # Print package name and version

Output:

pip 23.0.1
setuptools 65.5.1
...

Writing and Running Python Code

1.3.1 Running Code in Python Shell

Example 1: Launching the Python Shell

  • Type python in your terminal to start the shell.
  • Enter this:
# Python Shell example >>> 2 + 3

Output:

5

1.3.2 Creating Python Scripts

Example 2: Writing and Running a Script

  1. Create a file called example.py.
  2. Type:
print("This is a Python script") # Save this code in example.py
  1. Run with:
python example.py

Output:

This is a Python script

Example 3: Accepting User Input

# A simple script that accepts user input name = input("Enter your name: ") # Prompt user print("Hello,", name) # Greet the user

Input:

Michael

Output:

Hello, Michael

Example 4: Python with Loops

# Save and run this script to demonstrate loops for i in range(5): # Loop from 0 to 4 print(f"Number {i}")

Output:

Number 0
Number 1
Number 2
Number 3
Number 4

Note:
f-string (formatted string literal) in Python.
An f-string allows you to embed expressions inside string literals using curly braces {}. The expressions inside the curly braces are evaluated at runtime and included in the resulting string.

Example 5: Writing a Function

# Define a function in a script def greet(name): # Print a greeting message print(f"Hello, {name}!") # Call the function greet("Michael")

Output:

Hello, Michael

Variables and Data Types

2.1.1 Numbers, Strings, Booleans

Example 1: Declaring Variables in Python

# Numbers x = 10 # Integer variable y = 3.14 # Float variable # Strings name = "Michael" # String variable # Boolean is_python_fun = True # Boolean variable # Print variables print("Integer:", x) print("Float:", y) print("String:", name) print("Boolean:", is_python_fun)

Output:

Integer: 10
Float: 3.14
String: Michael
Boolean: True

Example 2: Type Checking

# Use type() to check the data type of variables a = 25 # Integer b = "Python" # String c = False # Boolean # Print the types print(type(a)) # class 'int' print(type(b)) # class 'str' print(type(c)) # class 'bool'

Output:

<class 'int'>
<class 'str'>
<class 'bool'>

2.1.2 Type Conversion

Implicit Type Conversion

Implicit Type Conversion, also called type coercion, is when the Python interpreter automatically converts one data type to another during an operation, without the programmer needing to specify the conversion explicitly.

Example 3: Implicit Type Conversion

# Python automatically converts the integer to a float during addition num1 = 5 # Integer num2 = 2.5 # Float result = num1 + num2 # Implicit type conversion print("Result:", result) print("Type of result:", type(result))

Output:

Result: 7.5
Type of result: <class 'float'>

Explicit Type Conversion

Explicit Type Conversion, also known as type casting, is when a programmer manually converts one data type to another using built-in functions.

Common Type Conversion Functions:

  • int() — Converts to integer
  • float() — Converts to float
  • str() — Converts to string
  • list() — Converts to list
  • tuple() — Converts to tuple
  • bool() — Converts to Boolean

Example 4: Explicit Type Conversion

# Converting between data types explicitly num = "123" # String # Convert string to integer num_as_int = int(num) # Perform arithmetic operation print("String converted to integer:", num_as_int + 10)

Output:

String converted to integer: 133

Example 5: Boolean to Integer

# Booleans can be treated as integers is_true = True # Boolean value # Convert to integer print("Boolean as integer:", int(is_true)) # True is 1

Output:

Boolean as integer: 1

Basic Operators

2.2.1 Arithmetic, Comparison, Logical, Assignment Operators

Example 1: Arithmetic Operators

# Perform basic arithmetic operations a = 10 b = 3 print("Addition:", a + b) # 10 + 3 = 13 print("Subtraction:", a - b) # 10 - 3 = 7 print("Multiplication:", a * b) # 10 * 3 = 30 print("Division:", a / b) # 10 / 3 = 3.333... print("Modulus:", a % b) # 10 % 3 = 1

Output:

Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Modulus: 1

Example 2: Comparison Operators

# Comparing two numbers x = 5 y = 10 print("x == y:", x == y) # False print("x != y:", x != y) # True,(!= means NOT) print("x < y:", x < y) # True print("x > y:", x > y) # False

Output:

x == y: False
x != y: True
x < y: True
x > y: False

Example 3: Logical Operators

# Logical AND, OR, NOT a = True b = False print("a and b:", a and b) # False, Evaluates to True if both operands are True print("a or b:", a or b) # True, Evaluates to True if at least one operand is True. print("not a:", not a) # False, Reverses the truth value of the operand. Since a=true, it will make the value to False

Output:

a and b: False
a or b: True
not a: False

Example 4: Assignment Operators

# Using assignment operators num = 10 num += 5 # Same as num = num + 5 print("After +=:", num) # 15 num *= 2 # Same as num = num * 2 print("After *=:", num) # 30

Output:

After +=: 15
After *=: 30

Input and Output

2.3.1 input() and print() Functions

Using input() allows users to input values.

Example 1: Using input()

# Take input from the user name = input("Enter your name: ") # Input from user print("Hello,", name) # Print the user input

Input:

Michael

Output:

Enter your name: Michael
Hello, Michael

Example 2: Formatted Output

# Using formatted strings age = 25 print(f"My age is {age} years.") # f-string for formatting

Output:

My age is 25 years.

Using sep and end in print()

The print() function in Python has two powerful parameters:

  • sep (separator): Defines the string inserted between values when printing multiple arguments. Default value is a space (' ').
  • end (ending): Specifies what to print at the end of the output instead of the default newline (\n). Default value is a newline.

Example 3: Using sep and end in print()

# Customize print behavior print("Python", "is", "fun", sep="-") # Use '-' as separator print("End of line", end=".") # Use '.' as the line ending

Output:

Python-is-fun
End of line.

Note: split() Method in Python

The split() method is used to divide a string into a list of substrings based on a specified delimiter (separator).

Syntax: string.split(separator, maxsplit)

  • separator (optional): The character(s) that define where the splits occur. By default, whitespace (' ') is used.
  • maxsplit (optional): The number of splits to perform. If omitted, it splits all occurrences.

Example 4: Taking Multiple Inputs

# Input multiple values at once a, b = input("Enter two numbers separated by space: ").split() print("You entered:", a, "and", b)

Input:

10 20

Output:

You entered: 10 and 20

Python Comments

2.4.1 Single-line and Multi-line Comment

Example 1: Single-line Comments

# This is a single-line comment print("Single-line comments start with #") # This is another single-line comment

Output:

Single-line comments start with #

Example 2: Multi-line Comments

""" This is a multi-line comment. It is enclosed in triple quotes and can span multiple lines. """ print("Multi-line comments use triple quotes.")

Output:

Multi-line comments use triple quotes.

Example 3: Inline Comments

# Inline comments follow Python code x = 5 # Variable x stores the number 5 y = 10 # Variable y stores the number 10 print(x + y) # Add x and y, then print the result

Output:

15

Example 4: Commenting Out Code

# This is a code block with commented lines # Uncomment the lines below to execute them # a = 10 # b = 20 # print(a + b) print("Commented-out code is ignored.")

Output:

Commented-out code is ignored.

Example 5: Using Comments for Documentation

# Function to calculate the square of a number def square(num): """ This function calculates the square of a given number. Parameter: num (int or float): The number to square. Returns: int or float: The square of the number. """ return num ** 2 print(square(4)) # Output: 16

Output:

16

Control Flow in Python

1. Conditional Statements

Conditional statements allow you to execute certain blocks of code based on whether a condition is true or false. The main types are:

  • if: Executes a block of code if the condition is true.
  • elif: Checks for another condition if the previous condition is false.
  • else: Executes a block of code if all previous conditions are false.

Example:

age = 20 if age >= 18: print("You are an adult.") elif age >= 13: print("You are a teenager.") else: print("You are a child.")

Output:

You are an adult.

2. Loops

Loops allow you to execute a block of code repeatedly based on certain conditions. The main types are:

  • for loop: Iterates over a sequence (like a list, tuple, or string) and executes the code block for each item.
  • while loop: Repeats the code block as long as the condition is True.

Example of a for Loop:

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

Output:

apple
banana
cherry

Example of a while Loop:

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

Output:

Count is 0
Count is 1
Count is 2

3. Control Flow Keywords

Control flow keywords are used to manage the flow of execution in loops:

  • break: Exits the loop immediately and stops further iterations.
  • continue: Skips the rest of the code inside the current loop iteration and goes to the next iteration.
  • pass: A placeholder that does nothing, often used when the syntax requires a statement but you don't need to implement any logic.

Example of break:

for i in range(5): if i == 3: break # Exit the loop when i is 3 print(i)

Output:

0
1
2

Example of continue:

for i in range(5): if i == 3: continue # Skip this iteration when i is 3 print(i)

Output:

0
1
2
4

4. Functions

Functions allow you to group code into reusable blocks and control the flow by calling them when needed. A function is defined using the def keyword.

Example of a Function:

def greet(name): print("Hello,", name) greet("Michael") greet("Dad")

Output:

Hello, Michael
Hello, Dad

Summary

  • if / elif / else: Conditional statements to control execution based on conditions.
  • for / while: Loops to execute code repeatedly.
  • break, continue, pass: Control flow keywords for managing loops.
  • Functions: Grouping code into reusable blocks.

These control structures give flexibility and allow you to manage the logic and flow of your Python program.

Control Flow in Python

3.1 Conditional Statements (if, elif, else)

Example 1: Basic if Statement

Check if a number is positive:

num = 10 if num > 0: # Condition to check if the number is greater than 0 print("The number is positive.")

Output:

The number is positive.

Example 2: if-else Statement

Check if a number is even or odd:

num = 7 if num % 2 == 0: # Condition to check if the number is divisible by 2 or even print("The number is even.") else: print("The number is odd.")

Output:

The number is odd.

Example 3: if-elif-else Statement

Categorize a person's age:

age = 25 if age < 13: # Check if age is less than 13 print("Child") elif 13 <= age < 20: # Check if age is between 13 and 19 print("Teenager") else: # If none of the above conditions are true print("Adult")

Output:

Adult

Example 4: Nested if Statements

Check if a number is positive, negative, or zero:

num = -5 if num != 0: # Check if the number is not zero if num > 0: # Check if the number is positive print("The number is positive.") else: # If the number is not positive, it's negative print("The number is negative.") else: print("The number is zero.")

Output:

The number is negative.

Example 5: Using Logical Operators in Conditions

Check if a person can vote:

age = 18 citizen = True if age >= 18 and citizen: # Both conditions must be true print("You are eligible to vote.") else: print("You are not eligible to vote.")

Output:

You are eligible to vote.

3.2 Loops (for and while Loops, break, continue, pass)

For Loops

Example 1: Iterating Over a List

Print each item in a list:

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

Output:

apple
banana
cherry

Example 2: Using range() in for Loops

Print numbers from 1 to 5:

for i in range(1, 6): # Range from 1 to 5 print(i)

Output:

1
2
3
4
5

Note: range() Function in Python

The range() function is used to generate a sequence of numbers. It is often used in loops to specify the number of iterations. The syntax is:

range(start, stop, step)
  • start (optional): The starting value of the sequence. Default is 0.
  • stop: The sequence will stop before this value (exclusive).
  • step (optional): The difference between each number in the sequence. Default is 1.

Examples:

1. Basic Example with One Argument

for i in range(5): print(i)

Output:

0
1
2
3
4

2. Using start and stop

for i in range(2, 7): print(i)

Output:

2
3
4
5
6

3. Using start, stop, and step

for i in range(1, 10, 2): print(i)

Output:

1
3
5
7
9

4. Negative Step

for i in range(10, 0, -2): print(i)

Output:

10
8
6
4
2

5. Using range() in a List

numbers = list(range(5)) print(numbers)

Output:

[0, 1, 2, 3, 4]

Key Points:

  • range() generates an iterator (not a list), so it's memory efficient for large ranges.
  • The stop value is exclusive, meaning it will generate numbers up to but not including the stop value.
  • step can be positive or negative to control the direction.

While Loops in Python

The while loop in Python is used to repeatedly execute a block of code as long as a specified condition is True. Once the condition becomes False, the loop terminates.

Syntax:

while condition:
    # Code to execute while the condition is True

condition: A Boolean expression (True or False). The loop runs as long as this condition evaluates to True.

The code inside the loop runs repeatedly until the condition is False.

Examples:

1. Simple While Loop

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

Output:

0
1
2
3
4

Explanation:

  • The condition count < 5 is checked. As long as count is less than 5, the loop continues.
  • The value of count is incremented by 1 on each iteration, and when it reaches 5, the condition becomes False, and the loop stops.

2. Infinite While Loop

while True:
    print("This loop runs forever!")
    break  # To stop the infinite loop

Output:

This loop runs forever!

Explanation:

  • The loop continues running because the condition is always True.
  • The break statement is used to exit the loop and prevent it from running indefinitely.

3. While Loop with Else Clause

count = 0
while count < 3:
    print(count)
    count += 1
else:
    print("Loop completed successfully.")

Output:

0
1
2
Loop completed successfully.

Explanation:

  • The else block runs after the loop finishes normally (without a break).

4. While Loop with Continue

count = 0
while count < 5:
    count += 1
    if count == 3:
        continue  # Skip the iteration when count is 3
    print(count)

Output:

1
2
4
5

Explanation:

  • When count equals 3, the continue statement is executed, skipping that iteration and moving to the next one.

Key Points:

  • Condition: The loop will keep running as long as the condition evaluates to True.
  • Infinite Loop: Can occur if the condition always remains True. Ensure the condition changes at some point to avoid an infinite loop.
  • break: Exits the loop prematurely.
  • continue: Skips the current iteration and proceeds with the next one.

5. Example of a While Loop

count = 1
while count <= 5:  # Condition to run the loop
    print(count)
    count += 1  # Increment the counter

Output:

1
2
3
4
5

Break, Continue, Pass in Loops

Example 6: Using break

for num in range(1, 10):
    if num == 5:  # Stop the loop when num is 5
        break
    print(num)

Output:

1
2
3
4

Example 7: Using continue

for num in range(1, 6):
    if num == 3:  # Skip the iteration when num is 3
        continue
    print(num)

Output:

1
2
4
5

Defining and Calling Functions in Python

Functions in Python allow you to encapsulate reusable code into blocks that can be called with different parameters. They can have parameters and return values.

Examples:

1. Simple Function

def greet():
    print("Hello, World!")

greet()  # Call the function

Output:

Hello, World!

Explanation: This function doesn't take any parameters and simply prints "Hello, World!" when called.

2. Function with Parameters

def greet(name):
    print(f"Hello, {name}!")

greet("Michael")  # Pass an argument

Output:

Hello, Michael!

Explanation: The function takes one parameter, name, and prints a personalized greeting.

3. Function with Return Value

def square(num):
    return num ** 2

result = square(5)  # Call the function and store the result
print("Square:", result)

Output:

Square: 25

Explanation: This function returns the square of the input number.

4. Default Parameter Value

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

greet()  # Call without argument
greet("Michael")  # Call with argument

Output:

Hello, Guest!
Hello, Michael!

Explanation: The function has a default value for the name parameter. If no argument is passed, it uses the default.

5. Function with Multiple Parameters

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

print("Sum:", add(3, 7))  # Call with two arguments

Output:

Sum: 10

Explanation: This function adds two numbers and returns the result.

Python Modules

Importing Built-in Modules

1. Using the math Module

import math  # Import the math module

print("Square root of 16:", math.sqrt(16))
print("Pi value:", math.pi)

Output:

Square root of 16: 4.0
Pi value: 3.141592653589793

Explanation: The math module provides functions like sqrt() for square roots and constants like pi.

2. Using the random Module

import random  # Import the random module

print("Random number between 1 and 10:", random.randint(1, 10))

Output:

Random number between 1 and 10: (varies)

Explanation: The random module allows generating random numbers, in this case between 1 and 10.

Writing Custom Modules

3. Creating a Custom Module

1. Create a file my_module.py:

# my_module.py
def greet(name):
    return f"Hello, {name}!"

2. Import and use it:

import my_module

print(my_module.greet("Michael"))

Output:

Hello, Michael!

4. Importing Specific Functions

from my_module import greet

print(greet("Mehrsa"))

Output:

Hello, Mehrsa!

5. Using Aliases

import math as m

print("Cosine of 0:", m.cos(0))

Output:

Cosine of 0: 1.0

Lists and Tuples in Python

Example 1: Creating and Accessing Lists

# Create a list of fruits
fruits = ["apple", "banana", "cherry"]

# Access elements by index
print(fruits[0])  # First element
print(fruits[1])  # Second element
print(fruits[-1])  # Last element (negative indexing)

Output:

apple
banana
cherry

Example 2: List Slicing

# Slicing a list
numbers = [10, 20, 30, 40, 50]

# Extract a portion of the list
print(numbers[1:4])  # Items from index 1 to 3
print(numbers[:3])  # First 3 items
print(numbers[2:])  # Items from index 2 onward

Output:

[20, 30, 40]
[10, 20, 30]
[30, 40, 50]

Example 3: Modifying Lists

# Modify a list
colors = ["red", "blue", "green"]
colors[1] = "yellow"  # Change the second element
print(colors)

# Add elements to a list
colors.append("purple")  # Add an item at the end
print(colors)

# Remove elements from a list
colors.remove("green")  # Remove by value
print(colors)

Output:

["red", "yellow", "green"]
["red", "yellow", "green", "purple"]
["red", "yellow", "purple"]

Example 4: Using List Methods

# Demonstrate some list methods
numbers = [3, 1, 4, 1, 5]

numbers.sort()  # Sort the list in ascending order
print("Sorted:", numbers)

numbers.reverse()  # Reverse the list
print("Reversed:", numbers)

print("Count of 1:", numbers.count(1))  # Count occurrences of 1

Output:

Sorted: [1, 1, 3, 4, 5]
Reversed: [5, 4, 3, 1, 1]
Count of 1: 2

Example 5: Nested Lists

# Create a nested list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Access elements in the nested list
print(matrix[0])  # First row
print(matrix[1][2])  # Element in the second row and third column

Output:

[1, 2, 3]
6

Example 6: Creating Tuples

# Create a tuple
numbers = (10, 20, 30)

# Access elements in a tuple
print(numbers[0])  # First element
print(numbers[-1])  # Last element

Output:

10
30

Example 7: Tuple Immutability

# Attempting to modify a tuple (raises an error)
numbers = (10, 20, 30)
# numbers[0] = 15  # Uncommenting this line will raise a TypeError

Output:

TypeError: 'tuple' object does not support item assignment

Example 8: Tuple Unpacking

# Unpack values from a tuple
coordinates = (5, 10)
x, y = coordinates  # Assign tuple values to variables
print(f"x: {x}, y: {y}")

Output:

x: 5, y: 10

Example 9: Using Tuples in Functions

# Return multiple values using a tuple
def min_max(numbers):
    return min(numbers), max(numbers)  # Return a tuple

result = min_max([1, 2, 3, 4, 5])
print("Min and Max:", result)

Output:

Min and Max: (1, 5)

Example 10: Tuple Methods

# Using tuple methods
names = ("Alice", "Bob", "Alice", "Eve")

print("Count of 'Alice':", names.count("Alice"))  # Count occurrences
print("Index of 'Bob':", names.index("Bob"))  # Find index of 'Bob'

Output:

Count of 'Alice': 2
Index of 'Bob': 1

Python Dictionaries and Sets

Dictionaries

Example 1: Creating and Accessing Dictionaries

# Create a dictionary
person = {"name": "John", "age": 30, "city": "New York"}

# Access values by keys
print("Name:", person["name"])
print("Age:", person["age"])
        
Output:
Name: John
Age: 30
        

Example 2: Adding and Modifying Entries

# Add or modify entries in a dictionary
person = {"name": "John", "age": 30}

person["city"] = "New York"  # Add a new key-value pair
person["age"] = 31  # Modify an existing value
print(person)
        
Output:
{'name': 'John', 'age': 31, 'city': 'New York'}
        

Sets

Example 1: Creating Sets

# Create a set
unique_numbers = {1, 2, 3, 4, 5}
print("Set:", unique_numbers)
        
Output:
Set: {1, 2, 3, 4, 5}
        

Example 2: Adding and Removing Elements

# Add and remove elements in a set
numbers = {1, 2, 3}

numbers.add(4)  # Add an element
numbers.remove(2)  # Remove an element
print(numbers)
        
Output:
{1, 3, 4}
        

Nested Data Structures

Nested Lists and Dictionaries

Example 1: Nested Lists

    matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    print("First row:", matrix[0])
    print("Element in second row, third column:", matrix[1][2])
    

Output:
First row: [1, 2, 3]
Element in second row, third column: 6

Example 2: Looping through Nested Lists

    for row in matrix:
        print("Row:", row)
        for item in row:
            print(item, end=" ")
        print()
    

Example 3: Nested Dictionaries

    person = {
        "name": "John",
        "contact": {"email": "john@example.com", "phone": "123-456-7890"},
        "address": {"street": "123 Main St", "city": "New York"}
    }
    print("Email:", person["contact"]["email"])
    print("City:", person["address"]["city"])
    

Output:
Email: john@example.com
City: New York

Example 4: Looping through Nested Dictionaries

    for key, value in person.items():
        print(f"{key}: {value}")
        if isinstance(value, dict):
            for sub_key, sub_value in value.items():
                print(f"  {sub_key}: {sub_value}")
    

Example 5: Modifying Nested Data Structures

    person["contact"]["phone"] = "987-654-3210"
    person["address"]["city"] = "Los Angeles"
    print(person["contact"]["phone"])
    print(person["address"]["city"])
    

Output:
987-654-3210
Los Angeles

Comprehensions

List, Dictionary, and Set Comprehensions

Example 1: List Comprehension

    numbers = [1, 2, 3, 4, 5]
    squares = [num**2 for num in numbers]
    print(squares)
    

Output: [1, 4, 9, 16, 25]

Example 2: Conditional List Comprehension

    even_numbers = [num for num in numbers if num % 2 == 0]
    print(even_numbers)
    

Output: [2, 4]

Example 3: Dictionary Comprehension

    squares_dict = {num: num**2 for num in numbers}
    print(squares_dict)
    

Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Example 4: Conditional Dictionary Comprehension

    odd_squares_dict = {num: num**2 for num in numbers if num % 2 != 0}
    print(odd_squares_dict)
    

Output: {1: 1, 3: 9, 5: 25}

Example 5: Set Comprehension

    unique_squares = {num**2 for num in numbers}
    print(unique_squares)
    

Output: {1, 4, 9, 16}

Nested Data Structures

Nested Lists

# Create a nested list (list inside a list) matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Access elements in the nested list print("First row:", matrix[0]) # First row of the matrix print("Element in second row, third column:", matrix[1][2]) # Access element in second row, third column

Looping through Nested Lists

# Iterate through a nested list for row in matrix: print("Row:", row) for item in row: print(item, end=" ") print()

Nested Dictionaries

# Create a nested dictionary (dictionary inside a dictionary) person = { "name": "John", "contact": { "email": "john@example.com", "phone": "123-456-7890" }, "address": { "street": "123 Main St", "city": "New York" } } # Accessing values in a nested dictionary print("Email:", person["contact"]["email"]) print("City:", person["address"]["city"])

Looping through Nested Dictionaries

# Iterate through a nested dictionary for key, value in person.items(): print(f"{key}: {value}") if isinstance(value, dict): # Check if the value is a dictionary for sub_key, sub_value in value.items(): print(f" {sub_key}: {sub_value}")

Modifying Nested Data Structures

# Modify values in nested structures person["contact"]["phone"] = "987-654-3210" # Change phone number person["address"]["city"] = "Los Angeles" # Change city print(person["contact"]["phone"]) # Check modified value print(person["address"]["city"]) # Check modified city

Comprehensions in Python

Comprehensions in Python are concise ways to create lists, dictionaries, or sets by iterating over iterable objects. They are more readable and often faster than equivalent for loops.

Benefits of Comprehensions

  • Readability: Clear and concise syntax.
  • Performance: Faster than traditional loops.
  • Memory Efficiency: Generators are memory-efficient compared to lists.

Types of Comprehensions

1. List Comprehension

Syntax: [expression for item in iterable if condition]

Example:

squares = [x**2 for x in range(11) if x % 2 == 0]
print(squares) # Output: [0, 4, 16, 36, 64, 100]

2. Dictionary Comprehension

Syntax: {key_expression: value_expression for item in iterable if condition}

Example:

cubes = {x: x**3 for x in range(1, 6)}
print(cubes) # Output: {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

3. Set Comprehension

Syntax: {expression for item in iterable if condition}

Example:

unique_squares = {x**2 for x in range(1, 6)}
print(unique_squares) # Output: {1, 4, 9, 16, 25}

4. Generator Comprehension

Syntax: (expression for item in iterable if condition)

Example:

squares_gen = (x**2 for x in range(6))
print(list(squares_gen)) # Output: [0, 1, 4, 9, 16, 25]

Examples

Example 1: List Comprehension

numbers = [1, 2, 3, 4, 5]
squares = [num**2 for num in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]

Example 2: Conditional List Comprehension

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]

Example 3: Dictionary Comprehension

numbers = [1, 2, 3, 4, 5]
squares_dict = {num: num**2 for num in numbers}
print(squares_dict) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Example 4: Conditional Dictionary Comprehension

numbers = [1, 2, 3, 4, 5]
odd_squares_dict = {num: num**2 for num in numbers if num % 2 != 0}
print(odd_squares_dict) # Output: {1: 1, 3: 9, 5: 25}

Example 5: Set Comprehension

numbers = [1, 2, 2, 3, 3, 4]
unique_squares = {num**2 for num in numbers}
print(unique_squares) # Output: {1, 4, 9, 16}