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.
# This is a simple Python program
# Prints "Hello, World!" to the screen
print("Hello, World!")
# Import the sys module to access system information
import sys
# Used for system-specific parameters
# Print the Python version
print("Python Version:", sys.version)
# 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)
Python is beginner-friendly, used in various fields like machine learning, automation, web development, AI, data science, and app development.
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.
def greet():
print("Hello!") # Indented 4 spaces inside the function
greet()
def greet():
print("Hello!") # Error: No indentation
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.
for i in range(3):
print(f"Number: {i}")
if i == 1:
print("This is one!")
# Python syntax is simple and readable
name = "Michael"
# Assign a name to the variable
print("Hello,", name) # Print a greeting
Output:
Hello, Michael
# 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!
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
Follow these steps to install and set up Python & Django on your Windows system using VS Code.
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
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).
pip install django
Verify the installation:
django-admin --version
Run:
django-admin startproject myproject .
This creates the following structure:
myproject/
│── manage.py
│── myproject/
│ │── __init__.py
│ │── settings.py
│ │── urls.py
│ │── asgi.py
│ │── wsgi.py
Start the Django server:
python manage.py runserver
If successful, you'll see:
Starting development server at http://127.0.0.1:8000/
1. Download and install VS Code.
2. Install the Python extension.
3. Open your project folder in VS Code:
code .
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
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
]
To create the database tables, run:
python manage.py migrate
Run:
python manage.py createsuperuser
Enter a username, email, and password.
Start the server again:
python manage.py runserver
Go to http://127.0.0.1:8000/admin/ and log in using your superuser credentials.
Django has been successfully set up on Windows. You can now start building your application!
# 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.
Do the following steps:
Install it using Homebrew:
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
Once Homebrew is ready, install Python:
brew install python
Verify the installation:
python3 --version
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
python3 -m ensurepip --default-pip
python3 -m pip --version
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.
With the virtual environment activated, install Django:
pip install django
Verify the installation:
django-admin --version
Run:
django-admin startproject myproject .
This creates the following structure:
myproject/
│── manage.py
│── myproject/
│ │── __init__.py
│ │── settings.py
│ │── urls.py
│ │── asgi.py
│ │── wsgi.py
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!
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.
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
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
]
To create the database tables, run:
python manage.py migrate
Run:
python manage.py createsuperuser
Enter a username, email, and password.
Start the server again:
python manage.py runserver
Go to http://127.0.0.1:8000/admin/ and log in using your superuser credentials.
Django has successfully set up on your MacOS and you can now start building your application.
Install and set up Django on your Linux system using VS Code.
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
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).
With the virtual environment activated, install Django:
pip install django
Verify the installation:
django-admin --version
Run:
django-admin startproject myproject .
This creates the following structure:
myproject/
│── manage.py
│── myproject/
│ │── __init__.py
│ │── settings.py
│ │── urls.py
│ │── asgi.py
│ │── wsgi.py
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!
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 .
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
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
]
To create the database tables, run:
python manage.py migrate
Run:
python manage.py createsuperuser
Enter a username, email, and password.
Start the server again:
python manage.py runserver
Go to http://127.0.0.1:8000/admin/ and log in using your superuser credentials.
Django has been successfully set up on Linux, and you can now start building your application!
An IDE such as VSCode helps write, debug, and run code.
Example 2: VSCode Setup
# This program is written and run in VSCode
print("This is running in VSCode")
Output:
This is running in VSCode
# This program is run using PyCharm
print("Welcome to PyCharm!")
Output:
Welcome to PyCharm!
pip install notebook
jupyter notebook
.
# Jupyter supports inline visualization
print("Welcome to Jupyter Notebook")
Output:
Welcome to Jupyter Notebook
# 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 ...
Example 1: Launching the Python Shell
python
in your terminal to start the shell.
# Python Shell example
>>> 2 + 3
Output:
5
Example 2: Writing and Running a Script
example.py
.
print("This is a Python script")
# Save this code in example.py
python example.py
Output:
This is a Python script
# 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
# 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.
# 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
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
# 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'>
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 integerfloat()
— Converts to floatstr()
— Converts to stringlist()
— Converts to listtuple()
— Converts to tuplebool()
— Converts to BooleanExample 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
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
# 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
# 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
# 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
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
# Using formatted strings
age = 25
print(f"My age is {age} years.") # f-string for formatting
Output:
My age is 25 years.
The print() function in Python has two powerful parameters:
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.
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)
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
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 #
"""
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.
# 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
# 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.
# 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
Conditional statements allow you to execute certain blocks of code based on whether a condition is true or false. The main types are:
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.
Loops allow you to execute a block of code repeatedly based on certain conditions. The main types are:
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
Control flow keywords are used to manage the flow of execution in loops:
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
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
These control structures give flexibility and allow you to manage the logic and flow of your Python program.
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.
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.
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
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.
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.
Print each item in a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple banana cherry
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
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)
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]
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.
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
.
count = 0
while count < 5:
print(count)
count += 1 # Increment count by 1
Output:
0
1
2
3
4
Explanation:
count < 5
is checked. As long as count
is less than 5, the loop continues.count
is incremented by 1 on each iteration, and when it reaches 5, the condition becomes False
, and the loop stops.while True:
print("This loop runs forever!")
break # To stop the infinite loop
Output:
This loop runs forever!
Explanation:
True
.break
statement is used to exit the loop and prevent it from running indefinitely.count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop completed successfully.")
Output:
0
1
2
Loop completed successfully.
Explanation:
else
block runs after the loop finishes normally (without a break
).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:
count
equals 3, the continue
statement is executed, skipping that iteration and moving to the next one.True
.True
. Ensure the condition changes at some point to avoid an infinite loop.count = 1
while count <= 5: # Condition to run the loop
print(count)
count += 1 # Increment the counter
Output:
1
2
3
4
5
for num in range(1, 10):
if num == 5: # Stop the loop when num is 5
break
print(num)
Output:
1
2
3
4
for num in range(1, 6):
if num == 3: # Skip the iteration when num is 3
continue
print(num)
Output:
1
2
4
5
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.
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.
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.
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.
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.
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.
math
Moduleimport 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
.
random
Moduleimport 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.
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!
from my_module import greet
print(greet("Mehrsa"))
Output:
Hello, Mehrsa!
import math as m
print("Cosine of 0:", m.cos(0))
Output:
Cosine of 0: 1.0
# 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
# 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]
# 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"]
# 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
# 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
# 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
# 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
# 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
# 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)
# 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
# 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
# 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'}
# Create a set
unique_numbers = {1, 2, 3, 4, 5}
print("Set:", unique_numbers)
Output:
Set: {1, 2, 3, 4, 5}
# 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}
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
for row in matrix: print("Row:", row) for item in row: print(item, end=" ") print()
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
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}")
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
numbers = [1, 2, 3, 4, 5] squares = [num**2 for num in numbers] print(squares)
Output: [1, 4, 9, 16, 25]
even_numbers = [num for num in numbers if num % 2 == 0] print(even_numbers)
Output: [2, 4]
squares_dict = {num: num**2 for num in numbers} print(squares_dict)
Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
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}
unique_squares = {num**2 for num in numbers} print(unique_squares)
Output: {1, 4, 9, 16}
# 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
# Iterate through a nested list
for row in matrix:
print("Row:", row)
for item in row:
print(item, end=" ")
print()
# 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"])
# 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}")
# 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 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.
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]
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}
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}
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]
numbers = [1, 2, 3, 4, 5]
squares = [num**2 for num in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
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]
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}
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}
numbers = [1, 2, 2, 3, 3, 4]
unique_squares = {num**2 for num in numbers}
print(unique_squares) # Output: {1, 4, 9, 16}