0% found this document useful (0 votes)
2 views50 pages

Unit 1 Full Notes Python

The document provides an overview of Jupyter Notebook and Python programming, detailing their features, components, and applications. Jupyter Notebook is an interactive web application that supports multiple programming languages, while Python is a high-level, interpreted language known for its simplicity and versatility. Key topics include installation steps, types of cells in Jupyter, advantages and disadvantages of both tools, and best practices for using comments and variables in Python.

Uploaded by

likithsai702
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views50 pages

Unit 1 Full Notes Python

The document provides an overview of Jupyter Notebook and Python programming, detailing their features, components, and applications. Jupyter Notebook is an interactive web application that supports multiple programming languages, while Python is a high-level, interpreted language known for its simplicity and versatility. Key topics include installation steps, types of cells in Jupyter, advantages and disadvantages of both tools, and best practices for using comments and variables in Python.

Uploaded by

likithsai702
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

UNIT-1

Jupyter Notebook

Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live
code, equations, visualizations, and narrative text. It is a popular tool among data scientists, researchers, and
educators for interactive computing and data analysis. The name "Jupyter" is derived from the three core
programming languages it originally supported: Julia, Python, and R.

What is Jupyter Notebook?

Three fundamental programming languages—Julia, Python, and R—that it initially supported are where Jupyter
Notebook gets its name. But now since it supports more than 40 programming languages, it is a flexible option for
a range of computational jobs. Because the notebook interface is web-based, users may use their web browsers to
interact with it.

Components of Jupyter Notebook

The Jupyter Notebook is made up of the three components listed below. -

1. The notebook web application

It is an interactive web application that allows you to write and run code.

Users of the notebook online application can:

• Automatic syntax highlighting and indentation are available when editing code in the browser.

• Activate the browser's code.

• Check out the computations' output in media formats like HTML, LaTex, PNG, PDF, etc.

• Create and use widgets in JavaScript.

• Contains mathematical formulas presented in Markdown cells

2. Kernels

The independent processes launched by the notebook web application are known as kernels, and they are used to
execute user code in the specified language and return results to the notebook web application.

The following languages are available for the Jupyter Notebook kernel:

• Python

•R

• Julia

• Ruby
• Scala

• [Link]

3. Notebook documents

All content viewable in the notebook online application, including calculation inputs and outputs, text,
mathematical equations, graphs, and photos, is represented in the notebook document.

Types of cells in Jupyter Notebook

1. Code Cell: A code cell's contents are interpreted as statements in the current kernel's programming
language. Python is supported in code cells because Jupyter notebook's kernel is by default written in that
language. The output of the statement is shown below the code when it is executed. The output can be shown
as text, an image, a matplotlib plot, or a set of HTML tables.

2. Markdown Cell: Markdown cells give the notebook documentation and enhance its aesthetic appeal. This
cell has all formatting options, including the ability to bold and italicize text, add headers, display sorted or
unordered lists, bulleted lists, hyperlinks, tabular contents, and images, among others.

3. Raw NBConvert Cell: There is a location where you can write code directly in Raw NBConvert Cell. The
notebook kernel does not evaluate these cells..

4. Heading Cell: The header cell is not supported by the Jupyter Notebook. The panel displayed in the
screenshot below will pop open when you choose the heading from the drop-down menu.

Key features of Jupyter Notebook

1. Several programming languages are supported.

2. Integration of Markdown-formatted text.

3. Rich outputs, such as tables and charts, are displayed.

4. flexibility in terms of language switching (kernels).

5. Opportunities for sharing and teamwork during export.

6. Adaptability and extensibility via add-ons.

7. Integration of interactive widgets with data science libraries.

8. Quick feedback and live code execution.

9. Widely employed in scientific research and education.

10. Getting Started with Jupyter Notebook

The easiest way to install jupyter notebook is through the terminal:

Step 1: Python's latest version for this method([Link]

Step 2 : Updating pip using cmd.


python -m pip install --upgrade pip

Upgrading pip

Step 3: Install the jupyter notebook using the command pip install jupyter notebook in the terminal.(refer to the
image)

pip install jupyter notebook

Step 4: Use the command jupyter notebook in terminal to run the notebook.

jupyter notebook

After you type the command, this home page should open up in your default browser.

Jupyter Home Page

Applications of Jupyter Notebook

• Data science workflows: Organizing and recording the steps involved in data analysis.

• Making slide displays and reports for presentations.

• Data analysis involves investigating and displaying data.

• The creation and evaluation of machine learning models.

• NLP: Text analysis and natural language processing.

Notebook Extensions

Extensions for Jupyter Notebook are add-ons or modules that improve the environment's functionality. Jupyter
Notebook is further enhanced and customizable by these extensions, which offer more capabilities and settings. The
Jupyter JavaScript API and the page's DOM are both accessible to extensions.

Although Jupyter Notebooks come with lots of built-in abilities, extensions let you add more. Actually, Jupyter
supports four different kinds of extensions:

• Kernel

• IPython kernel

• Notebook

• Notebook server

Keyboards Shortcuts

Working with code and markdown cells in Jupyter Notebook requires the use of keyboard shortcuts to increase
productivity. Here are several significant Jupyter Notebook keyboard shortcuts:

• Ctrl+Enter: Enter the current cell while holding down the control key.
• Y: Switch to the Code cell type.

• M: Markdown cell type change.

• D, D: Delete the current cell by pressing D twice.

• R: Switch to Raw cell type.

• Shift + S: Checkpoint and save the notebook.

• Z: Undelete a deleted cell.

• A: Add a new cell above the existing one.

• H: Display the keyboard shortcuts list.

• B: Add a new cell below the existing one.

Advantages

• Supports interactive experimentation and step-by-step code execution for data exploration.

• Multilingual: Supports a variety of programming languages.

• Rich Documentation: Enables the creation of code-, text-, and visualization-filled notebooks.

• Data Visualization: Works nicely with libraries for data visualization.

• Support from the community: Gains from a vibrant community and a large ecosystem.

Disadvantages

• Learning curve: Beginners may find it difficult.

• Version control: Complicated when controlling notebook versions.

• Resource Consuming: May use a lot of system resources.

• Not Good for Big Projects: Not good for big software development projects.

• Dependency Management: Managing dependencies takes more work.

python

Python is a dynamic, high-level, free open source, and interpreted programming language. It supports object-
oriented programming as well as procedural-oriented programming. In Python, we don’t need to declare the type of
variable because it is a dynamically typed language. For example, x = 10 Here, x can be anything such as String,
int, etc. In this article we will see what characteristics describe the python programming language

Python is a widely used high-level, interpreted programming language. It was created by Guido van Rossum in
1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code
readability, and its syntax allows programmers to express their concepts in fewer lines of code. Python is a
programming language that lets you work quickly and integrate systems more efficiently.
Features in Python

