Python All Unit by Dsalgo
Python All Unit by Dsalgo
COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”
Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.
Example :
Python is a versatile and widely-used programming language # Basic print statement
known for its readability and ease of use print("Hello, World!")
It is object oriented programming language # Printing multiple values
name =, nam "Alice"
age = 30
Python's programming cycle is notably shorter due to its print("Name:"e, "Age:", age)
interpreted nature. # Changing separator and end
Python skips compile and link steps, distinguishing itself from
print("Four")
traditional languages.
Programs import modules at runtime, ensuring immediate print("One", "Two", "Three", sep=' | ', end='
execution after changes. *** ')
Dynamic module reloading in Python allows modifications and
reloads during runtime, facilitating continuous program
updates without interruptions. The input() function is used to take user input from the
console. It waits for the user to enter some text and returns
that text as a string.
Syntax :
variable = input(prompt)
Example
# Taking user input
name = input("Enter your name: ")
print("Hello, " + name + "!")
# Converting input to integer
age = int(input("Enter your age: "))
print("You will be", age + 1, "years old next
year.")
Single-Line Comments:
An Integrated Development Environment (IDE) is a software Created with #.
suite that streamlines the software development process. Used for short explanations on the same line.
Syntax :
# Single-line comment
Multi-Line (Block) Comments:
Achieved with triple-quoted strings.
Used for longer explanations spanning multiple lines.
Syntax :
'''
Multi-line comment
'''
Best Practices:
Provide clarity and context.
Keep comments concise and up-to-date.
Avoid redundancy with self-explanatory code.
Example :
result = calculate_total(price, quantity) # Calculate total cost
Examples:
Reserved keywords in a programming language are words # Implicit conversion
that have special meanings and cannot be used as identifiers result = 10 + 3.14 # int implicitly converted
(names for variables, functions, etc.)
to float for addition
because they are reserved for specific purposes in the
language. # Explicit conversion
num_float = 5.5
num_int = int(num_float) # Converts float to
integer
str_num = str(42)
data types represent the type of data that a variable can hold.
Here are some common data types in Python: A combination of symbols that yields a value.
Integer (int): Comprises variables, operators, values, sub-expressions, and
Represents whole numbers without decimal points.
reserved keywords.
Example: x = 5
When entered in the command line, expressions are
Float (float): evaluated by the interpreter, producing a result.
Represents numbers with decimal points or in exponential
arithmetic expressions are evaluating to a numeric type are
form. termed arithmetic expressions.
Example: y = 3.14
Sub-expressions are parts of larger expressions, enclosed in
String (str): parentheses.
Represents text or sequences of characters.
Example: 4 + (3 * k)
Example: name = "John"
Individual Expressions: A single literal or variable can also be
Boolean (bool): considered an expression (e.g., 4, 3, k).
Represents either True or False.
Hierarchy of Sub-Expressions: Expressions may have
Example: is_valid = True
multiple levels of sub-expressions, forming a hierarchy.
List (list): Example: a + (b * (c - d)) has sub-expressions 3 and k.
Represents an ordered collection of elements.
Example: numbers = [1, 2, 3]
Tuple (tuple): Used for creating, assigning values to, and modifying
Similar to a list but immutable (cannot be changed after variables.
creation). Syntax:
Example: coordinates = (4, 5) Variable = Expression represents the assignment statement.
Set (set):
Represents an unordered collection of unique elements.
Value-based expression on RHS.
Example: unique_numbers = {1, 2, 3}
x = 5 + 3 # Assign the result of the expression (5 + 3) to the
Dictionary (dict):
variable x
Represents a collection of key-value pairs.
Current variable on RHS.
Example: person = {'name': 'Alice', 'age': 25}
y=2
NoneType (None):
y = y + 1 # Increment the value of the variable y by 1
Represents the absence of a value or a null value.
Operation on RHS.
Example: result = None
a = 10
Complex (complex):
b=2
Represents complex numbers with a real and an imaginary
c = a / b # Assign the result of the division operation (a / b)
part.
to the variable c
Example: z = 3 + 4j
9. Write a Python program that takes user input for their name,
age, and favorite color. Print a formatted output using this
information.
ENGINEERING
THANKS FOR VISITING
COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”
Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.
Syntax :
conditional statements are used to control the flow of a if condition1:
program based on certain conditions # Code to be executed if condition1 is true
Conditional statements are also known as decision-making elif condition2:
statements.
# Code to be executed if condition1 is false and condition2 is
The basic conditional statements are if, else, and elif (short
form "else if"). true
else:
# Code to be executed if both condition1 and condition2
The if statement is used to test a condition. If the condition is are false
true, the code inside the if block is executed.
Syntax
if condition:
# Code to be executed if the condition is true
Example:
x = 10 Example
if x > 5: # Example using if-elif-else
print("x is greater than 5") score = 85
if condition2:
# Code to be executed if condition2 is true (nested within
condition1)
if number % 2 == 0:
print("even")
else :
print("odd")
Example:
Q .Write a Python program to check whether number is
for i in range(1, 6):
armstrong or not .
if i == 3:
# Input from the user
continue
n = int(input("Enter a number to check for
print(i)
Armstrong: "))
COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”
Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.
Author : DSALGO
string list
A string is a sequence of characters in Python. list is a mutable, ordered collection of element.
Formed by enclosing characters in quotes. Lists are one of the most versatile & widely used data types in
Python treats single and double quotes equally. Python.
Strings are literal or scalar, treated as a single value in Python
Python treats strings as a single data type. Here are some key characteristics of lists:
Allows easy access and manipulation of string parts.
:
Example :
my_list = [1, 2, 3, "hello", True]
str1 = 'Hello World'
str2 = "My name is khan"
String manipulation in Python
1.Concatenation: Joining two or more strings together. first_element = my_list[0] # Accessing the first elementssing the first
result = str1 + " " + str2 element
print(result) # Output: "Hello World My name is khan"
2.String Formatting: Creating formatted strings with placeholders or sublist = my_list[1:4] # Extracting elements from index 1 to 3
f-strings.
fstr = f"{str1} and {str2}"
print(fstr) my_list[0] = 100 # Modifying an element
3.String Methods: Using built-in string methods to manipulate strings. my_list.append(5) # Adding an element to the end
u_str = str1.upper() #HELLO WORLD my_list.remove("hello") # Removing an element
l_str = str1.lower() # hello world
r_str =str2.replace("khan ", "singh")#my name is singh
length_of_list = len(my_list)
4.Splitting and Joining: Splitting a string into a list of substrings based
on a delimiter, and joining a list of strings into a single string.
splitlist = str1.split("") #['Hello','World'] my_list.sort() # Sorts the list in ascending order
joinlist = "-".join(splitlist) # Hello – World my_list.reverse() # Reverses the list
5.Stripping: Removing leading and trailing whitespace characters
from a string.
my_string = " Hello World " copy() method in list :
stripped_str = my_string.strip() original_list = [1, 2, 3, 4, 5]
print(stripped_str) # Output: "Hello World" copied_list1 = original_list.copy() #method 1
print(copied_list1)
6.Searching: Finding substrings within a string. copied_list2 = list(original_list) # method 2
string = "the quick brown fox jumps over the lazy dog" print(copied_list2)
is_dog = "dog" in string #bool:true or false copied_list3 = original_list[:] # method 3
index =string.find("fox") #return first occurance index print(copied_list3)
Dictionary
dictionary is a mutable, unordered collection of key-value pairs. Why do we use functions :(advantges)
Each key in a dictionary must be unique, and it is associated with 1.Reusability 2. Readability,
a specific value. 3.Maintainability 4. Scoping
Dictionaries are defined using curly braces {} and consist of key-
value pairs separated by commas. Syntax:
Here are some key points about dictionaries:
Creating a Dictionary: # define the function_name
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'} def function_name():
Accessing Values:
# Code inside the function
name = my_dict['name']
age = my_dict['age'] # Optionally, return a value
Modifying Values:
my_dict['age'] = 26 #call the function_name
Adding New Key-Value Pairs: Function_name()
my_dict['gender'] = 'Male'
Removing Key-Value Pairs: Example function without parameters
del my_dict['city']
def greet():
Checking Key Existence:
print("Hello, World!")
is_name_present = 'name' in my_dict
Dictionary Methods: greet() # Calling the greet function
keys = my_dict.keys() Example function with parameters
values = my_dict.values() def add_numbers(a, b):
items = my_dict.items() return a + b
Set
set is an unordered and mutable collection of unique elements. # Calling the add_numbers function
Sets are defined using curly braces {} and can contain various result = add_numbers(5, 7)
data types, such as numbers, strings, and other sets. print("Sum:", result)
Operations performed on sets are union , intersection ,
difference , symmetric difference
Elements of the function
Keyword: def for function header. #Make a table for selection operation
Function Name: Identifies uniquely. print("Select operation:")
Colon: Ends function header. print("1. Add")
Parameters: Values passed at a defining time , e.g., x and y.
print("2. Subtract")
Arguments: Values passed at a calling time , e.g., a and b.
Function Body: Processes arguments. print("3. Multiply")
Return Statement: Optionally returns a value. print("4. Divide")
Function Call: Executes the function, e.g., a = max(8, 6). choice = input("Enter choice (1/2/3/4): ")
Keyword Arguments:Pass values to function by associating num1 = float(input("Enter first number: "))
them with parameter names. num2 = float(input("Enter second number: "))
Syntax : function_name(p1=val1 , p2 =val2)
if choice == '1':
Default Values: can have default values, making them optional
during function calls.
print(num1, "+", num2, "=", add(num1, num2))
Syntax: def function_name(param1=default_value1, elif choice == '2':
param2=default_value2): print(num1, "-", num2, "=", sub(num1, num2))
scope rules in Python [LEGB rule ] elif choice == '3':
Local: Variables within a function; accessible only within that function. print(num1, "*", num2, "=", mult(num1, num2))
Enclosing: Scope for nested functions; refers to the enclosing elif choice == '4':
function's scope. print(num1, "/", num2, "=", div(num1, num2))
Global: Variables at the top level of a module or declared global else:
within a function; accessible throughout the module.
print("Invalid input. Please enter a valid choice.")
Builtin: Outermost scope containing built-in names like print(), sum(),
etc.; available everywhere.
Q. Write a function in find the HCF of given numbers
# Global scope
global_variable = "I am global" def HCF(num1, num2):
def outer_function(): while num2:
# Enclosing scope num1, num2 = num2, num1 % num2
enclosing_variable = "I am in the enclosing scope" return abs(num1)
def inner_function(): # Example usage:
# Local scope number1 = 24
local_variable = "I am in the local scope" number2 = 36
print(local_variable) result = HCF (number1, number2)
print(enclosing_variable) print(f"The HCF of {number1} and {number2} is {result}")
print(global_variable)
print(len(global_variable)) # Using a built-in function
inner_function()
outer_function()
Output :
I am in the local scope
I am in the enclosing scope
I am global
10
COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”
Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.
v
Author : DSALGO
Example:
File handling in Python refers to the manipulation and file = open('example.txt', 'r')
management of files, lines = file.readline()#read first line of the file
such as reading from or writing to them. lines = file.readline()#read second line of the file
Python provides built-in functions and methods to perform
various file operations.
Reads all lines from the file and returns them as a list of strings.
Each string in the list represents a single line from the file,
1. opening file 4.file navigation
including the newline character ('\n').
2. Reading file 5.checking file existance
Useful when you want to iterate over lines in a file or process
3. Writing file
them individually.
Advantages
Example:
1. Versatility 2. ease to use 3. portability
file = open('example.txt', 'r')
4. Flexibility 5.integration
Disadvantages lines = file.readlines() # Reads all lines into a list
1. performance 2.error handling 3. security Risks file.close()
4. Limited File Locking 5. Resource management
Difference b/w read(), readline() , readlines() function:
readline() when you want to read lines one by one.
You can use the open() function to open a file. read() when you want to read a specific number of bytes or the
It takes two parameters: entire file.
file path 2. mode[r,w, a] readlines() when you want to read all lines into a list for further
syntax: processing.
file = open('filename.txt', 'r')
After using read(), it's important to close the file using the close() Writes a string to the file.
method to release system resources If the file is opened in text mode ('t'), you can only write strings
syntax: to it.
file.close() If the file is opened in binary mode ('b'), you can write bytes-like
objects (e.g., bytes or bytearray).
Examples:
read() function in Python is used to read data from a file.
read() function is called on a file object and takes an optional file = open('example.txt', 'w') # Open file in write mode
parameter specifying the number of bytes to read. file.write("Hello, world!") # Write a string to the file
If no size is specified, it reads the entire file. file.close()
Syntax:
file_object.read(size) :
Example 1: Writes a list of strings to the file.
file = open('example.txt', 'r') Each string in the list represents a line, and newline characters
data = file.read() # Reads the entire contents ('\n') must be included if needed.
file.close() Example:
Example 2: (file cursor) lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file = open('example.txt', 'r') file = open('example.txt', 'w')
data1 = file.read(10) # Reads the first 10 bytes file.writelines(lines) # Write multiple lines to the file
data2 = file.read(10) # Reads the next 10 bytes file.close()
file.close()
You can use print() function with file parameter to write to file.
You can also use read() along with splitlines() to read lines from By default, it adds a newline character ('\n') after each print
the file unless specified otherwise
Example: Example:
file = open('example.txt', 'r') file = open('example.txt', 'w')
lines = file.read().splitlines() # Reads lines from the file into a list print("Hello, world!", file=file) # Write to file using print function
file.close() file.close()
with open('filename.txt', 'r') as file: Q.Develop a Python program that reads a text file and prints the
content = file.read() longest line along with its length
# File automatically closed after this block def longest_line(file_name):
try:
with open(file_name, 'r') as file:
Manipulating the file pointer using the seek() function in Python lines = file.readlines()
allows you to move the cursor position within the file longest_length = 0
Examples: longest_line = ""
# Open a file in read mode
with open('example.txt', 'r') as file: for line in lines:
# Read the first 10 bytes line_length = len(line.strip())
data1 = file.read(10) if line_length > longest_length:
longest_length = line_length
# Get the current cursor position
longest_line = line.strip()
position = file.tell()
print("Current position:", position) print(f"The longest line is: '{longest_line}'")
print(f"Its length is: {longest_length} characters")
# Move the cursor to the beginning of the file
except FileNotFoundError:
file.seek(0)
print(f"File '{file_name}' not found.")
# Read the next 20 bytes from the beginning of the file
except Exception as e:
data2 = file.read(20)
print(f"An error occurred: {e}")
Description : longest_line(file_name)
We open a file named example.txt in read mode. def search_string_in_file(file_name, search_string):
We use read(10) to read the first 10 bytes from the file. try:
We use tell() to get the current cursor position. with open(file_name, 'r') as file:
We use seek(0) to move the cursor back to the beginning of the
for line_number, line in enumerate(file, 1):
file.
We use read(20) to read the next 20 bytes from the beginning of if search_string in line:
the file. print(f"Found '{search_string}' in line {line_number}:
Finally, we print the read data. {line.strip()}")
except FileNotFoundError:
Q. Create a Python program that reads the content of a source file
and writes it to a destination file. print(f"File '{file_name}' not found.")
def copy_file(source_file, destination_file): except Exception as e:
try: print(f"An error occurred: {e}")
with open(source_file, 'r') as source:
with open(destination_file, 'w') as destination: # Example usage:
for line in source: file_name = input("Enter the file name: ")
destination.write(line) search_string = input("Enter the string to search: ")
print(f"Content copied from '{source_file}' to '{destination_file}'
search_string_in_file(file_name, search_string)
successfully.")
except FileNotFoundError: Q.Write a Python program to read a text file and count the total
print("One of the files could not be found.") number of words in it.
except Exception as e: Q.Design a Python program that encrypts the contents of a file using
a simple substitution cipher and then decrypts it back to its original
print(f"An error occurred: {e}")
form.
ENGINEERING
THANKS FOR VISITING
COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”
Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.
PYTHON UNIT 5
Abhay Kumar Singh
www.abhaysingh722@gmail.com
NumPy is a powerful library for numerical computing in import numpy as np
Python,
it provides a wide range of built-in functions for various # Create a NumPy array
mathematical operations. arr = np.array([1, 2, 3, 4, 5])
output:
Standard Deviation: 1.4142135623730951
Variance: 2.0
Median: 3.0
Percentile (50th): 3.0
# importing the numpy module
import numpy as np
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5]) import numpy as np
# Print the array # Define two matrices
print("Original Array:", arr) matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
# Perform some basic operations
print("Sum of Array Elements:", np.sum(arr)) # Perform matrix multiplication
print("Mean of Array Elements:", np.mean(arr)) result = np.dot(matrix1, matrix2)
print("Maximum Element in Array:", np.max(arr)) print("Matrix Multiplication Result:")
print("Minimum Element in Array:", np.min(arr)) print(result)
# Reshape the array
reshaped_arr = arr.reshape(1, 5) # Compute matrix determinant
print("Reshaped Array:", reshaped_arr) det = np.linalg.det(matrix1)
print("Determinant of Matrix1:", det)
output:
Original Array: [1 2 3 4 5] # Compute matrix inverse
Sum of Array Elements: 15 inverse = np.linalg.inv(matrix1)
Mean of Array Elements: 3.0
print("Inverse of Matrix1:")
Maximum Element in Array: 5
Minimum Element in Array: 1 print(inverse)
Reshaped Array: [[1 2 3 4 5]]
output:
Matrix Multiplication Result:
[[19 22]
import numpy as np [43 50]]
Determinant of Matrix1: -2.0000000000000004
# Create two NumPy arrays
Inverse of Matrix1:
arr1 = np.array([1, 2, 3]) [[-2. 1. ]
arr2 = np.array([4, 5, 6]) [ 1.5 -0.5]]
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125]) plt.show()
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.show()
import matplotlib.pyplot as plt plt.subplot(1, 2, 1)
import numpy as np
#the figure has 1 row, 2 columns, and this plot is the first plot.
xpoints = np.array([1, 2, 6, 8]) plt.subplot(1, 2, 2)
ypoints = np.array([3, 8, 1, 10]) #the figure has 1 row, 2 columns, and this plot is the second plot.
plt.plot(xpoints, ypoints)
plt.show()
7.scatterplot
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()
With Pyplot, you can use the pie() function to draw pie
charts:
import matplotlib.pyplot as plt
import numpy as np
plt.bar(x,y)
plt.show()
root = tk.Tk()
Tkinter is Python's built-in GUI toolkit for creating desktop entry = tk.Entry(root)
applications. entry.pack()
It offers a wide range of GUI widgets such as buttons, button = tk.Button(root, text="Get Text", command=get_entry_text)
button.pack()
labels, and textboxes.
root.mainloop()
GUI elements are arranged using layout managers like
pack, grid, and place.
Tkinter follows an event-driven programming paradigm,
Text: Multi-line text entry field for longer text input or
responding to user actions with specific functions.
display.
It allows customization of widget appearance and
behavior. import tkinter as tk
Tkinter applications are highly portable across various
operating systems. def get_text_content():
Suitable for small to medium-sized GUI projects and rapid print(text.get("1.0", "end-1c"))
prototyping.
Comprehensive documentation and community support root = tk.Tk()
are available. text = tk.Text(root)
While Tkinter is sufficient for many applications, more text.pack()
advanced libraries like PyQt and wxPython offer additional button = tk.Button(root, text="Get Text",
features and scalability for larger projects. command=get_text_content)
button.pack()
root.mainloop()
import tkinter as tk
def button_clicked():
print("Button clicked!")
root = tk.Tk()
var = tk.IntVar()
root = tk.Tk()
checkbutton = tk.Checkbutton(root, text="Check me",
button = tk.Button(root, text="Click Me", command=button_clicked)
variable=var)
button.pack()
checkbutton.pack()
root.mainloop()
root.mainloop()
: text or image that provides information or : Group of radio buttons where only one
instructions to the user. option can be selected at a time.
import tkinter as tk
root = tk.Tk()
root.title("Frame Example")
# Create a frame
frame = tk.Frame(root, width=200, height=100, bg="lightblue")
frame.pack()
root.mainloop()
import tkinter as tk
def menu_command():
print("Menu command executed")
root = tk.Tk()
# Create a menu
menu_bar = tk.Menu(root)
COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”
Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.