Unit 1 Full Notes Python
Unit 1 Full Notes Python
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.
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.
It is an interactive web application that allows you to write and run code.
• Automatic syntax highlighting and indentation are available when editing code in the browser.
• Check out the computations' output in media formats like HTML, LaTex, PNG, PDF, etc.
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.
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.
Upgrading pip
Step 3: Install the jupyter notebook using the command pip install jupyter notebook in the terminal.(refer to the
image)
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.
• Data science workflows: Organizing and recording the steps involved in data analysis.
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.
Advantages
• Supports interactive experimentation and step-by-step code execution for data exploration.
• Rich Documentation: Enables the creation of code-, text-, and visualization-filled notebooks.
• Support from the community: Gains from a vibrant community and a large ecosystem.
Disadvantages
• Not Good for Big Projects: Not good for big software development projects.
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:
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.
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.
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.
Python is also an Integrated language because we can easily integrate Python with other languages like C, C++, etc.
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.
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.
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.
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.
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.
• 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?
• Extensive libraries and frameworks: Offers rich libraries for web development, data science, AI, etc.
• Great for rapid prototyping: Quick syntax allows for fast idea implementation
• Web Development
• Easy to Learn and Use: Python’s simple and readable syntax makes it beginner-friendly.
• 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.
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.
• 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
Enclosed in triple quotes (""" """ or ''' '''), usually used for documentation.
'''This is an example
of multiline comment'''
print("Hello, World!")
"""
"""
print("Hello, World!")
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.
• Variable names can only contain letters, digits and underscores (_).
• Avoid using Python keywords (e.g., if, else, for) as variable names.
Example:
x = 10 # Integer
y = 3.14 # Float
print(x)
print(y)
print(name)
print(is_python_fun)
Explanation:
Output:
10
3.14
Alice
True
Python allows variables to be reassigned with different values and even different data types.
Example:
x = 5 # Initially an integer
print(x)
print(x)
Explanation:
Output:
Hello
3. Multiple Assignments
Example:
a, b, c = 1, 2.5, "Python"
print(a, b, c)
print(x, y, z)
Explanation:
a, b, c are assigned 1, 2.5, "Python" in one line.
Output:
1 2.5 Python
1. Swapping Variables
Example:
a = 10
b = 20
a, b = b, a # Swapping values
print("a =", a)
print("b =", b)
Explanation:
Output:
a = 20
b = 10
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(text))
# Type conversion
print(type(num_str))
print(type(text_int))
Explanation:
Output:
<class 'int'>
<class 'str'>
<class 'str'>
<class 'int'>
Example:
print("Hello, " + name + "! You are " + age + " years old.")
Explanation:
Example Interaction:
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
Output:
Conclusion
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.
Numeric data types store numerical values and include integers, floating-point numbers, and complex numbers.
Explanation: Integers are used when you need to count or index items.
Example:
age = 25
print(age, type(age))
Output:
25 <class 'int'>
Example:
price = 19.99
print(price, type(price))
Output:
Definition: Stores numbers in the form a + bj, where j is the imaginary unit.
Example:
num = 3 + 4j
print(num, type(num))
Output:
Example:
print(greeting, type(greeting))
Output:
Example:
print(fruits, type(fruits))
Output:
Explanation: Tuples are used when you want to store values that should not be changed.
Example:
print(coordinates, type(coordinates))
Output:
Example:
print(list(numbers))
Output:
[1, 2, 3, 4, 5]
Example:
my_set = {1, 2, 3, 3, 4}
Output:
Example:
print(frozen_set, type(frozen_set))
Output:
Example:
print(student, type(student))
Output:
Example:
is_python_fun = True
print(is_python_fun, type(is_python_fun))
Output:
True
Example:
print(b, type(b))
Output:
Example:
print(ba, type(ba))
Output:
Example:
mv = memoryview(bytes([1, 2, 3, 4]))
print(mv, type(mv))
Output:
7. None Type
Example:
x = None
print(x, type(x))
Output:
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
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators
7. Membership Operators
1. Arithmetic Operators
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
% Modulus (remainder) a % b
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
!= Not equal to a != b
Example:
x=5
y = 10
print(x == y) # False
print(x != y) # True
3. Logical Operators
and Returns True if both conditions are True x > 3 and x < 10
Example:
a = True
b = False
print(a or b) # True
print(not a) # False
4. Bitwise Operators
| Bitwise OR
^ Bitwise XOR a ^ b
~ Bitwise NOT ~a
Example:
a = 5 # 0101 in binary
b = 3 # 0011 in binary
print(a | b) # 7 (0111)
print(a ^ b) # 6 (0110)
5. Assignment Operators
= 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
Example:
a = [1, 2, 3]
b=a
c = [1, 2, 3]
7. Membership Operators
Example:
name = "Alice"
The help() function provides information about functions, classes, and modules.
print(abs(-10)) # Output: 10
The round(number, digits) function rounds a number to the given decimal places.
print("Hello,", name)
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
import math
import math
import math
Returns the natural logarithm (ln x), i.e., logarithm to the base e (~2.718).
import math
import math
import math
import math
print([Link](4.78)) # Output: 4
print([Link](-3.14)) # Output: -3
import math
print([Link](4.3)) # Output: 5
print([Link](-2.8)) # Output: -2
import math
print([Link](4.9)) # Output: 4
print([Link](-2.1)) # Output: -3
import math
Use Case: Used in scientific computing where integer and decimal parts need to be separated..
The math module provides trigonometric functions like sine, cosine, tangent, hyperbolic functions, inverse
trigonometric functions, and more.
import math
import math
import math
import math
import math
import math
import math
import math
import math
import math
import math
import math
Computes the hypotenuse (longest side) of a right triangle given sides x and y.
import math
import random
import random
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
The builtins module contains all standard Python functions like print(), len(), abs(), max(), etc.
import builtins
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:
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:
else:
Explanation:
• 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:
elif x > 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:
else:
else:
Explanation:
• 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".
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:
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
print(result)
Explanation:
The condition y > 0 checks if y is positive. Since y is 3, the result will be "Positive".
Key points:
It allows you to choose between two values based on a condition in a concise manner.
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:
case 2:
case 3:
case _:
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
def game_level(level):
match level:
case 1:
case 2:
case 3:
case 4:
case _:
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.
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.
x=0
while x < 5:
print(x)
x += 1
Explanation:
Output:
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:
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.
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:
• 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.
The range() function generates a sequence of numbers. It's often used with for loops to repeat actions a specific
number of times.
print(i)
Explanation:
• The for loop iterates over this sequence and prints each number.
Output:
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)
print(i)
Explanation:
Output:
A for loop can be nested inside another for loop to iterate over multiple sequences.
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:
Explanation:
• Once the loop finishes iterating, the else block executes and prints "Loop finished successfully."
Output:
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
Example:
def greet(name):
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.
1. Built-in Namespace
• Contains all built-in functions and exceptions, like print(), len(), int(), str(), etc.
Example:
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:
def show():
show() # Output: 10
3. Local Namespace
Example:
def func():
print(y)
func()
# print(y) # This would give an error because 'y' is not in the global namespace.
• 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():
a += 5
print(a)
inner()
outer() # Output: 15
def outer():
def inner():
outer()
Output:
local
enclosing
global
Python functions implicitly return a tuple when multiple values are returned.
def get_details():
name = "Alice"
age = 25
country = "USA"
result = get_details()
print(age) # Output: 25
def get_numbers():
numbers = get_numbers()
✔ Why? Use a list when you may need to modify the returned values.
def get_student():
student = get_student()
def get_unique_numbers():
result = get_unique_numbers()
Since functions are objects, you can store them in variables and call them later.
def greet(name):
greeting = greet
def square(x):
return x * x
def multiplier(n):
def multiply(x):
return x * n
print(double(5)) # Output: 10
return x + y
return x - y
operations = {
"sum": add,
"difference": subtract
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.
Inline: They are often used inline, where a function is needed temporarily.
add = lambda x, y: x + y
square = lambda x: x ** 2
print(square(4)) # Output: 16
constant = lambda: 42
print(constant()) # Output: 42
Lambda functions are often used with the sorted() function to sort lists based on a specific key.
Lambda functions can be used with the filter() function to filter elements from a list.
numbers = [1, 2, 3, 4, 5, 6]
Lambda functions can be used with the map() function to apply a function to all elements in a list.
numbers = [1, 2, 3, 4]
4. Inline Usage
Lambda functions are often used inline where a function is needed temporarily.
return func(value)
result = apply_function(lambda x: x * 3, 5)
print(result) # Output: 15
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.
1. Single Expression: They can only contain one expression, making them unsuitable for complex logic.
3. Readability: Overusing lambda functions can make code harder to read and understand.
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
return a + b
square = lambda x: x * x
print(square(4)) # Output: 16
4. Recursive Functions
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
5. Higher-Order Functions
return func(value)
double = lambda x: x * 2
6. Generator Functions
def countdown(n):
while n > 0:
yield n
n -= 1
print(num)
# Output:
#3
#2
#1
7. Nested Functions
def outer():
def inner():
return inner()