In this section we will see what are the features of Python programming language:

1. Free and Open Source

Python language is freely available at the official website and you can download it from the given download link
below click on the Download Python keyword. Download Python Since it is open-source, this means that source
code is also available to the public. So you can download it, use it as well as share it.

2. Easy to code

Python is a high-level programming language. Python is very easy to learn the language as compared to other
languages like C, C#, Javascript, Java, etc. It is very easy to code in the Python language and anybody can learn
Python basics in a few hours or days. It is also a developer-friendly language.

3. Easy to Read

As you will see, learning Python is quite simple. As was already established, Python’s syntax is really
straightforward. The code block is defined by the indentations rather than by semicolons or brackets.

4. Object-Oriented Language

One of the key features of Python is Object-Oriented programming. Python supports object-oriented language and
concepts of classes, object encapsulation, etc.

5. GUI Programming Support

Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in Python. PyQt5 is
the most popular option for creating graphical apps with Python.

6. High-Level Language

Python is a high-level language. When we write programs in Python, we do not need to remember the system
architecture, nor do we need to manage the memory.

7. Large Community Support

Python has gained popularity over the years. Our questions are constantly answered by the enormous
StackOverflow community. These websites have already provided answers to many questions about Python, so
Python users can consult them as needed.

8. Easy to Debug

Excellent information for mistake tracing. You will be able to quickly identify and correct the majority of your
program’s issues once you understand how to interpret Python’s error traces. Simply by glancing at the code, you
can determine what it is designed to perform.

9. Python is a Portable language


Python language is also a portable language. For example, if we have Python code for Windows and if we want to
run this code on other platforms such as Linux, Unix, and Mac then we do not need to change it, we can run this
code on any platform.

10. Python is an Integrated language

Python is also an Integrated language because we can easily integrate Python with other languages like C, C++, etc.

11. Interpreted Language:

Python is an Interpreted Language because Python code is executed line by line at a time. like other languages C,
C++, Java, etc. there is no need to compile Python code this makes it easier to debug our code. The source code of
Python is converted into an immediate form called bytecode.

12. Large Standard Library

Python has a large standard library that provides a rich set of modules and functions so you do not have to write
your own code for every single thing. There are many libraries present in Python such as regular expressions, unit-
testing, web browsers, etc.

13. Dynamically Typed Language

Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.) for a variable is
decided at run time not in advance because of this feature we don’t need to specify the type of variable.

14. Frontend and backend development

With a new project py script, you can run and write Python codes in HTML with the help of some simple tags <py-
script>, <py-env>, etc. This will help you do frontend development work in Python like javascript. Backend is the
strong forte of Python it’s extensively used for this work cause of its frameworks like Django and Flask.

15. Allocating Memory Dynamically

In Python, the variable data type does not need to be specified. The memory is automatically allocated to a variable
at runtime when it is given a value. Developers do not need to write int y = 18 if the integer value 15 is set to y. You
may just type y=18.

Python Latest Update

• The latest Python version is 3.12.6 and in this Python versions improve an efficiency, developer experience,
and performance.

• Improved Performance: Python 3.12 introduces several optimizations, such as support for the BOLT binary
optimizer, which provides an overall 5% performance improvement.

• Enhanced Error Messages: This version includes better error messages, with more detailed suggestions for
fixing common typos and mistakes, making it more user-friendly, especially for beginners.

• New Debugging Features: A new debugging and profiling API was introduced, which will be especially
useful for developers when profiling their applications.
• F-String Flexibility: Python’s f-string syntax has become more flexible, allowing for more powerful and
readable string formatting capabilities.

• Type Annotation Enhancements: Python 3.12 also introduces more advanced type annotations, especially for
generic classes, making code more readable and easier to maintain.

What is Python

Python is a high-level, interpreted programming language known for its simplicity and readability. Created by
Guido van Rossum and first released in 1991, Python has become one of the most popular programming languages
due to its versatility and ease of learning.

Advantages of Python?

• Easy to learn and use: Python’s simple syntax makes it beginner-friendly

• Extensive libraries and frameworks: Offers rich libraries for web development, data science, AI, etc.

• Versatile: Supports multiple programming paradigms and applications

• Cross-platform: Works seamlessly across Windows, macOS, and Linux

• Great for rapid prototyping: Quick syntax allows for fast idea implementation

Python Applications in Real World

• Web Development

• Data Science and Analytics

• Artificial Intelligence and Machine Learning

• Automation and Scripting

Python is used for:

• Web Development: Frameworks like Django, Flask.

• Data Science and Analysis: Libraries like Pandas, NumPy, Matplotlib.

• Machine Learning and AI: TensorFlow, PyTorch, Scikit-learn.

• Automation and Scripting: Automate repetitive tasks.

• Game Development: Libraries like Pygame.

• Web Scraping: Tools like BeautifulSoup, Scrapy.

• Desktop Applications: GUI frameworks like Tkinter, PyQt.

• Scientific Computing: SciPy, SymPy.

• Internet of Things (IoT): MicroPython, Raspberry Pi.


• DevOps and Cloud: Automation scripts and APIs.

• Cybersecurity: Penetration testing and ethical hacking tools.

Key Features of Python

• Easy to Learn and Use: Python’s simple and readable syntax makes it beginner-friendly.

• Cross-Platform Compatibility: Python runs seamlessly on Windows, macOS, and Linux.

• Extensive Libraries: Includes robust libraries for tasks like web development, data analysis, and machine
learning.

• Dynamic Typing: Variable types are determined automatically at runtime, simplifying code writing.

• Versatile: Supports multiple programming paradigms, including object-oriented, functional, and procedural
programming.

• Open Source: Python is free to use, distribute, and modify.

Why Learn Python?

Whether you are a beginner or an experienced developer, both have their own benefits.

For Beginners:

• Easy Syntax: Python syntax is like plain English, which allows you to focus on logic instead of worrying
about complex rules.

• Built-in Libraries for Beginners: Python has beginner friendly libraries like random, re, os etc, which can be
used while learning fundamentals.

• Error Friendly: Python’s error messages are easy to understand and debug.

• Project Oriented Learning: You can start making simple projects while learning the Python basics.

For Experienced:

• Easy Career Transition: If you know any other programming language, moving to Python is super easy.

• Great for Upskilling: Moving to Python expands your skill sets and gives opportunity to work in areas like
AI, Data Science, web development etc.

• High Demand of Python in Emerging tech: Python is widely used in trending domains, like Data Science,
Machine Learning, Cloud Computing etc.

• Bridge Between Roles: For software developers working with different language, learning Python can help
you integrate advanced features like AI in your projects.

Python Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the
program.

• Comments enhance the readability of the code.

