What is Programming Languages?
A programming language is a set of instructions that you can use to tell a computer what
to do. Just like how we use languages like English or Hindi to communicate with each
other, we use programming languages to communicate with computers.
Think of a computer as a very smart but literal machine. It doesn’t understand human
language, so we need to use a programming language to give it commands in a way it
understands.
Example:
Imagine you want the computer to add two numbers together. In English, you might say,
"Add 2 and 3." But the computer doesn’t understand that. Instead, you can use a
programming language like Python.
In Python, you would write:
print(2 + 3)
When you run this code, the computer will do exactly what you asked: it will add 2 and 3
together and show you the result, which is 5.
Key Points:
● Instructions: Programming languages allow you to give specific instructions to a
computer.
● Different Languages: There are many programming languages, like Python, Java,
and C++. Each has its own rules and uses.
● Purpose: We use programming languages to create software, websites, apps, and
more.
So, a programming language is simply a tool that helps you control what the computer
does.
Introduction to Python Programming Language
Python is a high-level, interpreted programming language known for its simplicity and
readability. It was created by Guido van Rossum and first released in 1991. Python's
design philosophy emphasizes code readability and simplicity, which makes it an
excellent language for beginners as well as experienced programmers.
Why Should We Learn Python?
1. Simplicity and Readability:
- Example: Consider a simple program to print "Hello, World!".
print("Hello, World!")
Python uses plain English words and has a clean syntax, making the code easy to read
and write. There are no curly braces `{}` or semicolons `;`, which are common in other
languages like Java or C++.
2. Versatility:
- Python is used in various fields, such as web development, data science, artificial
intelligence, machine learning, automation, and more.
- Example: Python can be used to automate repetitive tasks like file management:
import os
for filename in [Link]("."):
if [Link](".txt"):
print("Processing file:", filename)
- This small script lists all `.txt` files in the current directory and prints their names.
3. Large Community and Ecosystem:
- Python has a massive community, which means there are countless libraries and
frameworks available for almost any task.
- Example: For web development, you can use frameworks like Django or Flask:
from flask import Flask
app = Flask(__name__)
@[Link]('/')
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
[Link](debug=True)
- This is a simple web application using Flask, which runs a web server and returns
"Hello, World!" when accessed.
4. Learning Resources:
- Python is beginner-friendly with an abundance of tutorials, books, and courses
available online.
- Example: Platforms like Coursera, Udemy, and Codecademy offer Python courses for
all levels.
5. Industry Adoption:
- Python is widely adopted in industries like tech giants (Google, Facebook), finance
(JPMorgan), healthcare, and more.
- Example: Python is often used for data analysis in finance to predict stock prices or
analyze market trends using libraries like Pandas and NumPy.
Why Is Python Loved?
1. Ease of Learning:
- Python’s syntax is simple and clean, which reduces the learning curve. Even non-
programmers can start coding in Python with minimal effort.
- Example: Calculating the sum of numbers from 1 to 10:
sum(range(1, 11))
The code is intuitive and concise.
2. Strong Community Support:
- Python's large community means that if you face any problems, there’s a high chance
that someone has already solved it, and the solution is available online.
3. Cross-Platform Compatibility:
- Python runs on various platforms, including Windows, macOS, and Linux.
- Example: You can write a Python script on Windows and run it on a Linux server
without modification.
4. Extensive Libraries:
- Python's libraries cater to a wide range of needs, from web development (Django,
Flask) to data science (Pandas, NumPy) to automation (Selenium).
- Example: For machine learning, the Scikit-learn library provides tools to build models
in just a few lines of code:
from sklearn.linear_model import LinearRegression
model = LinearRegression()
[Link](X, y)
5. Rapid Prototyping:
- Python allows developers to quickly prototype ideas, which is particularly useful in
startups or research environments where time is critical.
History and Origin of Python Language
1. Early Development (Late 1980s - Early 1990s)
● Creator: Python was created by Guido van Rossum during the late 1980s
and was first released in 1991.
● Inspiration: Guido was inspired by the ABC language, which was designed
for teaching programming. He wanted to fix the shortcomings of ABC and
add extensibility, allowing users to create more complex programs.
2. Python 1.0 (Released in January 1994)
● Key Features:
○ Functions: Python 1.0 introduced basic features like functions, modules,
and error handling.
Examples:
def greet(name):
return "Hello, " + name
print(greet("Alice"))
3. Python 2.0 (Released in October 2000)
● Major Changes:
○ List Comprehensions: Allowed for the creation of new lists by
applying an expression to each item in an existing list.
○ Garbage Collection: Python 2.0 introduced automatic memory
management.
Examples:
# List comprehension example
numbers = [1, 2, 3, 4]
squares = [n2 for n in numbers]
print(squares) # Output: [1, 4, 9, 16]
4. Python 2.7 (Released in July 2010)
● Significance: This was the last major release of the Python 2.x series.
Python 2.7 extended the life of the Python 2.x series while the Python 3.x
series was still maturing.
Examples:
# Simple print statement in Python 2.7
print "Hello, World!"
5. Python 3.0 (Released in December 2008)
● Major Changes:
○ Print Function: The print statement was replaced with a print()
function.
○ Unicode Support: Python 3 uses Unicode by default, which is
important for supporting international characters.
○ Division: Division of integers now returns a float.
Examples:
# Print function
print("Hello, World!")
# Integer division in Python 3
print(5 / 2) # Output: 2.5
6. Python 3.4 (Released in March 2014)
● Key Features:
○ asyncio Module: Introduced the asyncio library for asynchronous
programming, allowing for better handling of I/O-bound operations.
○ pathlib Module: Provides an object-oriented interface for handling
filesystem paths.
Examples:
# Asynchronous programming using asyncio
import asyncio
async def greet():
print("Hello")
await [Link](1)
print("World")
[Link](greet())
7. Python 3.6 (Released in December 2016)
● Key Features:
○ F-Strings: Introduced f-strings for easier string formatting.
○ Variable Annotations: Introduced syntax for type hints.
Examples:
# Using f-strings for formatting
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
8. Python 3.8 (Released in October 2019)
● Key Features:
○ Assignment Expressions: Also known as the "walrus operator" (:=),
allows assignment inside expressions.
○ Positional-only Arguments: Introduced syntax for specifying
positional-only parameters.
Examples:
# Walrus operator example
numbers = [1, 2, 3, 4, 5]
if (n := len(numbers)) > 3:
print(f"List is too long ({n} elements).")
9. Python 3.10 (Released in October 2021)
● Key Features:
○ Pattern Matching: Introduced structural pattern matching, similar to
switch-case in other languages.
○ Parenthesized Context Managers: Enhanced the use of context
managers.
Examples:
# Pattern matching example
def match_case(x):
match x:
case 1:
return "One"
case 2:
return "Two"
case _:
return "Other"
print(match_case(2)) # Output: Two
10. Python 3.11 (Released in October 2022)
● Key Features:
○ Performance Improvements: Python 3.11 brought significant speed
improvements.
○ Fine-grained Error Locations: Enhanced error messages with more
precise location reporting.
Examples:
# Improved error handling example
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error occurred: {e}")
Features of Python ➖
1. Easy to Learn and Use
● Python has a simple syntax that is easy to understand, making it a great
choice for beginners.
Example:
print("Hello, World!")
● This code prints "Hello, World!" to the screen. The syntax is straightforward
and readable.
2. Interpreted Language
● Python doesn't need to be compiled before running. You can write code and
run it directly.
Example:
x=5
y = 10
print(x + y)
● You can immediately see the result, which is 15.
3. Dynamically Typed
● You don't need to declare the type of variable; Python figures it out for you.
Example:
x=5 # Integer
x = "Hello" # Now it's a string
print(x)
● The variable x can hold different types of data without any problem.
4. Open Source
● Python is free to use, distribute, and modify.
● Example: You can download Python from the official website, use it for
your projects, or even contribute to its development.
5. Extensive Libraries
● Python comes with a rich set of libraries and modules to perform various
tasks without writing much code.
Example:
import math
print([Link](16))
● This code uses the math library to calculate the square root of 16, which is
4.0.
6. Cross-Platform
● Python runs on different operating systems like Windows, macOS, and
Linux.
● Example: Write code on Windows, and it will run on Linux without any
changes.
7. Object-Oriented
● Python supports object-oriented programming, which helps in organizing
code better.
Example:
class Dog:
def __init__(self, name):
[Link] = name
def bark(self):
print(f"{[Link]} says woof!")
my_dog = Dog("Buddy")
my_dog.bark()
● The output will be Buddy says woof!.
8. Readable and Maintainable Code
● Python's syntax promotes readability, making it easier to maintain and
understand.
Example:
if x > 0:
print("Positive")
else:
print("Negative")
● The indentation makes it clear what the code is doing.
9. High-Level Language
● Python handles complex tasks like memory management, allowing you to
focus on the logic of your program.
Example:
numbers = [1, 2, 3, 4, 5]
print(sum(numbers))
● You don’t need to worry about low-level operations.
10. Large Community Support
● Python has a vast community, so if you face any issue, chances are someone
has already solved it.
● Example: There are forums, Stack Overflow, and many other platforms
where you can get help.
11. Portability
● Python code can be easily ported to other platforms without requiring any
changes.
● Example: Write a Python script on macOS, and it will run on Windows.
12. Integrated with Other Languages
● Python can easily integrate with other programming languages like C, C++,
and Java.
Example:
# Example of using a C library in Python
from ctypes import CDLL
libc = CDLL("[Link].6")
[Link](b"Hello from C!\n")
13. Embeddable
● Python can be embedded into applications to provide scripting capabilities.
● Example: You can embed Python in a C++ application to provide a
scripting interface.
14. Support for GUI Programming
● Python has libraries like Tkinter, PyQt, and Kivy to create graphical user
interfaces.
Example:
import tkinter as tk
root = [Link]()
label = [Link](root, text="Hello, Tkinter!")
[Link]()
[Link]()
● This code creates a simple window with the text "Hello, Tkinter!".
15. Support for Web Development
● Python has frameworks like Django and Flask for developing web
applications.
Example:
from flask import Flask
app = Flask(__name__)
@[Link]("/")
def home():
return "Hello, Flask!"
if __name__ == "__main__":
[Link]()
● This code creates a basic web server that returns "Hello, Flask!" when
accessed.
16. Support for Scripting
● Python is often used for writing scripts that automate tasks.
Example:
import os
[Link]("echo 'This is a script!'")
● This script runs a command in the operating system.
17. Fast Prototyping
● Python is great for quickly testing ideas and prototypes.
Example:
def add(a, b):
return a + b
result = add(3, 5)
print(result)
● You can quickly write and test small functions like this.
18. Support for Scientific and Numeric Computing
● Libraries like NumPy, SciPy, and Pandas make Python powerful for
scientific and numeric computing.
Example:
import numpy as np
array = [Link]([1, 2, 3])
print(array * 2)
● This code doubles the values in a NumPy array.
19. Support for Machine Learning and AI
● Python is widely used in AI and machine learning due to libraries like
TensorFlow, PyTorch, and scikit-learn.
Example:
from sklearn.linear_model import LinearRegression
model = LinearRegression()
# Example with data
● Python is often the first choice for machine learning projects.
20. Support for Data Analysis
● Python's libraries like Pandas and Matplotlib make it a strong choice for
data analysis.
Example:
import pandas as pd
data = {'Name': ['John', 'Anna'], 'Age': [28, 24]}
df = [Link](data)
print(df)
● This code creates and displays a simple data table.
21. Extensible
● Python can be extended by adding modules or functions written in other
languages like C.
● Example: You can write a C function and use it in Python for performance-
critical code.
22. Readable
● Python's clear and readable syntax reduces the cost of program
maintenance.
Example:
for i in range(5):
print(i)
● The code is self-explanatory and easy to understand.
23. Concurrency
● Python supports multi-threading and multi-processing, allowing for
concurrent execution of tasks.
Example:
import threading
def print_numbers():
for i in range(5):
print(i)
t = [Link](target=print_numbers)
[Link]()
● This code runs a function in a separate thread.
24. Support for Networking
● Python has libraries for building network applications, such as sockets.
Example:
import socket
s = [Link]()
[Link](("localhost", 8080))
[Link](1)
● This code creates a simple server that listens on port 8080.
25. Simple Syntax
● Python's syntax is clean and straightforward, making it easy to write and
understand code.
Example:
for item in [1, 2, 3]:
print(item)
● The syntax is simple and resembles plain English, making it intuitive.
Limitations of Python ➖
1. Speed
● Limitation: Python is slower than compiled languages like C or Java because
it is an interpreted language. This means that Python code is executed line
by line, which can slow down performance, especially for computationally
intensive tasks.
Example:
import time
start = [Link]()
for i in range(10000000):
pass
end = [Link]()
print("Time taken:", end - start)
In Python, this loop takes more time to execute compared to the same loop written
in C.
2. Memory Consumption
● Limitation: Python uses more memory compared to languages like C or
Java. This is partly due to Python's dynamic typing, which requires more
memory to manage.
Example:
large_list = [i for i in range(1000000)]
print(f"Memory used by large list: {large_list.__sizeof__()} bytes")
A list of 1 million integers can consume a significant amount of memory.
4. Weak in Mobile Computing
● Limitation: Python is not commonly used for mobile app development.
Languages like Java, Swift, or Kotlin are more popular for this purpose.
● Example:
○ While you can use Python for mobile apps with frameworks like
Kivy, it's not the preferred choice due to performance and
compatibility issues.
5. Runtime Errors
● Limitation: Python is dynamically typed, which means errors can occur at
runtime if the code is not properly tested. This can lead to unexpected bugs.
Example:
def add(a, b):
return a + b
result = add(5, "10")
This code will cause a runtime error because Python doesn't check types until the
code is executed.
6. Limited in Mobile Computing and Browsers
● Limitation: Python is not natively supported by web browsers, so you can't
use Python directly for client-side web development (like you can with
JavaScript).
● Example:
○ You can't write Python code to directly run in a user's browser;
JavaScript or WebAssembly is needed instead.
7. Database Access Layers Are Not as Robust
● Limitation: Python's database access layers are not as strong as those in
Java's JDBC or C#'s [Link]. While libraries like SQLAlchemy and
Django ORM are popular, they can be slower and less powerful.
Example:
import sqlite3
conn = [Link]('[Link]')
c = [Link]()
[Link]('''CREATE TABLE IF NOT EXISTS students (name text,
age integer)''')
[Link]()
[Link]()
Python works fine with databases, but for large-scale systems, other languages may
offer better performance and features.
8. Not Ideal for Low-Level Programming
● Limitation: Python is not suitable for low-level programming tasks like
operating system development or writing device drivers, where languages
like C or C++ are better suited.
● Example:
○ Python is too high-level to interact directly with hardware, making it
unsuitable for tasks like writing a new file system or a new kernel
module.
9. Lack of True Multiprocessing Support
● Limitation: While Python provides the multiprocessing module, the GIL still
limits the efficiency of parallel execution, especially for CPU-bound tasks.
10. Error Handling and Testing
● Limitation: Python's dynamic typing can make it harder to catch errors at
compile time, requiring more extensive testing to ensure code quality.
Example:
def greet(name):
return "Hello, " + name
print(greet(123))
This will not raise an error until runtime, where it might cause unexpected
behavior.
Major Applications of Python ➖
1. Web Development
● Explanation: Python is widely used for building websites and web
applications.
● Frameworks: Django, Flask.
● Examples: Instagram (Django), Pinterest (Django), Flask (simple web apps).
2. Data Science
● Explanation: Python helps in analyzing and visualizing data.
● Libraries: Pandas, NumPy, Matplotlib.
● Examples: Analyzing sales data to find trends, visualizing survey results.
3. Machine Learning
● Explanation: Python is used to create systems that learn from data.
● Libraries: Scikit-learn, TensorFlow, Keras.
● Examples: Email spam filters, product recommendations (like Amazon),
self-driving cars.
4. Artificial Intelligence
● Explanation: Python is used to develop intelligent systems.
● Libraries: PyTorch, OpenAI Gym.
● Examples: Chatbots (like Siri or Alexa), facial recognition systems,
autonomous drones.
5. Automation/Scripting
● Explanation: Python automates repetitive tasks, saving time.
● Libraries: Selenium, Automate the Boring Stuff.
● Examples: Renaming files in bulk, filling online forms automatically,
scraping data from websites.
6. Web Scraping
● Explanation: Python is used to extract data from websites.
● Libraries: BeautifulSoup, Scrapy.
● Examples: Collecting product prices from e-commerce sites, gathering job
listings, extracting news articles.
7. Game Development
● Explanation: Python is used to create simple games.
● Libraries: Pygame.
● Examples: Developing 2D games like Snake, Tetris, or platformers.
8. Desktop GUI Applications
● Explanation: Python can build desktop applications with graphical user
interfaces (GUIs).
● Libraries: Tkinter, PyQt.
● Examples: Simple text editors, calculators, and to-do list applications.
9. Scientific Computing
● Explanation: Python is used for complex scientific computations.
● Libraries: SciPy, NumPy.
● Examples: Simulating physics experiments, solving mathematical equations,
analyzing chemical data.
10. Networking
● Explanation: Python can be used to manage and configure networks.
● Libraries: Scapy, Twisted.
● Examples: Creating custom network protocols, automating network tasks,
building simple network servers.
11. Embedded Systems
● Explanation: Python can run on tiny devices and control hardware.
● Libraries: MicroPython, CircuitPython.
● Examples: Programming microcontrollers for home automation, IoT devices
like smart thermostats.
12. Cloud Computing
● Explanation: Python is used to interact with cloud services.
● Libraries: Boto3 (for AWS), Google Cloud Python Client.
● Examples: Managing cloud storage, automating cloud resource management,
deploying machine learning models on the cloud.
13. Robotics
● Explanation: Python is used to program robots.
● Libraries: ROS (Robot Operating System), PyRobot.
● Examples: Controlling robot arms, programming drones, building
autonomous robots for competitions.
14. Audio and Video Applications
● Explanation: Python can process audio and video files.
● Libraries: OpenCV, PyDub.
● Examples: Editing video files, converting audio formats, creating video
players.
15. Education
● Explanation: Python is popular for teaching programming.
● Examples: Python is often the first language taught in schools and
universities due to its simplicity. It’s used in courses like “Introduction to
Programming” and “Data Science 101.”
16. Image Processing
● Explanation: Python is used to manipulate and analyze images.
● Libraries: OpenCV, PIL (Pillow).
● Examples: Face detection, image enhancement, converting images between
formats.
17. Business Applications
● Explanation: Python helps build business-oriented software.
● Examples: ERP (Enterprise Resource Planning) systems, e-commerce
platforms, inventory management systems.
18. Finance
● Explanation: Python is used in financial services for analyzing data,
modeling financial systems, and trading.
● Libraries: QuantLib, PyAlgoTrade.
● Examples: Stock market analysis, financial predictions, automated trading
systems.
19. Cybersecurity
● Explanation: Python is used to develop security tools.
● Libraries: PyCrypto, Paramiko.
● Examples: Writing penetration testing tools, automating security checks,
analyzing network security.
20. Blockchain
● Explanation: Python is used in developing blockchain technologies and
cryptocurrencies.
● Libraries: [Link].
● Examples: Developing smart contracts, creating cryptocurrency wallets,
building blockchain networks.
Getting Python
Python is a popular programming language used for web development, data
analysis, artificial intelligence, and more. To start programming in Python, you
need to have Python installed on your computer.
2. Installing Python
1. Visit the Python website: Go to [Link] and download the latest version
of Python.
2. Run the installer: Open the downloaded file. During installation, ensure you
check the box that says "Add Python to PATH" (this is important for the
next steps).
3. Complete installation: Follow the on-screen instructions to complete the
installation.
3. Setting Up Path and Environment Variables
When you check the "Add Python to PATH" box during installation, Python
automatically adds its location to your system's PATH environment variable. This
allows you to run Python from the command line anywhere on your computer.
If you forgot to check the box during installation, you can manually add Python to
your PATH:
1. Find the installation path: Locate the folder where Python is installed (e.g.,
C:\Python39\ on Windows).
2. Add to PATH:
○ On Windows:
1. Search for "Environment Variables" in the Start menu.
2. Click "Environment Variables".
3. Under "System variables", find the Path variable and click
"Edit".
4. Add the Python installation path to the list.
○ On Mac/Linux:
1. Open the terminal.
2. Edit the .bash_profile, .bashrc, or .zshrc file.
3. Add the line: export PATH="/path/to/python:$PATH".
4. Save the file and run source ~/.bash_profile (or equivalent).
4. Running Python
Once Python is installed and added to your PATH, you can run Python scripts or
use the Python interpreter directly from the command line.
Example 1: Running Python in the Command Line (Interactive Mode)
1. Open your command line (Command Prompt on Windows, Terminal on
Mac/Linux).
2. Type python (or python3 on some systems) and press Enter.
Python 3.9.1 (default, Dec 8 2020, [Link])
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more
information.
>>>
3. This is the Python interactive shell where you can type Python commands
and see the results immediately.
Example 2: Running a Python Script
1. Create a Python script file with a .py extension, for example, [Link].
Inside [Link], write a simple Python program:
print("Hello, World!")
2. Save the file.
Run the script from the command line by typing:
python [Link]
You should see the output:
Hello, World!
5. First Python Program
Let's create and run your first Python program step by step.
Example: Creating a Simple Python Program
1. Open a text editor (like Notepad, VS Code, or any IDE).
Type the following code:
print("Welcome to Python programming!")
2. Save the file as [Link].
Run it from the command line:
python [Link]
The output will be:
Welcome to Python programming!
Example: A Simple Calculator Program
# Simple Python program to add two numbers
# Input from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Adding the numbers
sum = num1 + num2
# Display the result
print("The sum is:", sum)
● Explanation:
○ input() is used to get user input.
○ float() converts the input to a floating-point number.
○ The two numbers are added, and the result is stored in sum.
○ print() displays the result.
Running the Calculator Program
1. Save this code as [Link].
Run it from the command line: python [Link]
2. Follow the prompts to enter two numbers, and it will display their sum.
Python Interactive Help Feature
Python provides an interactive help feature that allows users to get help directly
from the Python interpreter. This feature is extremely useful for beginners and
even experienced programmers who need quick information about Python
commands, functions, modules, or any other topic.
Example 1: Starting the Help System
You can start the help system in the Python interactive shell by simply typing:
help()
When you run this, Python will enter its help mode, where you can type the name
of a module, keyword, or topic you want help with.
Example 2: Getting Help on a Specific Function
If you want to know more about a specific function like print, you can directly ask
for help:
help(print)
This command will display a detailed description of how the print function works,
including its parameters and usage examples.
Example 3: Help on Modules
You can also get help on an entire module by passing the module name:
import math
help(math)
This will display all the functions and constants available in the math module.
Example 4: Exiting the Help System
To exit the help mode, you can simply type:
quit
or press Ctrl + D.
Python differences from other languages
Feature/ JavaScr
Language Python C++ Java ipt
Uses Uses
braces {} braces {}
Simple and Uses braces and and
readable; uses {} to define semicolons semicolon
Syntax indentation blocks ; s;
No
Requires explicit
Requires explicit type
No need to explicit type type declaratio
Variable declare variable declaration declaration n (e.g., let
Declaration type (e.g., int x) (e.g., int x) x)
Manual
memory
Automatic management Automatic Automatic
Memory garbage using new garbage garbage
Management collection and delete collection collection
Strongly Supports
Supports supports OOP but
Supports OOP OOP with OOP with is
with classes classes and classes and prototype-
Object-Oriented and objects objects objects based
Uses try, Uses try,
Uses try, catch, catch, Uses try,
Error Handling except, finally finally finally catch
Uses return Uses return
type and type and Uses
Function function function function
Definition def keyword name name keyword
[Link]
std::cout << .println("H [Link]
Print Statement print("Hello") "Hello" ello") g("Hello")
str1 + str2 str1 + str2
String (using (using
Concatenation str1 + str2 std::string) String) str1 + str2
int arr[] = int[] arr = let arr =
List/Array list = [1, 2, 3] {1, 2, 3} {1, 2, 3} [1, 2, 3]
Yes,
variables
No, types No, types can
Yes, variables are static are static change
can change and must be and must type at
Dynamic Typing type at runtime declared be declared runtime
Keywords
Keywords are reserved words in Python that have a special meaning and cannot be
used for anything other than their intended purpose. These words are predefined in
the language and are essential to its syntax.
Examples of Keywords:
● def: Used to define a function.
● if: Used for conditional statements.
● for: Used to create loops.
● import: Used to include external modules.
Example:
def greet(name): # 'def' is a keyword used to define a function
if name: # 'if' is a keyword used for conditional statements
print(f"Hello, {name}!") # 'print' is a built-in function, not a
keyword
else:
print("Hello, World!")
2. Identifiers
Identifiers are names given to various program elements such as variables,
functions, and classes. An identifier can be any combination of letters, digits, and
underscores but must start with a letter or an underscore.
Rules for Identifiers:
● Must start with a letter (a-z, A-Z) or an underscore (_).
● Can contain letters, digits (0-9), and underscores.
● Must not be a Python keyword.
● Identifiers are case-sensitive.
Examples of Identifiers:
● my_variable
● totalAmount
● _hiddenValue
● calculate_sum
Example:
my_variable = 10 # 'my_variable' is an identifier
totalAmount = 20 # 'totalAmount' is another identifier
def add(a, b): # 'add' is an identifier for the function name
return a + b
result = add(my_variable, totalAmount) # 'result' is an identifier for
storing the result
print(result)
3. Python Statement
A statement in Python is a line of code that performs a specific action. Statements
are the building blocks of a Python program and can be simple or compound.
Types of Statements:
Assignment Statements: Assign values to variables.
x = 5 # 'x = 5' is an assignment statement
Expression Statements: Evaluate expressions.
print(x + 10) # 'print(x + 10)' is an expression statement
Control Flow Statements: Control the flow of the program.
if x > 10: # 'if x > 10' is a control flow statement
print("x is greater than 10")
Function Call Statements: Call functions.
result = add(x, 10) # 'result = add(x, 10)' is a function call statement
Example:
# Assignment Statement
name = "Alice"
# Function Call Statement
print("Hello, " + name + "!") # 'print("Hello, " + name + "!")' is a
function call statement
# Control Flow Statement
if name == "Alice":
print("Welcome, Alice!")
else:
print("Who are you?")
In summary:
● Keywords are predefined reserved words.
● Identifiers are names you choose for variables, functions, etc.
● Statements are lines of code that perform actions.
Indentation
Definition: Indentation refers to the spaces or tabs at the beginning of a line of
code. Python uses indentation to define the structure of the code, especially for
blocks of code that belong together, like in loops or conditionals.
Why it’s important: Indentation makes the code readable and helps Python
understand which statements are part of the same block.
Example:
# Without indentation, this code will raise an error
if True:
print("Hello, World!") # This line should be indented
# Correct indentation
if True:
print("Hello, World!") # This line is indented correctly
In this example, print("Hello, World!") is part of the if block because it is indented.
If it wasn’t indented, Python would not understand that it belongs to the if
statement.
Documentation
Definition: Documentation in Python refers to comments and docstrings that
explain what the code does. This helps others (and yourself) understand the code
later on.
Comments:
● Single-line comments: Begin with #.
● Multi-line comments: Enclosed in triple quotes (''' or """).
Example:
# This is a single-line comment
"""
This is a multi-line comment.
It can span multiple lines.
"""
# Function to add two numbers
def add_numbers(a, b):
"""
This function takes two numbers and returns their sum.
"""
return a + b
In this example, comments explain what each part of the code does. The docstring
inside the function provides a description of what the function does.
Variables
Definition: Variables are used to store data that can be used and manipulated in
your program. They are essentially placeholders for data.
Example:
# Declaring variables
name = "Alice" # Variable 'name' stores a string
age = 25 # Variable 'age' stores an integer
# Using variables
print(name) # Outputs: Alice
print(age) # Outputs: 25
In this example, name and age are variables storing the values "Alice" and 25,
respectively.
Multiple Assignment
Definition: Multiple assignment allows you to assign values to multiple variables
in a single line.
Example:
# Multiple assignment
x, y, z = 10, 20, 30
print(x) # Outputs: 10
print(y) # Outputs: 20
print(z) # Outputs: 30
In this example, x, y, and z are assigned the values 10, 20, and 30 in one line.
Another Example:
# Swapping values using multiple assignment
a, b = 5, 8
a, b = b, a
print(a) # Outputs: 8
print(b) # Outputs: 5
In this example, the values of a and b are swapped using multiple assignment.
Data Types in Python
In Python, data types refer to the kind of data that a variable can hold. Here are
some common data types:
1. Integer (int): Whole numbers.
○ Example: x = 5
2. Float (float): Numbers with decimal points.
○ Example: y = 3.14
3. String (str): Text or a sequence of characters enclosed in quotes.
○ Example: name = "Alice"
4. Boolean (bool): Represents True or False.
○ Example: is_student = True
5. List (list): An ordered collection of items, which can be of different types.
○ Example: numbers = [1, 2, 3, 4]
6. Tuple (tuple): Similar to lists but immutable (cannot be changed).
○ Example: coordinates = (10, 20)
7. Dictionary (dict): A collection of key-value pairs.
○ Example: student = {"name": "John", "age": 21}
Data Type Conversion
Sometimes, you need to convert one data type into another. Here are some
common conversions:
Integer to Float:
x=5
y = float(x) # y is now 5.0
Float to Integer:
x = 3.14
y = int(x) # y is now 3 (note that it truncates the decimal part)
String to Integer:
x = "10"
y = int(x) # y is now 10
Integer to String:
x=5
y = str(x) # y is now "5"
String to Float:
x = "3.14"
y = float(x) # y is now 3.14
When programming in Python, you might need to convert one data type into
another. This process is called data type conversion, and it can happen in two
ways: implicit conversion and explicit conversion.
1. Implicit Conversion
Implicit conversion happens automatically when Python converts one data type to
another without you explicitly telling it to do so. This usually occurs when you're
working with operations that involve different data types, and Python handles the
conversion for you.
Example:
x = 10 # Integer
y = 3.5 # Float
# Adding an integer and a float
z = x + y # Python automatically converts the integer 'x' to float and adds it to 'y'
print(z) # Output: 13.5 (a float)
In this example, Python automatically converts x (an integer) to a float so it can be
added to y (a float). This is an implicit conversion because Python does it on its
own.
2. Explicit Conversion
Explicit conversion happens when you manually convert a data type into another
using functions like int(), float(), str(), etc. This is also known as type casting.
Example:
# Integer to Float (Explicit Conversion)
x = 10 # Integer
y = float(x) # Manually converting x to float
print(y) # Output: 10.0 (a float)
# String to Integer (Explicit Conversion)
a = "20" # String
b = int(a) # Manually converting a to an integer
print(b) # Output: 20 (an integer)
In this example, you're explicitly telling Python to convert x (an integer) to a float
using float(x), and a (a string) to an integer using int(a).
Key Differences:
● Implicit Conversion: Done automatically by Python. You don't have to write
extra code.
● Explicit Conversion: Done manually by you. You must use specific
functions to convert data types.
Input and Output Functions
Input Function (input()): Used to take user input as a string.
name = input("Enter your name: ")
print("Hello, " + name)
Output Function (print()): Used to display data on the screen.
age = 21
print("You are", age, "years old.")
You can also use f-strings (formatted string literals) for a more readable way to
format strings:
print(f"You are {age} years old.")
Import Command
The import command is used to include external Python modules (libraries) into
your script, so you can use their functions and classes.
Importing an entire module:
import math
print([Link](16)) # prints 4.0, the square root of 16
Importing specific functions from a module:
from math import sqrt
print(sqrt(16)) # prints 4.0
Importing with an alias:
import numpy as np
array = [Link]([1, 2, 3])
print(array)
Python Operators:-
Refer this link -
[Link]
ors-of-python
Operators are symbols that perform operations on variables and values. Python
supports various types of operators:
● Arithmetic Operators: +, -, *, /, %, , //
Addition (+): Adds two values.
python
5 + 3 # Output: 8
○
Subtraction (-): Subtracts the second value from the first.
python
10 - 4 # Output: 6
Multiplication (*): Multiplies two values.
python
6 * 7 # Output: 42
Division (/): Divides the first value by the second.
python
20 / 4 # Output: 5.0
Modulus (%): Returns the remainder of division.
python
29 % 5 # Output: 4
Exponentiation (): Raises the first value to the power of the second.
python
2 3 # Output: 8
Floor Division (//): Divides and rounds down to the nearest integer.
python
7 // 2 # Output: 3
○
● Comparison Operators: ==, !=, >, <, >=, <=
Equal to (==): Checks if two values are equal.
python
5 == 5 # Output: True
Not equal to (!=): Checks if two values are not equal.
python
5 != 3 # Output: True
Greater than (>): Checks if the first value is greater than the second.
python
10 > 3 # Output: True
Less than (<): Checks if the first value is less than the second.
python
2 < 5 # Output: True
Greater than or equal to (>=): Checks if the first value is greater than or equal to
the second.
python
5 >= 5 # Output: True
○
Less than or equal to (<=): Checks if the first value is less than or equal to the
second.
python
4 <= 6 # Output: True
○
● Logical Operators: and, or, not
Logical AND (and): Returns True if both conditions are true.
python
True and False # Output: False
Logical OR (or): Returns True if at least one condition is true.
python
True or False # Output: True
Logical NOT (not): Returns the opposite of the condition.
python
not True # Output: False
○
● Assignment Operators: =, +=, -=, *=, /=, %=...
Assignment (=): Assigns a value to a variable.
python
x=5
○
Add and assign (+=): Adds and assigns.
python
x += 3 # x is now 8
○
● Identity Operators: is, is not
is: Checks if two variables point to the same object.
python
a = [1, 2]
b = [1, 2]
a is b # Output: False (they are different objects)
is not: Checks if two variables point to different objects.
python
a is not b # Output: True
○
● Membership Operators: in, not in
in: Checks if a value is in a sequence.
python
3 in [1, 2, 3] # Output: True
not in: Checks if a value is not in a sequence.
python
4 not in [1, 2, 3] # Output: True
○
2. Expressions
An expression is a combination of variables, constants, operators, and functions
that evaluates to a value.
python
x=5
y = 10
result = x * y + 3 # Expression: x * y + 3
3. Precedence
Operator precedence determines the order in which operators are evaluated in an
expression. Higher precedence operators are evaluated first.
● Parentheses () - Highest precedence
● Exponentiation
● Unary plus and minus +x, -x
● Multiplication, Division, Floor Division, Modulus *, /, //, %
● Addition, Subtraction +, -
● Comparison Operators ==, !=, >, <, >=, <=
● Logical NOT not
● Logical AND and
● Logical OR or
Example:
python
result = 2 + 3 * 4 # Output: 14 (Multiplication is done before addition)
4. Associativity of Operators
Associativity defines the direction in which operators of the same precedence are
evaluated.
Left-to-Right (most operators like +, -, *, /, %, ==, !=):
python
5 - 3 - 1 # Evaluated as (5 - 3) - 1 = 1
Right-to-Left (exponentiation ):
python
2 3 2 # Evaluated as 2 (3 2) = 2 9 = 512
5. Non-Associative Operators
Non-associative operators do not have a defined direction of evaluation. For
example, comparison operators are non-associative:
python
# Comparison operators are generally used in chains
result = 1 < 2 < 3 # Output: True (equivalent to (1 < 2) and (2 < 3))
In summary:
● Operators perform operations on values.
● Expressions are combinations of values and operators.
● Precedence determines the order of operations.
● Associativity defines how operators of the same precedence are grouped.
● Non-associative operators do not have a clear direction of evaluation.
UNIT- II
Control Structures
Decision Making Statements
Control structures in Python into three main categories:
1. Decision-Making Statements
2. Loops
3. Control Statements
1. Decision-Making Statements
Decision-making statements allow your program to choose different paths based
on certain conditions. The primary decision-making statements in Python are if,
if-else, and if-elif-else.
a. if Statement
The if statement lets you execute a block of code only if a specific condition is
true.
Syntax:
if condition:
# code to execute if condition is true
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")
Output:
You are eligible to vote.
b. if-else Statement
The if-else statement provides two paths: one if the condition is true and another if
it's false.
Syntax:
if condition:
# code if condition is true
else:
# code if condition is false
Example:
temperature = 30
if temperature > 25:
print("It's a hot day.")
else:
print("It's not a hot day.")
Output:
It's a hot day.
c. if-elif-else Statement
When you have multiple conditions to check, you can use elif (short for "else
if") to handle additional cases.
Syntax:
if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
elif condition3:
# code if condition3 is true
else:
# code if none of the above conditions are true
Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
Output:
Grade: B
2. Loops
Loops allow you to execute a block of code multiple times. Python has two
primary loop types: for loops and while loops.
a. for Loop
A for loop is used to iterate over a sequence (like a list, tuple, string, or range).
Syntax:
for item in sequence:
# code to execute for each item
Examples:
Iterating Over a List:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
1.
Using range() Function:
for i in range(5):
print(i)
Output:
2. Iterating Over a String:
for char in "Hello":
print(char)
Output:
b. while Loop
A while loop repeatedly executes a block of code as long as a condition is true.
Syntax:
while condition:
# code to execute repeatedly
Example:
count = 1
while count <= 5:
print(count)
count += 1 # Equivalent to count = count + 1
Output: `` 1 2 3 4 5
3. Control Statements
Control statements alter the flow of loops. The primary control statements in
Python are `break`, `continue`, and `pass`.
a. `break` Statement
The `break` statement exits the nearest enclosing loop immediately.
Example:
for number in range(1, 10):
if number == 5:
break
print(number)
Output:
Explanation: The loop stops when number equals 5.
b. continue Statement
The continue statement skips the rest of the code inside the loop for the current
iteration and moves to the next iteration.
Example:
for number in range(1, 6):
if number == 3:
continue
print(number)
Output:
Explanation: When number is 3, continue skips the print statement.
c. pass Statement
The pass statement does nothing. It's used as a placeholder when a statement is
syntactically required but no action is needed.
Example:
for number in range(1, 6):
if number == 3:
pass # Placeholder for future code
print(number)
Output:
Explanation: When number is 3, pass does nothing, and the loop continues
normally.
Another Example: Defining Empty Functions or Classes:def
my_function():
pass # Function to be implemented later
class MyClass:
pass # Class to be implemented later
Putting It All Together: A Comprehensive Example
Let's create a simple program that uses decision-making statements, loops, and
control statements.
Task: Print numbers from 1 to 10. For each number:
● If it's divisible by 2, print "Even".
● If it's divisible by 3, skip printing the number.
● Stop the loop if the number is greater than 8.
Code:
for number in range(1, 11):
if number > 8:
break # Stop the loop if number is greater
than 8
if number % 3 == 0:
continue # Skip the rest of the loop if number
is divisible by 3
print(number)
if number % 2 == 0:
print("Even")
Output:
Even
Even
6 # Skipped because 6 is divisible by 3
7
8
Even
Note: Numbers 3, 6, and 9 are skipped because they are divisible by 3. The loop
stops before reaching 9 due to the break statement when number > 8.
Summary
● Decision-Making Statements (if, if-else, if-elif-else): Let your program
make choices based on conditions.
● Loops (for, while): Allow your program to execute code repeatedly.
● Control Statements (break, continue, pass): Modify the flow of loops by
exiting them, skipping iterations, or acting as placeholders.
Python Native Data Types
Python Numbers
There are three numeric types in Python:
● int
● float
● complex
Variables of numeric types are created when you assign a value to them:
x=1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative, containing
one or more decimals.
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Random Number
Python does not have a random() function to make a random number, but
Python has a built-in module called random that can be used to make random
numbers:
Import the random module, and display a random number between 1 and 9:
import random
print([Link](1, 10))
Python Strings
A string is a sequence of characters enclosed within quotes. You can use single ('),
double ("), or triple quotes (''' or """) to create strings.
Examples:
string1 = 'Hello'
string2 = "World"
string3 = '''Python is fun!'''
print(string1)
print(string2)
print(string3)
Output:
Hello
World
Python is fun!
2. Slicing Strings
Slicing allows you to extract a part of a string. You can use string[start:end] to
slice from the start index to the end index (not including the end index).
Examples:
text = "Python Programming"
slice1 = text[0:6] # 'Python'
slice2 = text[7:] # 'Programming'
slice3 = text[-11:-1] # 'Programmin' (last character not included)
print(slice1)
print(slice2)
print(slice3)
Output:
Python
Programming
Programmin
3. Modify Strings
Strings are immutable, meaning you cannot change a part of the string directly.
However, you can create a new string based on modifications.
Example:
text = "Hello"
modified_text = [Link]('H', 'J') # 'Jello'
print(modified_text)
Output:
Jello
4. Concatenate Strings
Concatenation is the process of joining two or more strings together using the +
operator.
Examples:
greeting = "Hello"
name = "Alice"
full_greeting = greeting + ", " + name + "!"
print(full_greeting)
Output:
Hello, Alice!
5. Format Strings
Formatting allows you to insert values into a string. The format() method or f-
strings (f"...") can be used for this purpose.
Examples:
age = 25
message = "I am {} years old.".format(age) # Using format()
print(message)
name = "Bob"
message = f"My name is {name}." # Using f-string
print(message)
Output:
I am 25 years old.
My name is Bob.
6. Escape Characters
Escape characters allow you to include special characters in a string. They start
with a backslash (\).
Common Escape Characters:
● \n: Newline
● \t: Tab
● \': Single quote
● \": Double quote
● \\: Backslash
Examples:
text = "She said, \"Hello!\"\nHow are you?"
print(text)
Output:
She said, "Hello!"
How are you?
7. String Methods
Python provides several built-in methods to work with strings.
Examples:
text = "hello world"
print([Link]()) # 'HELLO WORLD'
print([Link]()) # 'Hello world'
print([Link]()) # ['hello', 'world']
print([Link]('world')) # 6 (index of 'world')
print([Link]('world', 'Python')) # 'hello Python'
Output:
HELLO WORLD
Hello world
['hello', 'world']
hello Python
capitalize Converts the first character to upper case
()
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith( Returns true if the string ends with the specified value
)
expandtab Sets the tab size of the string
s()
find() Searches the string for a specified value and returns the position
of where it was found
format() Formats specified values in a string
format_m Formats specified values in a string
ap()
index() Searches the string for a specified value and returns the position
of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal Returns True if all characters in the string are decimals
()
isdigit() Returns True if all characters in the string are digits
isidentifie Returns True if the string is an identifier
r()
islower() Returns True if all characters in the string are lower case
isnumeric Returns True if all characters in the string are numeric
()
isprintabl Returns True if all characters in the string are printable
e()
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans Returns a translation table to be used in translations
()
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a
specified value
rfind() Searches the string for a specified value and returns the last
position of where it was found
rindex() Searches the string for a specified value and returns the last
position of where it was found
rjust() Returns a right justified version of the string
rpartition( Returns a tuple where the string is parted into three parts
)
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines( Splits the string at line breaks and returns a list
)
startswith Returns true if the string starts with the specified value
()
strip() Returns a trimmed version of the string
swapcase( Swaps cases, lower case becomes upper case and vice versa
)
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the
beginning
Python Lists
mylist = ["apple", "banana", "cherry"]
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
Example:
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1]
etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order,
and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the
order of the items will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
List Items - Data Types
List items can be of any data type:
Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
A list can contain different data types:
Example
A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
The list() Constructor
It is also possible to use the list() constructor when creating a new list.
Example
Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
Python Collections (Arrays)
There are four collection data types in the Python programming language:
List is a collection which is ordered and changeable. Allows duplicate
members.
Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
Set is a collection which is unordered, unchangeable*, and unindexed.
No duplicate members.
Dictionary is a collection which is ordered and changeable. No
duplicate members.
[Link]
UNIT -3
Python Functions
Functions in Python are blocks of code that perform a specific task. They
help in breaking down large problems into smaller chunks and promote code
reuse.
Advantages of Functions:
- Code Reusability: Functions allow you to reuse code, so you don’t have to
write the same logic again.
- Modularity: Functions help in dividing the program into smaller modules or
sections, which makes the code easier to understand.
- Maintainability: Changes can be made easily, and debugging becomes more
manageable.
- Code Organization: Functions make the code cleaner and more organized.
Types of Functions:
1. Built-in Functions: These are functions that come pre-built with
Python.
- Example:
# Example of built-in functions
print(len("Hello")) # Returns length of a string
print(max(1, 5, 9)) # Returns the maximum value
2. User-defined Functions: Functions that are defined by the user
to perform specific tasks.
- Example:
# Example of a user-defined function
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
3. Anonymous Functions (Lambda Functions): These
are small functions without a name, defined using the `lambda` keyword.
- Example:
# Example of a lambda function
square = lambda x: x * x
print(square(5)) # Output: 25
Pass by Value vs. Pass by Reference:
- Pass by Value: In Python, everything is passed by reference, but
immutable objects (like numbers, strings) behave like pass by value.
- Example:
def change_value(x):
x = 10
print("Inside function:", x)
y=5
change_value(y)
print("Outside function:", y) # Output: 5 (unchanged outside)
- Pass by Reference: Mutable objects (like lists) behave like pass by
reference, meaning changes inside a function affect the original object.
- Example:
def change_list(lst):
[Link](4)
print("Inside function:", lst)
my_list = [1, 2, 3]
change_list(my_list)
print("Outside function:", my_list) # Output: [1, 2, 3, 4]
Recursion:
- Recursion is when a function calls itself to solve a smaller part of the
problem.
- Example:
# Factorial using recursion
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Scope and Lifetime of Variables:
- Local Scope: Variables defined inside a function are only accessible
within that function.
- Global Scope: Variables defined outside all functions are accessible
anywhere in the code.
- Example:
x = 10 # Global variable
def my_function():
y = 5 # Local variable
print("Inside function:", y)
my_function()
print("Outside function:", x) # Output: 10
---
Python Modules
A module is a file containing Python code, typically functions, classes, and
variables, that you can reuse in other Python scripts.
Need of Modules:
- Modularity: Organizing code into modules helps break down the program
into manageable sections.
- Code Reusability: Modules allow us to use the same code in multiple
programs by importing them.
- Namespace Management: Modules help prevent conflicts between function
or variable names by keeping them in separate namespaces.
Creating and Importing a Module:
- A Python module is just a Python file (with a `.py` extension).
Example: Create a module called `[Link]`:
# [Link]
def greet(name):
return f"Hello, {name}!"
Now, in another Python file, you can import and
use this module:
# importing the module
import mymodule
print([Link]("Alice")) # Output: Hello, Alice!
Path Searching of a Module:
- When you import a module, Python searches for the module in the
following locations:
1. The current directory.
2. Directories listed in `PYTHONPATH` environment variable.
3. Standard directories (like the Python installation folder).
You can view the module search paths with:
import sys
print([Link])
Module Reloading:
- If you modify a module after importing it, you need to reload it to see the
changes using the `[Link]()` function.
import mymodule
import importlib
[Link](mymodule) # Reloads the module to reflect changes
Standard Modules:
- Python comes with many standard modules like `math`, `datetime`,
`random`, etc., that can be used in your code.
- Example:
import math
print([Link](16)) # Output: 4.0
Python Packages:
- A package is a collection of modules. It's simply a directory containing a
special `__init__.py` file.
Example:
Let's say we have the following structure:
mypackage/
__init__.py
[Link]
[Link]
You can import modules from this package:
from mypackage import module1
---
Summary:
- Functions help organize code and perform tasks.
- Types: Built-in, User-defined, Anonymous.
- Key Concepts: Pass by value/reference, Recursion, Scope of variables.
- Modules organize code into separate files, making it reusable and modular.
- Creating, importing, reloading, and path searching are key components.
- Packages are directories that contain multiple modules for larger projects.
Different Types of User-Defined Functions in
Python
User-defined functions in Python are created by the user to perform specific
tasks and can be classified based on the following aspects:
1. Functions Without Parameters and Without
Return Value:
- These functions don’t take any input (no parameters) and don’t return any
output (no return value). They just perform an action.
- Example:
def greet():
print("Hello, Welcome to Python!")
greet() # Output: Hello, Welcome to Python!
2. Functions With Parameters and Without Return
Value:
- These functions take input (parameters) but do not return any value. They
perform an action using the passed parameters.
- Example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
3. Functions Without Parameters and With Return
Value:
- These functions don’t take any input but return some value after
performing the task.
- Example:
def get_welcome_message():
return "Hello, Welcome to Python!"
message = get_welcome_message()
print(message) # Output: Hello, Welcome to Python!
4. Functions With Parameters and With Return
Value:
- These functions take input (parameters) and also return a value after
performing the task.
- Example:
def add_numbers(a, b):
return a + b
result = add_numbers(5, 10)
print(result) # Output: 15
5. Functions with Default Parameters:
- These functions have parameters with default values, so if no argument is
passed for that parameter, it uses the default value.
- Example:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
6. Functions with Variable-length Arguments:
- These functions can accept a variable number of arguments. Python
provides two ways to handle variable-length arguments: `*args` (for
positional arguments) and `kwargs` (for keyword arguments).
- Using `*args` (for a variable number of positional arguments):
def sum_all(*numbers):
total = sum(numbers)
return total
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(4, 5, 6, 7, 8)) # Output: 30
- Using `kwargs` (for a variable number of
keyword arguments):
def print_info(details):
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")
# Output:
# name: Alice
# age: 25
# city: New York
---
Arguments and Parameters in Functions
Parameters and Arguments are closely related concepts in functions, but they
refer to different things.
# Parameters:
- Parameters are variables defined in the function declaration.
- They act as placeholders for the values (arguments) that the function
expects when it is called.
- Example:
def greet(name): # 'name' is a parameter
print(f"Hello, {name}!")
# Arguments:
- Arguments are the actual values that are passed to the function when it is
called.
- These values replace the parameters during function execution.
- Example:
greet("Alice") # 'Alice' is an argument
# Types of Arguments:
1. Positional Arguments:
- These are passed to a function based on the position in which the
parameters are defined.
- Example:
def add(a, b):
return a + b
print(add(5, 10)) # Output: 15 (5 is passed to 'a', 10 is passed to 'b')
2. Keyword Arguments:
- These are passed by explicitly specifying the parameter name and value,
so the order does not matter.
- Example:
def greet(name, message):
print(f"{message}, {name}!")
greet(message="Good morning", name="Alice") # Output: Good
morning, Alice!
3. Default Arguments:
- If a parameter has a default value and no argument is provided, the default
value is used.
- Example:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
4. Variable-length Arguments:
- Python allows functions to accept any number of positional or keyword
arguments using `*args` and `kwargs`.
- Example using `*args`:
def add_all(*numbers):
return sum(numbers)
print(add_all(1, 2, 3)) # Output: 6
print(add_all(4, 5, 6, 7, 8)) # Output: 30
- Example using `kwargs`:
def print_details(info):
for key, value in [Link]():
print(f"{key}: {value}")
print_details(name="Alice", age=25, city="New York")
# Output:
# name: Alice
# age: 25
# city: New York
---
Summary:
- User-defined functions can be categorized based on whether they take
parameters and whether they return values.
- Arguments are actual values passed to a function, while parameters are the
placeholders defined in the function signature.
- Python supports positional, keyword, default, and variable-length
arguments, allowing for flexible function calls.
Unit-IV: Exception Handling in Python
In Python, exceptions are errors detected during execution. Exception
handling allows a program to deal with these errors gracefully, preventing the
program from crashing abruptly.
1. What Are Exceptions?
● Exception: An unwanted or unexpected event that disrupts the normal
flow of a program.
● Python provides a mechanism to handle these exceptions, ensuring the
program continues running smoothly even when an error
occurs.
Example of an Exception:
python
# Example of an exception (division by zero)
num = 10
result = num / 0 # This raises a ZeroDivisionError
In the above example, dividing a number by zero raises a
ZeroDivisionError exception.
2. Built-in Exceptions
Python has a set of built-in exceptions that are raised when errors occur.
Some common ones include:
Exception Description
ZeroDivisio Raised when division by zero occurs.
nError
ValueError Raised when a function receives an argument of the right
type but inappropriate value.
TypeError Raised when an operation is performed on an
inappropriate type.
IndexError Raised when trying to access an element out of the list or
tuple's range.
KeyError Raised when trying to access a dictionary key that does
not exist.
FileNotFoun Raised when trying to open a file that doesn't exist.
dError
ImportError Raised when an import fails (module not found).
AttributeEr Raised when an attribute reference or assignment fails.
ror
Indentation Raised when there is an incorrect indentation.
Error
Example of Built-in Exception:
python
# Trying to access an index out of range
my_list = [1, 2, 3]
print(my_list[5]) # Raises IndexError
3. Exception Handling in Python
To handle exceptions and prevent crashes, Python uses try-except
blocks.
Basic Syntax of Exception Handling:
python
try:
# Code that might raise an exception
pass
except SomeException:
# Code to handle the exception
pass
Example of Exception Handling:
python
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Please enter a number.")
Explanation:
● The try block contains code that may raise an exception.
● The except block contains the code to handle the exception.
● If an exception occurs in the try block, the program jumps to the
corresponding except block and continues execution.
4. Handling Multiple Exceptions
You can handle multiple exceptions by specifying different except
blocks.
Example:
python
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: You can't divide by zero.")
except ValueError:
print("Error: Invalid input, please enter a
number.")
In the above example:
● If the user enters zero, a ZeroDivisionError is handled.
● If the user enters a non-integer value, a ValueError is handled.
5. Catching All Exceptions
To catch any type of exception, you can use a generic except block:
python
try:
# Some code
except Exception as e:
print(f"An error occurred: {e}")
Example:
python
try:
num = int(input("Enter a number: "))
result = 10 / num
except Exception as e:
print(f"An error occurred: {e}")
6. Finally Block
The finally block is used to define code that should always run,
regardless of whether an exception occurred or not. It is often used to release
resources like closing files or network connections.
Example:
python
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always execute.")
7. User-defined Exceptions
Python allows users to create custom exceptions by defining new exception
classes. These classes should inherit from Python’s built-in Exception
class.
Syntax for User-defined Exception:
python
class MyCustomError(Exception):
pass
Example of User-defined Exception:
python
class NegativeNumberError(Exception):
"""Custom exception for negative numbers."""
pass
def check_positive(num):
if num < 0:
raise NegativeNumberError("Negative number
entered")
else:
print("Number is positive")
try:
number = int(input("Enter a positive number: "))
check_positive(number)
except NegativeNumberError as e:
print(e)
In this example, a custom exception NegativeNumberError is raised
when the user inputs a negative number.
Summary:
● Exceptions are runtime errors that occur when the program is running.
● Built-in exceptions like ValueError, ZeroDivisionError, and
IndexError handle common errors.
● Exception handling in Python uses try-except blocks to manage
exceptions and prevent crashes.
● User-defined exceptions allow you to create custom error types
tailored to your specific needs, ensuring better error handling.
FILE HANDLING
File Management in Python
File management in Python allows us to interact with files on our computer. We
can perform various operations such as opening, reading, writing, and closing files,
as well as navigating directories.
1. Opening a File
In Python, you can open a file using the `open()` function. The syntax is:
python
file_object = open('filename', mode)
- `'filename'`: The name of the file you want to open.
- `mode`: The mode in which you want to open the file. Common modes are:
- `'r'`: Read (default mode, file must exist).
- `'w'`: Write (creates a new file or truncates the existing one).
- `'a'`: Append (writes to the end of the file if it exists).
- `'b'`: Binary mode (used for non-text files like images).
- `'x'`: Exclusive creation (fails if the file already exists).
# Example:
python
# Opening a file in read mode
file = open("[Link]", "r")
2. File Modes
| Mode | Description |
|------|--------------------------------------------------------------------|
| `'r'` | Opens file for reading (default). File must exist. |
| `'w'` | Opens file for writing, truncates the file if it exists, or creates a new file. |
| `'a'` | Opens file for appending. Writes data to the end of the file. |
| `'b'` | Binary mode (e.g., for images). |
| `'r+'` | Opens file for reading and writing. |
| `'x'` | Creates a new file, fails if the file already exists. |
# Example:
python
# Writing to a file (creates the file if it does not exist)
file = open("[Link]", "w")
[Link]("Hello, World!")
[Link]()
3. File Attributes
When a file is opened, you can check its attributes like `name`, `mode`, and
`encoding`.
# Example:
python
file = open("[Link]", "r")
print([Link]) # Outputs the name of the file
print([Link]) # Outputs the mode of the file ('r' in this case)
print([Link]) # Outputs the encoding (usually 'UTF-8')
[Link]()
4. Closing a File
Once you're done with the file, it's important to close it using the `close()` method
to free up system resources.
# Example:
python
file = open("[Link]", "r")
# Do operations on the file
[Link]()
Or, you can use a `with` statement to automatically close the file after the block of
code is executed:
python
with open("[Link]", "r") as file:
content = [Link]()
print(content)
# File is automatically closed after the block
5. Reading Files
Python provides several methods to read files:
- `read()`: Reads the entire content of the file.
- `readline()`: Reads a single line from the file.
- `readlines()`: Reads all lines and returns a list of strings.
# Example:
python
with open("[Link]", "r") as file:
content = [Link]() # Reads entire content
print(content)
with open("[Link]", "r") as file:
line = [Link]() # Reads one line
print(line)
with open("[Link]", "r") as file:
lines = [Link]() # Reads all lines as a list
print(lines)
6. Writing to Files
- `write()`: Writes a string to the file.
- `writelines()`: Writes a list of strings to the file.
# Example:
python
# Writing to a file
with open("[Link]", "w") as file:
[Link]("Python is great!\n")
# Writing multiple lines
with open("[Link]", "w") as file:
lines = ["Python\n", "File Management\n", "Example\n"]
[Link](lines)
7. tell() & seek() Methods
- `tell()`: Returns the current position of the file pointer (in bytes).
- `seek()`: Moves the file pointer to a specified position.
# Example:
python
with open("[Link]", "r") as file:
[Link](10) # Read the first 10 characters
print([Link]()) # Check current position (should return 10)
[Link](0) # Move back to the start of the file
print([Link](5)) # Read the first 5 characters
8. Renaming & Deleting Files
The `os` module provides methods to rename or delete files:
- `[Link](old_name, new_name)`: Renames a file.
- `[Link](file_name)`: Deletes a file.
# Example:
python
import os
# Renaming a file
[Link]("[Link]", "new_example.txt")
# Deleting a file
[Link]("new_example.txt")
9. Directories in Python
Python allows you to work with directories using the `os` module:
- `[Link]()`: Creates a new directory.
- `[Link]()`: Lists the contents of a directory.
- `[Link]()`: Removes a directory (if empty).
- `[Link]()`: Changes the current working directory.
# Example:
python
import os
# Create a directory
[Link]("new_folder")
# Change directory
[Link]("new_folder")
# List contents of the directory
print([Link]())
# Remove directory
[Link]("..") # Go back to parent directory
[Link]("new_folder")
Full Example: Read, Write, and Analyze File
python
import os
# Write data to a file
with open("[Link]", "w") as file:
[Link]("Alice,90,85,88\nBob,78,82,80\nCharlie,95,92,93")
# Read and analyze file data
with open("[Link]", "r") as file:
lines = [Link]()
for line in lines:
name, math, science, english = [Link]().split(',')
average = (int(math) + int(science) + int(english)) / 3
print(f"{name}'s average score: {average:.2f}")
# Renaming the file
[Link]("[Link]", "student_scores.txt")
# Deleting the file
[Link]("student_scores.txt")
### File Management in Python (Extended)
In addition to basic file operations, Python's `[Link]` module and extended
file modes such as `r+`, `a+`, and `w+` provide more advanced file
management capabilities.
### 1. **Opening a File with Extended Modes**
Python allows us to open files in more advanced modes:
- `r+`: Opens a file for both **reading and writing**. The file must already
exist.
- `a+`: Opens a file for **reading and appending**. If the file doesn’t exist, it
is created.
- `w+`: Opens a file for **reading and writing**, but it **truncates** the file
(i.e., clears the file content if it exists).
#### Example:
```python
# r+: Read and Write mode (file must exist)
with open("example_r+.txt", "r+") as file:
content = [Link]()
print("Original content:", content)
[Link]("New line added.")
# a+: Append and Read mode (file will be created if it doesn't exist)
with open("example_a+.txt", "a+") as file:
[Link]("This is an appended line.\n")
[Link](0) # Move pointer to the start to read the file
content = [Link]()
print("Content after appending:", content)
# w+: Write and Read mode (file is truncated if it exists)
with open("example_w+.txt", "w+") as file:
[Link]("This file was opened in w+ mode.\n")
[Link](0) # Move pointer to the start to read the file
content = [Link]()
print("Content after writing:", content)
```
### 2. **File Modes Recap**
| Mode | Description |
|-------|--------------------------------------------------------------------|
| `'r+'` | Opens file for reading and writing. File must exist. |
| `'a+'` | Opens file for reading and appending. File is created if not exists. |
| `'w+'` | Opens file for reading and writing. File is truncated (cleared) if it
exists. |
### 3. **Using `[Link]` Module**
The `[Link]` module provides functions to work with file paths, check file
existence, and perform operations on directories.
#### Key Functions:
- `[Link]()`: Checks if a file or directory exists.
- `[Link]()`: Checks if a given path is a file.
- `[Link]()`: Checks if a given path is a directory.
- `[Link]()`: Joins directory paths to create full file paths.
- `[Link]()`: Returns the size of the file in bytes.
- `[Link]()`: Extracts the base name (file name) from a path.
- `[Link]()`: Extracts the directory name from a path.
#### Example:
```python
import os
# Check if file exists
if [Link]("example_r+.txt"):
print("File exists!")
else:
print("File does not exist.")
# Check if a path is a file or directory
print([Link]("example_r+.txt")) # True if it's a file
print([Link]("some_directory")) # True if it's a directory
# Join paths to create a full file path
folder = "documents"
file_name = "[Link]"
full_path = [Link](folder, file_name)
print("Full path:", full_path)
# Get the size of a file
file_size = [Link]("example_r+.txt")
print("File size:", file_size, "bytes")
# Extract the base name and directory name
print("Base name:", [Link](full_path)) # [Link]
print("Directory name:", [Link](full_path)) # documents
```
### 4. **Example: Combining File Modes and `[Link]`**
Here's an example that uses advanced file modes (`r+`, `a+`, and `w+`) and the
`[Link]` module for file management.
```python
import os
# Writing and Reading a file using w+ mode
with open("example_w+.txt", "w+") as file:
[Link]("Hello from w+ mode!\n")
[Link](0)
print("Content after writing:", [Link]())
# Checking file existence using [Link]
if [Link]("example_w+.txt"):
print("example_w+.txt exists!")
print("File size:", [Link]("example_w+.txt"), "bytes")
else:
print("File does not exist!")
# Reading and Appending to the file using a+ mode
with open("example_w+.txt", "a+") as file:
[Link]("This line is appended using a+ mode.\n")
[Link](0)
print("Content after appending:", [Link]())
# Renaming the file using [Link]
[Link]("example_w+.txt", "renamed_example.txt")
print("File renamed successfully!")
```
### 5. **Deleting Files and Directories**
You can delete files and directories using `[Link]()` and `[Link]()`
respectively.
- `[Link]()`: Deletes a file.
- `[Link]()`: Deletes an empty directory.
- `[Link]()`: Deletes a directory and all its contents (import `shutil` for
this).
#### Example:
```python
import os
import shutil
# Deleting a file
if [Link]("renamed_example.txt"):
[Link]("renamed_example.txt")
print("File deleted successfully!")
# Deleting a directory
if [Link]("test_directory"):
[Link]("test_directory")
print("Directory deleted successfully!")
# To remove a directory with its contents
if [Link]("directory_with_files"):
[Link]("directory_with_files")
print("Directory and all its contents deleted!")
```
### Summary of `[Link]` Functions
| Function | Description |
|------------------------|--------------------------------------------------------|
| `[Link]()` | Checks if a file or directory exists. |
| `[Link]()` | Checks if the given path is a file. |
| `[Link]()` | Checks if the given path is a directory. |
| `[Link]()` | Joins multiple path components into a single path. |
| `[Link]()` | Returns the size of the file in bytes. |
| `[Link]()` | Returns the base name (file name) of the path. |
| `[Link]()` | Returns the directory name of the path. |
### Summary of File Modes (`r+`, `a+`, `w+`)
- **`r+`**: Read and write. The file must exist.
- **`a+`**: Append and read. If the file doesn't exist, it's created.
- **`w+`**: Write and read. The file is truncated if it exists.
### Complete Example: Managing Files and Paths
import os
# Create and write to a file using w+ mode
with open("test_file.txt", "w+") as file:
[Link]("This is a test file.\n")
[Link](0)
print("Initial content:", [Link]())
# Append to the file using a+ mode
with open("test_file.txt", "a+") as file:
[Link]("Appending some data.\n")
[Link](0)
print("Content after appending:", [Link]())
# Check file existence and size
if [Link]("test_file.txt"):
print("File exists!")
print("File size:", [Link]("test_file.txt"), "bytes")
# Rename the file
[Link]("test_file.txt", "new_test_file.txt")
# Delete the file
[Link]("new_test_file.txt")
print("File deleted successfully!")