• Comment can be used to identify functionality or structure the code-base.

• Comment can help understanding unusual or tricky scenarios handled by the code to prevent accidental
removal or changes.

• Comments can be used to prevent executing any specific part of your code, while making changes or testing.

In Python, comments are used to make code more readable and to explain what different parts of the program do.
Python supports two types of comments:

1. Single-line comments

Start with a # symbol and extend to the end of the line.

# This is a single-line comment

print("Hello, World!") # This prints Hello, World!

2. Multi-line comments (Docstrings)

Enclosed in triple quotes (""" """ or ''' '''), usually used for documentation.

Example of Multi-line Comments

'''This is an example

of multiline comment'''

print("Hello, World!")

"""

This is a multi-line comment (also called a docstring).

It can span multiple lines.

"""

# This is an example of a multiline comment

# created using multiple single-line commenced

# The code prints the text Hello World

print("Hello, World!")

Best Practices for Using Comments

• Keep comments concise and meaningful.


• Use comments to explain why something is done, not what (since code should be self-explanatory).

• Use docstrings for documenting functions, classes, and modules.

Python Variables

In Python, variables are used to store data that can be referenced and manipulated during program execution. A
variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python
variables do not require explicit declaration of type. The type of the variable is inferred based on the value
assigned.

Variables act as placeholders for data. They allow us to store and reuse values in our program.

Rules for Naming Variables

To use variables effectively, we must follow Python’s naming rules:

• Variable names can only contain letters, digits and underscores (_).

• A variable name cannot start with a digit.

• Variable names are case-sensitive (myVar and myvar are different).

• Avoid using Python keywords (e.g., if, else, for) as variable names.

1. Declaring and Assigning Variables

You can assign values to variables using the = operator.

Example:

x = 10 # Integer

y = 3.14 # Float

name = "Alice" # String

is_python_fun = True # Boolean

print(x)

print(y)

print(name)

print(is_python_fun)

Explanation:

x holds an integer (10).

y holds a floating-point number (3.14).

name holds a string ("Alice").


is_python_fun holds a boolean (True).

Output:

10

3.14

Alice

True

2. Changing Variable Values

Python allows variables to be reassigned with different values and even different data types.

Example:

x = 5 # Initially an integer

print(x)

x = "Hello" # Now changed to a string

print(x)

Explanation:

First, x is assigned an integer (5).

Later, x is assigned a string ("Hello"), demonstrating dynamic typing.

Output:

Hello

3. Multiple Assignments

Python allows multiple variables to be assigned values in a single line.

Example:

a, b, c = 1, 2.5, "Python"

print(a, b, c)

x = y = z = 100 # Assigning the same value to multiple variables

print(x, y, z)

Explanation:
a, b, c are assigned 1, 2.5, "Python" in one line.

x, y, z are all assigned the same value (100).

Output:

1 2.5 Python

100 100 100

1. Swapping Variables

In Python, you can swap values without using a temporary variable.

Example:

a = 10

b = 20

a, b = b, a # Swapping values

print("a =", a)

print("b =", b)

Explanation:

a and b swap values using a, b = b, a.

Output:

a = 20

b = 10

1. Type Checking and Type Conversion

You can check a variable’s type using type(), and convert between types using int(), float(), str(), etc.

Example:

num = 50

text = "123"

print(type(num)) # Checking type

print(type(text))

# Type conversion

num_str = str(num) # Convert int to string


text_int = int(text) # Convert string to int

print(type(num_str))

print(type(text_int))

Explanation:

type(num) returns <class 'int'>, meaning num is an integer.

text_int = int(text) converts "123" (a string) into an integer (123).

Output:

<class 'int'>

<class 'str'>

<class 'str'>

<class 'int'>

6. Taking User Input

Python allows user input using input(). By default, it returns a string.

Example:

name = input("Enter your name: ")

age = input("Enter your age: ")

print("Hello, " + name + "! You are " + age + " years old.")

Explanation:

input() takes user input as a string.

age remains a string unless explicitly converted using int(age).

Example Interaction:

Enter your name: Alice

Enter your age: 25

Hello, Alice! You are 25 years old.

7. Constants in Python

Python does not have built-in constant variables, but by convention, constants are written in UPPERCASE.

Example:
PI = 3.14159 # Constant value

GRAVITY = 9.8

print("Value of PI:", PI)

Output:

Value of PI: 3.14159

Conclusion

• Variables store different types of data.

• Python allows dynamic typing, meaning variables can change types.

• Multiple variables can be assigned in one line.

• Swapping variables is easy in Python.

• You can check and convert data types.

• input() allows user interaction.

• Constants are written in uppercase by convention.

Different Data Types in Python

Python has several built-in data types that define the type of values a variable can hold. These data types help
manage and manipulate data effectively. Below is a comprehensive explanation of different data types, including
definition, explanation, and examples.

1. Numeric Data Types

Numeric data types store numerical values and include integers, floating-point numbers, and complex numbers.

(a) Integer (int)

Definition: Stores whole numbers (positive, negative, or zero) without decimals.

Explanation: Integers are used when you need to count or index items.

Example:

age = 25

print(age, type(age))

Output:

25 <class 'int'>

(b) Floating Point (float)


Definition: Stores decimal numbers (floating-point numbers).

Explanation: Used when precision is required, like in scientific calculations.

Example:

price = 19.99

print(price, type(price))

Output:

19.99 <class 'float'>

(c) Complex (complex)

Definition: Stores numbers in the form a + bj, where j is the imaginary unit.

Explanation: Used for scientific and engineering calculations.

Example:

num = 3 + 4j

print(num, type(num))

Output:

(3+4j) <class 'complex'>

2. Sequence Data Types

These data types store ordered collections of items.

(a) String (str)

Definition: A sequence of characters enclosed in single, double, or triple quotes.

Explanation: Strings are used to store and manipulate text data.

Example:

greeting = "Hello, Python!"

print(greeting, type(greeting))

Output:

Hello, Python! <class 'str'>

(b) List (list)

Definition: An ordered, mutable collection of elements.


Explanation: Lists can store multiple data types and allow modification.

Example:

fruits = ["apple", "banana", "cherry"]

print(fruits, type(fruits))

[Link]("orange") # Adding an item

print("Updated List:", fruits)

Output:

['apple', 'banana', 'cherry'] <class 'list'>

Updated List: ['apple', 'banana', 'cherry', 'orange']

(c) Tuple (tuple)

Definition: An ordered, immutable collection of elements.

Explanation: Tuples are used when you want to store values that should not be changed.

Example:

coordinates = (10, 20, 30)

print(coordinates, type(coordinates))

Output:

(10, 20, 30) <class 'tuple'>

(d) Range (range)

Definition: Represents an immutable sequence of numbers, commonly used in loops.

Explanation: Efficient way to generate sequences of numbers.

Example:

numbers = range(1, 6) # Generates numbers from 1 to 5

print(list(numbers))

Output:

[1, 2, 3, 4, 5]

3. Set Data Types

These data types store unordered collections of unique elements.


(a) Set (set)

Definition: A collection of unique, unordered elements.

Explanation: Sets automatically remove duplicate values.

Example:

my_set = {1, 2, 3, 3, 4}

print(my_set, type(my_set)) # Duplicates removed

Output:

{1, 2, 3, 4} <class 'set'>

(b) Frozen Set (frozenset)

Definition: An immutable version of a set.

Explanation: Useful when you need a set that cannot be modified.

Example:

frozen_set = frozenset([1, 2, 3, 3, 4])

print(frozen_set, type(frozen_set))

Output:

frozenset({1, 2, 3, 4}) <class 'frozenset'>

4. Mapping Data Type

(a) Dictionary (dict)

Definition: A collection of key-value pairs.

Explanation: Used to store and retrieve data using keys.

Example:

student = {"name": "Alice", "age": 25, "grade": "A"}

print(student, type(student))

Output:

{'name': 'Alice', 'age': 25, 'grade': 'A'} <class 'dict'>

5. Boolean Data Type

(a) Boolean (bool)


Definition: Represents True or False values.

Explanation: Used in conditional statements.

Example:

is_python_fun = True

print(is_python_fun, type(is_python_fun))

print(10 > 5) # Boolean result

Output:

True <class 'bool'>

True

6. Binary Data Types

These store binary data.

(a) Bytes (bytes)

Definition: An immutable sequence of bytes.

Example:

b = bytes([65, 66, 67]) # ASCII for A, B, C

print(b, type(b))

Output:

b'ABC' <class 'bytes'>

(b) Bytearray (bytearray)

Definition: A mutable sequence of bytes.

Example:

ba = bytearray([65, 66, 67])

ba[1] = 68 # Changing value

print(ba, type(ba))

Output:

bytearray(b'ADC') <class 'bytearray'>

(c) Memoryview (memoryview)


Definition: Allows direct memory access to binary data.

Example:

mv = memoryview(bytes([1, 2, 3, 4]))

print(mv, type(mv))

Output:

<memory at 0x...> <class 'memoryview'>

7. None Type

Definition: Represents the absence of a value.

Example:

x = None

print(x, type(x))

Output:

None <class 'NoneType'>

Operators in Python

Operators in Python are special symbols that perform operations on variables and values. Python supports different
types of operators:

1. Arithmetic Operators

2. Comparison (Relational) Operators

3. Logical Operators

4. Bitwise Operators

5. Assignment Operators

6. Identity Operators

7. Membership Operators

Each of these categories is explained below with examples.

1. Arithmetic Operators

Used to perform mathematical operations like addition, subtraction, multiplication, etc.

Operator Description Example

+ Addition a + b
- Subtraction a - b

* Multiplication a * b

/ Division a / b (returns float)

% Modulus (remainder) a % b

** Exponentiation a ** b (a raised to the power b)

// Floor Division a // b (quotient without decimal)

Example:

a = 10

b=3

print("Addition:", a + b)

print("Subtraction:", a - b)

print("Multiplication:", a * b)

print("Division:", a / b)

print("Modulus:", a % b)

print("Exponentiation:", a ** b)

print("Floor Division:", a // b)

Output:

Addition: 13

Subtraction: 7

Multiplication: 30

Division: 3.3333333333333335

Modulus: 1

Exponentiation: 1000

Floor Division: 3

2. Comparison (Relational) Operators

Used to compare values and return True or False.

Operator Description Example


== Equal to a == b

!= Not equal to a != b

> Greater than a > b

< Less than a < b

>= Greater than or equal to a >= b

<= Less than or equal to a <= b

Example:

x=5

y = 10

print(x == y) # False

print(x != y) # True

print(x > y) # False

print(x < y) # True

print(x >= y) # False

print(x <= y) # True

3. Logical Operators

Used to combine conditional statements.

Operator Description Example

and Returns True if both conditions are True x > 3 and x < 10

or Returns True if at least one condition is True x > 3 or x < 2

not Returns True if the condition is False not(x > 3)

Example:

a = True

b = False

print(a and b) # False

print(a or b) # True

print(not a) # False
4. Bitwise Operators

Perform operations on binary numbers.

Operator Description Example

& Bitwise AND a & b

| Bitwise OR

^ Bitwise XOR a ^ b

~ Bitwise NOT ~a

<< Left shift a << 2

>> Right shift a >> 2

Example:

a = 5 # 0101 in binary

b = 3 # 0011 in binary

print(a & b) # 1 (0001)

print(a | b) # 7 (0111)

print(a ^ b) # 6 (0110)

print(~a) # -6 (inverts bits)

print(a << 1) # 10 (shifts left by 1 bit)

print(a >> 1) # 2 (shifts right by 1 bit)

5. Assignment Operators

Used to assign values to variables.

Operator Description Example

= Assign x = 5

+= Add and assign x += 5 (same as x = x + 5)

-= Subtract and assign x -= 5

*= Multiply and assign x *= 5

/= Divide and assign x /= 5

%= Modulus and assign x %= 5


**= Exponent and assign x **= 5

//= Floor divide and assign x //= 5

Example:

x = 10

x += 5 # x = x + 5

print(x) # 15

x *= 2 # x = x * 2

print(x) # 30

6. Identity Operators

Used to compare memory locations of objects.

Operator Description Example

is Returns True if both variables reference the same object x is y

is not Returns True if both variables reference different objects x is not y

Example:

a = [1, 2, 3]

b=a

c = [1, 2, 3]

print(a is b) # True (same object)

print(a is c) # False (different objects)

print(a is not c) # True

7. Membership Operators

Used to check if a value exists in a sequence.

Operator Description Example

in Returns True if value exists in sequence x in y

not in Returns True if value does not exist in sequence x not in y

Example:

fruits = ["apple", "banana", "cherry"]


print("banana" in fruits) # True

print("grape" not in fruits) # True

Python Built-in Functions with Explanation & Examples

1. print() – Display Output

The print() function displays output on the screen.

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

name = "Alice"

print("Welcome,", name) # Output: Welcome, Alice

👉 Use Case: Displaying messages, debugging values in a program.

2. help() – Get Documentation

The help() function provides information about functions, classes, and modules.

help(print) # Shows documentation for print()

help([Link]) # Shows documentation for [Link]() method

Use Case: Getting quick information about Python functions.

3. abs() – Absolute Value

The abs() function returns the absolute (positive) value of a number.

print(abs(-10)) # Output: 10

print(abs(5.5)) # Output: 5.5

Use Case: Distance calculations, stock market changes.

4. pow() – Exponentiation (Power)

The pow(x, y, mod) function calculates xyxy, optionally with modulo.

print(pow(2, 3)) # Output: 8 (2^3)

print(pow(3, 4, 5)) # Output: 1 ((3^4) % 5)

Use Case: Mathematics, cryptography, financial calculations.

5. min() – Find Minimum 📉

The min() function returns the smallest value.

print(min(4, 1, 7, 3)) # Output: 1


print(min([5, 9, 2, 8])) # Output: 2

Use Case: Finding the lowest price, smallest grade in a class.

6. max() – Find Maximum 📈

The max() function returns the largest value.

print(max(4, 1, 7, 3)) # Output: 7

print(max([5, 9, 2, 8])) # Output: 9

Use Case: Finding the highest temperature, largest sales figure.

7. divmod() – Division & Remainder 🔢

The divmod(x, y) function returns a tuple (quotient, remainder).

print(divmod(10, 3)) # Output: (3, 1) -> 10 // 3 = 3, remainder = 1

print(divmod(20, 4)) # Output: (5, 0)

Use Case: Converting seconds into minutes, handling currency denominations.

8. round() – Rounding Numbers 🧮

The round(number, digits) function rounds a number to the given decimal places.

print(round(3.14159, 2)) # Output: 3.14

print(round(2.675, 2)) # Output: 2.67 (Python rounding behavior)

Use Case: Rounding prices, financial calculations.

9. bin() – Convert to Binary 🖥️

The bin(x) function converts an integer to binary format.

print(bin(10)) # Output: 0b1010

print(bin(255)) # Output: 0b11111111

Use Case: Low-level programming, working with binary numbers.

10. oct() – Convert to Octal 🔢

The oct(x) function converts an integer to octal format.

print(oct(10)) # Output: 0o12

print(oct(255)) # Output: 0o377

Use Case: Permissions in Unix/Linux file systems.


11. hex() – Convert to Hexadecimal 🎨

The hex(x) function converts an integer to hexadecimal format.

print(hex(10)) # Output: 0xa

print(hex(255)) # Output: 0xff

Use Case: Colors in web design (#FF5733), cryptography.

12. type() – Find Variable Type 🏷️

The type(x) function returns the data type of a value or variable.

print(type(10)) # Output: <class 'int'>

print(type(3.14)) # Output: <class 'float'>

print(type("Hello")) # Output: <class 'str'>

print(type([1, 2, 3])) # Output: <class 'list'>

Use Case: Debugging, dynamic programming.

13. input() – Take User Input ⌨️

The input() function reads input from the user as a string.

name = input("Enter your name: ")

print("Hello,", name)

Use Case: Getting user input in programs.

14. int() – Convert to Integer 🔢

The int(x, base) function converts a value to an integer.

print(int("100")) # Output: 100

print(int("1010", 2)) # Output: 10 (Binary to Decimal)

print(int("A", 16)) # Output: 10 (Hexadecimal to Decimal)

Use Case: Type conversion, parsing numbers.

15. str() – Convert to String 📝

The str(x) function converts a value to a string.

print(str(100)) # Output: "100"

print(str(3.14)) # Output: "3.14"


print(str(True)) # Output: "True"

Use Case: Formatting output, saving data as text.

Python math Module – Built-in Functions with Examples 🚀

The math module provides mathematical functions such as square root, factorial, logarithms, rounding functions,
and more. To use it, import math at the beginning of your program.

import math

1. [Link](x) – Square Root

Finds the square root of a number.

import math

print([Link](25)) # Output: 5.0

print([Link](2)) # Output: 1.4142135623730951

Use Case: Geometry calculations, physics formulas.

2. [Link](x) – Factorial of a Number

Computes x!x! (product of all positive integers up to x).

import math

print([Link](5)) # Output: 120 (5! = 5 × 4 × 3 × 2 × 1)

print([Link](7)) # Output: 5040

Use Case: Probability calculations, combinatorics.

3. [Link](x) – Absolute Value (Float)

Returns the absolute (positive) value of a number as a float.

import math

print([Link](-10)) # Output: 10.0

print([Link](5.5)) # Output: 5.5

Use Case: Handling distances, financial calculations.

4. [Link](x) – Natural Logarithm (Base e) 📖

Returns the natural logarithm (ln x), i.e., logarithm to the base e (~2.718).

import math

print([Link](10)) # Output: 2.302585092994046


print([Link](math.e)) # Output: 1.0 (ln(e) = 1)

Use Case: Machine learning, exponential growth modeling.

[Link].log10(x) – Logarithm Base 10

Computes the logarithm of x to base 10.

import math

print(math.log10(100)) # Output: 2.0 (log10(100) = 2)

print(math.log10(1000)) # Output: 3.0

Use Case: Scientific calculations, measuring sound levels (decibels).

6. [Link](x) – Exponential Function exex

Computes exex, where e (~2.718) is Euler’s number.

import math

print([Link](2)) # Output: 7.38905609893065 (e^2)

print([Link](0)) # Output: 1.0 (e^0 = 1)

Use Case: Population growth models, compound interest.

7. [Link](x) – Truncate Decimal Part

Removes the decimal part and returns only the integer.

import math

print([Link](4.78)) # Output: 4

print([Link](-3.14)) # Output: -3

Use Case: Used in financial applications to ignore decimal fractions.

8. [Link](x) – Ceiling Function (Round Up)

Rounds up to the nearest integer.

import math

print([Link](4.3)) # Output: 5

print([Link](-2.8)) # Output: -2

Use Case: Ticket pricing, where prices are rounded up.

9. [Link](x) – Floor Function (Round Down)


Rounds down to the nearest integer.

import math

print([Link](4.9)) # Output: 4

print([Link](-2.1)) # Output: -3

Use Case: Discretizing continuous values (e.g., floors in a building).

10. [Link](x) – Split Integer & Decimal Parts

Returns a tuple (fractional_part, integer_part).

import math

print([Link](4.75)) # Output: (0.75, 4.0)

print([Link](-2.3)) # Output: (-0.3, -2.0)

Use Case: Used in scientific computing where integer and decimal parts need to be separated..

Python math Module – Trigonometric Functions Explained with Examples

The math module provides trigonometric functions like sine, cosine, tangent, hyperbolic functions, inverse
trigonometric functions, and more.

To use them, import math at the beginning of your program:

import math

1. [Link](x) – Convert Radians to Degrees

Converts an angle from radians to degrees.

import math

print([Link]([Link])) # Output: 180.0

print([Link]([Link]/2)) # Output: 90.0

Use Case: Converting angles for engineering and physics calculations.

2. [Link](x) – Convert Degrees to Radians

Converts an angle from degrees to radians.

import math

print([Link](180)) # Output: 3.141592653589793 (π)

print([Link](90)) # Output: 1.5707963267948966 (π/2)

Use Case: Converting degrees to radians for trigonometric calculations.


3. [Link](x) – Sine Function

Computes the sine of x (angle in radians).

import math

print([Link]([Link](30))) # Output: 0.5

print([Link]([Link](90))) # Output: 1.0

Use Case: Used in wave equations, physics, and signal processing.

4. [Link](x) – Cosine Function

Computes the cosine of x (angle in radians).

import math

print([Link]([Link](0))) # Output: 1.0

print([Link]([Link](60))) # Output: 0.5

Use Case: Used in rotational mechanics, GPS calculations.

5. [Link](x) – Tangent Function

Computes the tangent of x (angle in radians).

import math

print([Link]([Link](45))) # Output: 1.0

print([Link]([Link](30))) # Output: 0.5773502691896257

Use Case: Used in geometry, physics, and navigation systems.

6. [Link](x) – Hyperbolic Sine

Computes the hyperbolic sine of x.

import math

print([Link](1)) # Output: 1.1752011936438014

Use Case: Used in thermal expansion, electrical engineering.

7. [Link](x) – Hyperbolic Cosine 🌡️

Computes the hyperbolic cosine of x.

import math

print([Link](1)) # Output: 1.5430806348152437


Use Case: Used in relativity, physics, and engineering calculations.

8. [Link](x) – Hyperbolic Tangent ⚖️

Computes the hyperbolic tangent of x.

import math

print([Link](1)) # Output: 0.7615941559557649

Use Case: Used in neural networks, physics simulations.

9. [Link](x) – Inverse Sine (Arcsin)

Computes the inverse sine (arcsin) of x, returning an angle in radians.

import math

print([Link]([Link](0.5))) # Output: 30.0

Use Case: Used in GPS calculations, solving right triangles.

10. [Link](x) – Inverse Cosine (Arccos)

Computes the inverse cosine (arccos) of x, returning an angle in radians.

import math

print([Link]([Link](0.5))) # Output: 60.0

Use Case: Used in robotics, navigation, physics.

11. [Link](x) – Inverse Tangent (Arctan)

Computes the inverse tangent (arctan) of x, returning an angle in radians.

import math

print([Link]([Link](1))) # Output: 45.0

Use Case: Used in computer graphics, calculating slopes.

12. [Link](x, y) – Hypotenuse Calculation

Computes the hypotenuse (longest side) of a right triangle given sides x and y.

import math

print([Link](3, 4)) # Output: 5.0 (Pythagorean theorem)

Use Case: Used in distance calculations, robotics, physics.

Python Random & Built-in Modules Explained


Python provides built-in modules like random for generating random numbers

[Link]() – Generate Random Float (0 to 1)

Returns a random floating-point number between 0 and 1 (excluding 1).

import random

print([Link]()) # Output: 0.374245 (varies each time)

Use Case: Simulating probabilities, games, simulations.

2. [Link](a, b) – Random Integer in Range 🎲

Returns a random integer between a and b (inclusive).

import random

print([Link](1, 10)) # Output: Random integer between 1 and 10

Use Case: Rolling dice, generating OTPs, selecting random items.

3. [Link](x) – Set Random Seed (Reproducible Results)

Seeds the random number generator to produce the same sequence every time.

import random

[Link](42)

print([Link](1, 100)) # Output: Always the same number if seed is the same

Use Case: Testing, debugging, machine learning (ensuring reproducibility).

4. __builtin__ (or builtins in Python 3) – Built-in Functions

The builtins module contains all standard Python functions like print(), len(), abs(), max(), etc.

Example: Checking Built-in Functions

import builtins

print(dir(builtins)) # Lists all built-in functions in Python

Conditional Statements and Loops:

If-statement

In Python, the if statement allows for conditional execution, which means that different blocks of code can be
executed based on whether a given condition evaluates to True or False. Below are the different types of if
statements in Python, along with examples and explanations.

1. Basic if Statement
The simplest form of the if statement checks a single condition. If the condition is True, the code inside the if block
runs.

Example:

x = 10

if x > 5:

print("x is greater than 5")

Explanation:

• The condition x > 5 evaluates to True because 10 > 5, so the code inside the if block executes, and it prints
"x is greater than 5".

2. if-else Statement

The if-else statement provides an alternative block of code that runs when the condition is False.

Example:

x=3

if x > 5:

print("x is greater than 5")

else:

print("x is not greater than 5")

Explanation:

• The condition x > 5 evaluates to False because 3 is not greater than 5.

• Therefore, the code inside the else block executes, and it prints "x is not greater than 5".

3. if-elif-else Statement

The if-elif-else statement is used when you have multiple conditions to check. The elif (short for "else if") allows
you to check additional conditions if the first one is False.

Example:

x=7

if x > 10:

print("x is greater than 10")

elif x > 5:

print("x is greater than 5 but less than or equal to 10")


else:

print("x is less than or equal to 5")

Explanation:

• The condition x > 10 is False, so Python checks the next condition, x > 5, which is True because 7 > 5.

• The code inside the elif block executes, printing "x is greater than 5 but less than or equal to 10".

4. Nested if Statements

An if statement can be nested inside another if statement, allowing for more complex decision-making.

Example:

x = 10

y = 20

if x > 5:

if y > 15:

print("x is greater than 5 and y is greater than 15")

else:

print("x is greater than 5 but y is not greater than 15")

else:

print("x is less than or equal to 5")

Explanation:

• The outer if checks if x > 5, which is True (since 10 > 5).

• Then, the inner if checks if y > 15, which is also True (since 20 > 15).

• Therefore, the output is "x is greater than 5 and y is greater than 15".

[Link] statement in a single line

In Python, you can write a simple if statement in a single line using a conditional expression (also known as a
ternary operator). The syntax is as follows:

value_if_true if condition else value_if_false

Example:

x = 10

print("x is greater than 5" if x > 5 else "x is less than or equal to 5")
Explanation:

The condition x > 5 is evaluated. Since x is 10, which is greater than 5, the first part "x is greater than 5" is printed.

If the condition were False, the second part "x is less than or equal to 5" would have been printed.

Another Example:

y=3

result = "Positive" if y > 0 else "Non-positive"

print(result)

Explanation:

The condition y > 0 checks if y is positive. Since y is 3, the result will be "Positive".

Key points:

This single-line version is a compact way to handle simple conditions.

It allows you to choose between two values based on a condition in a concise manner.

Switch -Match -statement

Using the match Statement (Python 3.10 and later)

Python 3.10 introduced the match statement, which provides pattern matching, and it can be used to simulate a
switch statement.

Example:

def switch_example(option):

match option:

case 1:

return "Option 1 selected"

case 2:

return "Option 2 selected"

case 3:

return "Option 3 selected"

case _:

return "Invalid option"

print(switch_example(2))
Explanation:

• The match statement works similarly to switch. It checks the option against each case (like a switch case).

• The _ (underscore) case acts as a default, similar to the else clause in a traditional switch statement.

Write a program that uses the match statement to simulate a switch for a user input. The program should take a
number between 1 and 4, and print a message corresponding to the level of a game (1 = Beginner, 2 = Intermediate,
3 = Advanced, 4 = Expert). If the number is not in the range, it should print "Invalid level".

Example Input/Output:

• Input: 2

• Output: Intermediate Level

def game_level(level):

match level:

case 1:

return "Beginner Level"

case 2:

return "Intermediate Level"

case 3:

return "Advanced Level"

case 4:

return "Expert Level"

case _:

return "Invalid level"

# Get user input

level = int(input("Enter a level (1-4): "))

print(game_level(level))

while loop:

In Python, a while loop repeatedly executes a block of code as long as a specified condition is True. Once the
condition becomes False, the loop stops.

Basic Syntax of while loop:

while condition:
# code to execute repeatedly

Explanation:

• condition: A boolean expression that is evaluated before each iteration. If it's True, the loop body executes.
If it's False, the loop terminates.

• code to execute repeatedly: This is the block of code that will run repeatedly as long as the condition
remains true.

Example 1: Simple while loop

x=0

while x < 5:

print(x)

x += 1

Explanation:

• The loop continues to run as long as x is less than 5.

• In each iteration, it prints the value of x and then increments x by 1.

• The loop will stop once x becomes 5.

Output:

Example 2: while loop with a break statement

You can use the break statement to exit the loop early, even if the condition hasn't become False yet.

x=0

while True:

if x == 3:

break # Exit the loop when x is 3

print(x)
x += 1

Explanation:

• The condition in the while loop is always True, so it will run infinitely unless stopped by a break statement.

• The loop will stop when x reaches 3.

for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of
code for each item in that sequence. The for loop in Python is different from other programming languages, as it
directly iterates over the elements of a sequence rather than using an index.

for loop:

Basic Syntax of for loop:

for item in sequence:

# code to execute for each item

• item: The variable that takes the value of each element in the sequence during each iteration.

• sequence: The sequence (e.g., list, tuple, string, etc.) over which the loop iterates.

[Link] loop with range()

The range() function generates a sequence of numbers. It's often used with for loops to repeat actions a specific
number of times.

for i in range(5): # Loops over numbers 0 to 4

print(i)

Explanation:

• The range(5) generates numbers from 0 to 4 (not including 5).

• The for loop iterates over this sequence and prints each number.

Output:

2. Using range() with both start and stop parameters

If you provide both start and stop, the sequence will start at the start value and end at stop - 1.
Example 2: Using range(start, stop)

for i in range(2, 7): # This will generate numbers from 2 to 6

print(i)

Explanation:

• range(2, 7) generates the numbers 2, 3, 4, 5, 6.

• The for loop will print each of these numbers.

Output:

3. Nested for loop

A for loop can be nested inside another for loop to iterate over multiple sequences.

for i in range(3): # Outer loop

for j in range(2): # Inner loop

print(f"i={i}, j={j}")

Explanation:

• The outer loop runs 3 times (with i taking values 0, 1, and 2).

• For each iteration of the outer loop, the inner loop runs 2 times (with j taking values 0 and 1).

Output:

i=0, j=0

i=0, j=1

i=1, j=0

i=1, j=1

i=2, j=0

i=2, j=1
4. for loop with else statement

You can use an else clause with a for loop. The else block will execute after the loop completes, unless the loop is
terminated prematurely by a break statement.

for i in range(3):

print(i)

else:

print("Loop finished successfully.")

Explanation:

• The for loop runs from 0 to 2 and prints each number.

• Once the loop finishes iterating, the else block executes and prints "Loop finished successfully."

Output:

Loop finished successfully.

Functions in Python

A function in Python is a block of reusable code that performs a specific task. Functions help in making the code
modular, reusable, and easy to manage.

Definition of a Function

A function in Python is defined using the def keyword, followed by the function name and parentheses (). It can
have parameters (input values) and return a result.

Syntax:

def function_name(parameters):

"""Docstring (optional)"""

# Function body

return value # (Optional)

Example:

def greet(name):

"""This function greets the user."""


return f"Hello, {name}!"

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

Namespaces in Python

A namespace in Python is a mapping between names (identifiers) and objects (variables, functions, etc.). It ensures
that names are unique and prevents naming conflicts.

Types of Namespaces in Python

Python has different types of namespaces based on scope and lifetime:

1. Built-in Namespace

• Contains all built-in functions and exceptions, like print(), len(), int(), str(), etc.

• Available everywhere in the program.

Example:

print(len("Hello")) # 'len' comes from the built-in namespace

2. Global Namespace

• Contains variables and functions defined at the top level of a script or module.

• Available throughout the script but not inside functions unless specified with global.

Example:

x = 10 # 'x' is in the global namespace

def show():

print(x) # Accessing global variable

show() # Output: 10

3. Local Namespace

• Created inside a function when it is called.

• Contains variables defined inside the function.

• Destroyed after the function ends.

Example:

def func():

y = 5 # 'y' is in the local namespace

print(y)
func()

# print(y) # This would give an error because 'y' is not in the global namespace.

4. Enclosing Namespace (Nonlocal)

• Exists in nested functions.

• The inner function can access variables from the outer function but cannot modify them unless nonlocal is
used.

Example:

def outer():

a = 10 # Enclosing variable

def inner():

nonlocal a # Allows modification of 'a' in the outer function

a += 5

print(a)

inner()

outer() # Output: 15

Namespace Resolution: LEGB Rule

Python follows the LEGB rule to resolve variable names:

1. Local → Check inside the function.

2. Enclosing → Check in the enclosing function (if nested).

3. Global → Check the global scope.

4. Built-in → Check Python’s built-in functions.

Example demonstrating LEGB:

x = "global" # Global namespace

def outer():

x = "enclosing" # Enclosing namespace

def inner():

x = "local" # Local namespace

print(x) # Prints 'local'


inner()

print(x) # Prints 'enclosing'

outer()

print(x) # Prints 'global'

Output:

local

enclosing

global

Returning Multiple Values in Python

In Python, a function can return multiple values using:


✔ Tuples
✔ Lists
✔ Dictionaries
✔ Sets

1. Returning Multiple Values Using a Tuple

Python functions implicitly return a tuple when multiple values are returned.

def get_details():

name = "Alice"

age = 25

country = "USA"

return name, age, country # Returns a tuple

result = get_details()

print(result) # Output: ('Alice', 25, 'USA')

# Accessing values separately

name, age, country = get_details()

print(name) # Output: Alice

print(age) # Output: 25

print(country) # Output: USA

✔ Why? Tuples are immutable and easy to unpack.


2. Returning Multiple Values Using a List

If the function needs to return modifiable values, use a list.

def get_numbers():

return [1, 2, 3, 4, 5] # Returns a list

numbers = get_numbers()

print(numbers) # Output: [1, 2, 3, 4, 5]

✔ Why? Use a list when you may need to modify the returned values.

3. Returning Multiple Values Using a Dictionary

If the returned values need named labels, use a dictionary.

def get_student():

return {"name": "Alice", "age": 25, "grade": "A"}

student = get_student()

print(student) # Output: {'name': 'Alice', 'age': 25, 'grade': 'A'}

print(student["name"]) # Output: Alice

✔ Why? Useful when the data needs clear labeling.

4. Returning Multiple Values Using a Set

If unique values are needed, use a set.

def get_unique_numbers():

return {1, 2, 3, 4, 4, 5} # Duplicates are removed

result = get_unique_numbers()

print(result) # Output: {1, 2, 3, 4, 5}

✔ Why? Ensures values are unique.

Functions as Objects in Python

In Python, functions are first-class objects, meaning they can:


✅ Be assigned to variables
✅ Be passed as arguments to other functions
✅ Be returned from other functions
✅ Be stored in data structures (lists, dictionaries, etc.)

This makes Python flexible and powerful for functional programming.


1. Assigning Functions to Variables

Since functions are objects, you can store them in variables and call them later.

def greet(name):

return f"Hello, {name}!"

# Assign function to a variable

greeting = greet

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

✔ Why? This allows dynamic function selection.

2. Passing Functions as Arguments

Functions can be passed as arguments to other functions, enabling higher-order functions.

def square(x):

return x * x

def apply_function(func, value):

return func(value) # Calls the passed function

print(apply_function(square, 4)) # Output: 16

✔ Why? This is useful for callbacks and functional programming.

3. Returning Functions from Another Function

A function can return another function, creating function factories.

def multiplier(n):

def multiply(x):

return x * n

return multiply # Returning the inner function

double = multiplier(2) # double is now a function

print(double(5)) # Output: 10

✔ Why? This enables custom function creation.

4. Storing Functions in Data Structures

Functions can be stored in lists, dictionaries, or other data structures.


def add(x, y):

return x + y

def subtract(x, y):

return x - y

operations = {

"sum": add,

"difference": subtract

print(operations["sum"](10, 5)) # Output: 15

print(operations["difference"](10, 5)) # Output: 5

✔ Why? Useful for building dynamic behavior.

Lambda functions

Lambda functions in Python are small, anonymous functions defined using the lambda keyword. They are also
known as anonymous functions because they are not declared using the standard def keyword. Lambda functions
are typically used for short, simple operations that can be written in a single line.

Syntax of Lambda Functions

The syntax for a lambda function is:

lambda arguments: expression

lambda: Keyword used to define a lambda function.

arguments: Input arguments (similar to parameters in a regular function).

expression: A single expression that is evaluated and returned.

Key Characteristics of Lambda Functions

Anonymous: They do not have a name (unless explicitly assigned to a variable).

Single Expression: They can only contain one expression.

Inline: They are often used inline, where a function is needed temporarily.

No Statements: They cannot include statements like if, for, or while.

Examples of Lambda Functions

1. Basic Lambda Function


A lambda function that adds two numbers:

add = lambda x, y: x + y

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

2. Lambda Function with One Argument

A lambda function that squares a number:

square = lambda x: x ** 2

print(square(4)) # Output: 16

3. Lambda Function with No Arguments

A lambda function that returns a constant value:

constant = lambda: 42

print(constant()) # Output: 42

4. Lambda Function with Conditional Logic

A lambda function that returns the maximum of two numbers:

max_num = lambda x, y: x if x > y else y

print(max_num(10, 20)) # Output: 20

Common Use Cases for Lambda Functions

1. Sorting with sorted()

Lambda functions are often used with the sorted() function to sort lists based on a specific key.

Example: Sort a list of tuples by the second element

data = [(1, 3), (4, 1), (2, 2)]

sorted_data = sorted(data, key=lambda x: x[1])

print(sorted_data) # Output: [(4, 1), (2, 2), (1, 3)]

2. Filtering with filter()

Lambda functions can be used with the filter() function to filter elements from a list.

Example: Filter even numbers from a list

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

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))


print(even_numbers) # Output: [2, 4, 6]

3. Mapping with map()

Lambda functions can be used with the map() function to apply a function to all elements in a list.

Example: Double each element in a list

numbers = [1, 2, 3, 4]

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

print(doubled_numbers) # Output: [2, 4, 6, 8]

4. Inline Usage

Lambda functions are often used inline where a function is needed temporarily.

Example: Use a lambda function as an argument to another function

def apply_function(func, value):

return func(value)

result = apply_function(lambda x: x * 3, 5)

print(result) # Output: 15

Advantages of Lambda Functions

1. Conciseness: They allow you to write simple functions in a single line.

2. Readability: They can make code more readable when used appropriately.

3. No Need for a Name: They are useful for small, one-time operations where defining a full function is
unnecessary.

Limitations of Lambda Functions

1. Single Expression: They can only contain one expression, making them unsuitable for complex logic.

2. No Statements: They cannot include statements like if, for, or while.

3. Readability: Overusing lambda functions can make code harder to read and understand.

Types of Functions in Python

Python has different types of functions based on their use and implementation.

1. Built-in Functions

Python provides several built-in functions like print(), len(), type(), sum(), etc.

print(len("Hello")) # Output: 5
2. User-Defined Functions

These are functions created by users to perform specific tasks.

def add(a, b):

return a + b

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

3. Anonymous (Lambda) Functions

A lambda function is a small, single-expression function that doesn’t require a name.

square = lambda x: x * x

print(square(4)) # Output: 16

4. Recursive Functions

A function that calls itself to solve a problem.

def factorial(n):

if n == 0:

return 1

return n * factorial(n - 1)

print(factorial(5)) # Output: 120

5. Higher-Order Functions

Functions that take other functions as arguments.

def apply_function(func, value):

return func(value)

double = lambda x: x * 2

print(apply_function(double, 5)) # Output: 10

6. Generator Functions

Functions that use yield instead of return to produce a sequence of values.

def countdown(n):

while n > 0:

yield n
n -= 1

for num in countdown(3):

print(num)

# Output:

#3

#2

#1

7. Nested Functions

Functions defined inside other functions.

def outer():

def inner():

return "Hello from inner function"

return inner()

print(outer()) # Output: Hello from inner function

You might also like