Python Final Noteu3to5
Python Final Noteu3to5
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also
provides triple-quotes to represent the string, but it is generally used for multiline string or
docstrings.
Output –
Hello
Python
Hello
Python
Triple quotes are generally used for represent
the multiline or docstring
String Slicing
● In Python, the String Slicing method is used to access a range of characters in
the String. Slicing in a String is done by using a Slicing operator, i.e., a colon (:).
● One thing to keep in mind while using this method is that the string returned after
slicing includes the character at the start index but not the character at the last
index.
Reassigning Strings
As Python strings are immutable in nature, we cannot update the
existing string. We can only assign a completely new value to the variable with the same
name.
Example 1
Output:
A character of a string can be updated in Python by first converting the string into a Python
List and then updating the element in the list. As lists are mutable in nature, we can update
the character and then convert the list back into the String.
String2 = ''.join(list1)
#Method 2
String3 = String1[0:2] + 'p' + String1[3:] print(String3)
Example 2
Output:
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters from
the string. But we can delete the entire string using the del keyword.
Output:
Output:
● Escape sequences start with a backslash and can be interpreted differently. If single
quotes are used to represent a string, then all the single quotes present in the string
must be escaped and the same is done for Double Quotes.
Example
String1= "C:\\Python\\Geeks\\" print(String1)
Formatting of Strings
Strings in Python can be formatted with the use of format( ) . Format method in String
contains curly braces {} as placeholders which can hold arguments according to position or
keyword to specify the order.
Output
● The list is a sequence data type which is used to store the collection
of data.
● In lists the comma (,)and the square brackets [enclose the List's items] serve
as separators.
● Lists need not be homogeneous always which makes it the most powerful
tool in Python.
● A single list may contain DataTypes like Integers, Strings, as well as Objects.
● Lists are mutable, and hence, they can be altered even after their creation.
A list may contain duplicate values with their distinct positions and hence, multiple distinct
or duplicate values can be passed as a sequence at the time of list creation.
Example-
List1=[“physics”, “Maths”,34,15.5]
List2=[2,3,5,10]
List Indexing and Splitting
The indexing procedure is carried out similarly to string processing. The slice operator [] can
be used to get to the List's components.
We can get the sub-list of the list using the following syntax.
o Within a start, the step is used to skip the nth element: stop.
Example-
List1=[0,1,2,3,4]
List1[1:3:1]= [1,2]
List = []
print("Initial blank List: ")
print(List)
List.append(1) List.append(2)
List.insert(2, 12)
List.extend([8, 'Geeks'])
print("List after performing Extend Operation: ") print(List)
Removing Elements from the List
Elements can be removed from the List by using the built-in remove() function but an
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
List.remove(5) List.remove(6)
pop() function can also be used to remove and return an element from the list, but by
default it removes only the last element of the list, to remove an element from a specific
position of the List, the index of the element is passed as an argument to the pop() method.
List = [1, 2, 3, 4, 5]
List.pop()
print("List after popping an element: ")
print(List)
List.pop(2)
print("\nList after popping a specific element: ") print(List)
List out some in-built function in python List
Lecture-14 Python Tuple
Note: Creation of Python tuple without the use of parentheses is known as Tuple
Packing.
Note: We can change any python collection like (list, tuple, set) and string into other data
type like tuple, list and string. But cannot change into and float to any python collection.
For example: int cannot change into list or vice-versa.
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple
gets deleted by the use of del() method.
The zip() is an inbuilt function in python. It takes items in sequence from a number of
collections to make a list of tuples, where each tuple contains one item from each collection.
The function is often used to group items from a list which has the same index.
Example:
A=[1,2,
3]
B=’XYZ’
Note: if the sequences are not of the same length then the result of zip() has the length of
the shorter sequence.
A=’abcd’
B=[1,2,3]
Res=list(zip(A,B))
print(Res)
Output:
[(‘a’,1),(‘b’,2),(‘c’,3)]
The * operator is used within the zip() function. The * operator unpacks a sequence into
positional arguments.
X=[(‘apple’,90000),(‘del’,60000),(‘hp’,50000)]
Laptop,prize=zip(*X)
print(Laptop)
print(prize)
Output:
(‘apple’,’del’,’hp’)
(90000,60000,50000)
Python program to find the maximum and minimum K elements in a tuple
Output
Lecture-15 String ManipulationMethods
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it
was found
index() Searches the string for a specified value and returns the position of where it
was found
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
split() Splits the string at the specified separator, and returns a list
startswith( Returns true if the string starts with the specified value
)
title() Converts the first character of each word to upper case
swapcase() Swaps cases, lower case becomes upper case and vice versa
2. WAP to accept a string & replace all spaces by # without using string method.
3. WAP to accept two strings and then display the common words
str1=input("Enter string1:")
str2=input("Enter string2:")
for i in str1.split():
if i in str2.s
Lecture-16 Python Set
set is an unordered collection of data items which does not contain duplicate values. Every
set element is unique and must be immutable (cannot be changed). However, a set itself is
mutable. Elements of set are enclosed inside a pair of curly brackets
{}.
We can add and remove items from the set. But cannot replace item as it does not support
indexing of data items.
Outpu
t:
apple
banan
a
cherry
NOTE: Lists cannot be added to a set as elements because Lists are not hashable whereas
Tuples can be added because tuples are immutable and hence Hashable.
● Elements can be removed from the Set by using the built-in remove()
function but a KeyError arises if the element doesn’t exist in the set.
S1={1,2,3,4,5}
S1.remove(2
) print(S1)
Output:
{1,3,4,5}
S1={1,2,3,4}
S2={1,2,3,4,5}
print(S1.issubset(S2))
Output:
True
print(S2.issuperset(S1))
Output:
True
>>> S1={1,2,3,4,5}
S2={5,6,7}
print(S1.union(S2)) # print(S1|S2) Output:
{1,2,3,4,5,6,7}
>>>
print(S1.intersection(S2)) # print(S2&S2)
Output:
{5}
>>>
Output:
{1,2,3,4,6,7}
● Dictionary in Python is a collection of keys values, used to store data values like a
map, which, unlike other data types which hold only a single value as an element.
● Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.
● Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such
as strings, numbers, or tuples.
More than one entry per key is not allowed. Which means no duplicate key is allowed. When
duplicate keys are encountered during assignment, the last assignment wins.
Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary
keys but something like ['key'] is not allowed.
In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets. . Following is a simple example −
dict['Name']:Zara dict['Age']: 7
There is also a method called get() that will also help in accessing the element from a
dictionary.This method accepts key as argument and returns the value.
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing
entry, or deleting an existing entry as shown below in the simple example −
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
The items of the dictionary can be deleted by using the del keyword
Output
Dictionary methods
Method Description
Q1. What do you mean by function? Give the syntax to define the function with an example.
Master code
s=0
Output:
Function calling is called driver code and function definition with block of statements is called master code
Q2. Differentiate between argument and parameter.
1. Formal parameter
2. Actual Parameter
Formal parameters are those written in function definition and actual
parameters are those written in function calling.
Formal parameters are called argument.
Arguments are the values that are passed to function definition.
Example:
Def fun(n1):
Print(n1)
a=10
fun(a)
here n1 is argument and a is parameter.
python. Ans:
def display(a='hello',b='world'): # you can have only default arguments
also print(a,b)
display()
Output:
hello world
print(d)
def display(a,b,c=10):
d=a+b+c
print(d)
display(2,
3)
Output:
15
def
display(*arg)
: for i in arg:
print(i)
display(‘hello’,’world’,’python’)
Output:
hello
world
pytho
Q5. Discuss return statement. Can we return more than one values with return
statement? Ans:
The Return Statement:The return statement is used to return a value from the function to a
calling function. It is also used to return from a function i.e. break out of the function.
Example:
square,cube=compute(2)
cube=lambda x:
x*x*x print(cube(2))
Output:
Note:
● The statement cube=lambda x: x*x*x creates a lambda function called cube, which
takes a single argument and returns the cube of a number.
variable. Ans:
1. Program to access a local variable outside a functions
def demo():
q=10
demo()
Output:
defined
2. Program to read global variable from a local scope
def demo():
print(s)
demo()
Output:
I love python
def demo():
print(s)
Output:
I love python
I love programming
Global statement is used to define a variable defined inside a function as a global variable. To
make local variable as global variable, use global keyword
Example:
a=20
def display():
global a
a=30
print(‘value of a is’,a)
display()
Output:
value of a is 30
Note:
Since the value of the global variable is changed within the function, the value
of ‘a’ outside the function will be the most recent value of ‘a’
def factorial(n):
return 1
return n * factorial(n-1)
print(factorial(5))
Output:
120
Note: Recursion ends when the number n reduces to 1. This is called base condition. Every
recursive function must have a base condition that stops the recursion or else the function
calls itself infinitely.
Ans:
def fibonacci(n):
return n
else:
return(fibonacci(n-1) +
fibonacci(n-2)) n = int(input("Enter
sequence:")
for i in range(n):
fibonacci(i),
Ans:
def gcd(a,b):
if(b==0):
return
else:
return gcd(b,a%b)
b=int(input("Enter second
number:")) GCD=gcd(a,b)
print(GCD)
Q10. Program to find the sum of elements in a list recursively.
Ans:
def sum_arr(arr,size):
if (size == 0):
return 0 else:
for i in range(0,n):
print(b)
Q11. Program to check whether a string is a palindrome or not using recursion. Ans:
def is_palindrome(s):
else:
if s[0] == s[-1]:
if(is_palindrome(a)==True):
Unit-4
Lecture21 :- File handling in Python
Introduction to File Handling
Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file
handling options, to operate on files.
The concept of file handling has stretched over various other languages, but the implementation is either complicated
or lengthy, like other concepts of Python, this concept here is also easy and short. Python treats files differently as text
or binary and this is important. Each line of code includes a sequence of characters, and they form a text file. Each line
of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline
character. It ends the current line and tells the interpreter a new one has begun.
Advantages of File Handling in Python
● Versatility: File handling in Python allows you to perform a wide range of operations, such as creating, reading,
writing, appending, renaming, and deleting files.
● Flexibility: File handling in Python is highly flexible, as it allows you to work with different file types (e.g. text files,
binary files, CSV files, etc.), and to perform different operations on files (e.g. read, write, append, etc.).
● User–friendly: Python provides a user-friendly interface for file handling, making it easy to create, read, and
manipulate files.
● Cross-platform: Python file-handling functions work across different platforms (e.g. Windows, Mac, Linux),
allowing for seamless integration and compatibility.
Python provides built-in functions and methods to perform various file operations like reading, writing, and updating
files
Python File Open
Before performing any operation on the file like reading or writing, first, we have to open that file. For this, we should
use Python’s inbuilt function open() but at the time of opening, we have to specify the mode, which represents the
purpose of the opening file.
f = open(filename, mode)
Eg:- file = open('example.txt', 'r') # Opens the file in read mode
The mode argument is a string that specifies the mode in which the file is opened:
'r' for reading (default)
'w' for writing (creates a new file or truncates the file first)
'x' for exclusive creation (fails if the file already exists)
'a' for appending (creates a new file if it does not exist)
'b' for binary mode
r+: To read and write data into the file. The previous data in the file will be overridden.
w+: To write and read data. It will override existing data.
a+: To append and read data from the file. It won’t override existing data.
Lecture22:- Discussed about How use read functions like read(), readline(), readlines().
Reading from a File
Once the file is opened, you can read its content using methods like read(), readline(), or readlines():
# Read the entire file
content = file.read()
print(content)
print(lines)
file.close() # Always close the file when you're done with it
Output:
Hello world
Welcome CSE
123 456
Q:- In this example, we will see how we can read a file using the with statement in Python.
# Python code to illustrate with()
with open("geeks.txt") as file:
data = file.read()
print(data)
Q:- Another way to read a file is to call a certain number of characters like in the following code the interpreter will
read the first five characters of stored data and return it as a string:
# Python code to illustrate read() mode character wise
file = open("geeks.txt", "r")
print (file.read(5))
Q:-We can also split lines while reading files in Python. The split() function splits the variable when space is
encountered. You can also split using any characters as you wish.
word = line.split()
print (word)
OUTPUT:-
['Hello', 'world']
['CSE', ‘Welcome’]
['123', '456']
Lecture23 :- Writing files in Python
Writing to a File
To write to a file, you need to open it in a write ('w'), append ('a'), or update ('+') mode. Then, use the write() or
writelines() methods:
Syntax:-
file = open('example.txt', 'w') # Open the file in write mode
file.write('Hello, World!\n') # Write a string to the file
lines = ['First line.\n', 'Second line.\n']
file.writelines(lines) # Write a list of strings to the file
file.close()
Closing a File
It's important to close the file when you're done with it to free up system resources. Use the close() method:
file.close()
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)
def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)
Output:
1. offset: The number of bytes to move the file pointer. Positive values move the pointer forward, negative values
move it backward.
2. from_what: This argument specifies the reference point for the offset. It can take one of three values:
● 0 (default): The beginning of the file.
● 1: The current file position.
● 2: The end of the file.
Example:-
Example 1: Let’s suppose we have to read a file named “CSE.txt” which contains the following text:
"Code is like humor. When you have to explain it, it’s bad."
f = open("CSE.txt", "r")
print(f.readline())
f.close()
Output:
20
When you have to explain it, it’s bad.
Example 2: Seek() function with negative offset only works when file is opened in binary mode. Let’s suppose the
binary file contains the following text.
b'Code is like humor. When you have to explain it, its bad.'
f = open("data.txt", "rb")
f.close()
Output:
47
, its bad.
# Move the file pointer to the 10th byte from the beginning
file.seek(10)
# Move the file pointer 5 bytes backward from the current position
file.seek(-5, 1)
In this example:
The first seek(10) call moves the file pointer to the 10th byte from the beginning of the file.
The second seek(-5, 1) call moves the file pointer 5 bytes backward from the current position.
The third seek(0, 2) call moves the file pointer to the end of the file.
It's important to note that seeking beyond the end of the file when writing will cause the file to be extended with
null bytes up to the specified position. Therefore, you can seek beyond the end of the file when writing to append
data. However, seeking beyond the end of the file when reading will result in an error.
Lecture25:- File of Operations
Using a file of operations typically involves reading from or writing to a file that contains a series of instructions or data
manipulations. These operations can vary widely depending on the context, such as programming, data processing, or
system administration. Let's break down how to approach this in a few different scenarios:
2. Data Processing
In data processing, a file of operations might list data transformations or analyses to perform on a dataset. This could
involve:
Performing Operations:
For each operation, apply the corresponding data transformation. This might involve filtering data, performing
calculations, or aggregating information.
After performing an operation, you might need to write the result to a file or prepare it for the next operation.
3. System Administration
For system administration, a file of operations might contain a list of system commands or configuration changes to
apply to a server or network of computers.
Automating Tasks:
Use a scripting language suitable for system administration (such as Bash for Linux/Unix systems or PowerShell for
Windows).
Read each operation from the file and use the script to execute the corresponding system command or change the
system configuration.
General Tips
Error Handling: Always include error handling to manage unexpected or malformed operations gracefully.
Logging: Keep a log of operations performed and any errors or warnings generated. This is invaluable for debugging
and verifying that operations have been executed correctly.
Security: Be cautious when executing operations from a file, especially if the operations involve system commands or
could impact data integrity. Validate and sanitize the operations to prevent security vulnerabilities.
By breaking down the process into manageable steps and considering the context in which you're using the file of
operations, you can effectively implement and automate a wide range of tasks.
print,Hello World!
add,3,5
You want to read these operations and execute them. Let's assume add operation sums the numbers.
def handle_print(args):
print(*args)
def handle_add(args):
result = sum(map(int, args))
print(result)
2. Data Processing
Imagine you have a CSV file data.csv and an operations file data_operations.txt that contains operations like filter, >10
and average. For simplicity, let's handle a single operation: filtering values greater than 10.
Program:-
import pandas as pd
# Assuming a simple CSV file with one column of integers
df = pd.read_csv('data.csv')
3. System Administration
For system administration, let's automate the creation of backup files. Assume an operations file system_ops.txt with
content like backup,/path/to/file.
import shutil
import os
def backup_file(file_path):
if os.path.exists(file_path):
shutil.copy(file_path, f"{file_path}.backup")
print(f"Backup created for {file_path}")
else:
print(f"File does not exist: {file_path}")
1. Recursive Approach
The recursive approach directly implements the mathematical definition of the Fibonacci sequence. However, it's not
efficient for large numbers due to repeated calculations and a high recursive call stack usage.
def fibonacci_recursive(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
# Example usage:
n = 10
print(f"The {n}th Fibonacci number (recursive) is: {fibonacci_recursive(n)}")
2. Iterative Approach
The iterative approach uses a loop to calculate the Fibonacci numbers up to n. This method is much more efficient
than recursion for large numbers.
def fibonacci_iterative(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# Example usage:
n = 10
print(f"The {n}th Fibonacci number (iterative) is: {fibonacci_iterative(n)}")
Lecture26:- Python Program(Matrix Addition)
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
result_matrix[i][j] = matrix1[i][j] + matrix2[i][j]
return result_matrix
# Example usage
print("Resultant Matrix:")
Program:-
Transposing a matrix means flipping a matrix over its diagonal, turning the matrix's rows into columns and columns
into rows. This operation is common in mathematics and programming, especially in the context of linear algebra and
data manipulation.
Basic Python Loops: Good for educational purposes and environments where external dependencies are discouraged
or not allowed. However, manually coding the transpose operation can be error-prone for complex data structures.
Using NumPy: Offers a simple, efficient, and less error-prone method for transposing matrices. Highly recommended
for scientific computing, data analysis, and any application requiring manipulation of large numerical datasets.
def transpose_matrix(matrix):
# Initialize the transposed matrix with zeros
transposed = [[0 for _ in range(len(matrix))] for _ in range(len(matrix[0]))]
return transposed
# Example usage
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed_matrix = transpose_matrix(matrix)
print("Original Matrix:")
for row in matrix:
print(row)
print("\nTransposed Matrix:")
for row in transposed_matrix:
print(row)
Lecture26:- Python Program (Identity Matrix)
def identity_matrix(n):
"""Create an n x n identity matrix."""
return [[1 if i == j else 0 for j in range(n)] for i in range(n)]
# Example usage
n=4
print("Identity Matrix of size", n)
for row in identity_matrix(n):
print(row)
Parameters:
number (int): The number for which the multiplication table is to be printed.
range_limit (int): The range up to which the table should be printed.
"""
for i in range(1, range_limit + 1):
print(f"{number} x {i} = {number * i}")
def main():
# Prompt the user for input
number = int(input("Enter the number for the multiplication table: "))
range_limit = int(input("Enter the range up to which to print the table: "))
def is_leap_year(year):
"""
Returns True if the given year is a leap year, False otherwise.
"""
# Year is divisible by 4
if year % 4 == 0:
# Year is not divisible by 100 unless it's also divisible by 400
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def main():
year = int(input("Enter a year: "))
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. For example, 28 is
a perfect number because its divisors are 1, 2, 4, 7, and 14, and
1+2+4+7+14=28
Below is a Python program that checks if a given number is a perfect number. The program defines a function to
calculate the sum of divisors of a number and then checks if this sum equals the number itself.
def is_perfect_number(number):
if number < 1:
return False
sum_of_divisors = 0
# Check for divisors of the number
for possible_divisor in range(1, number):
if number % possible_divisor == 0:
sum_of_divisors += possible_divisor
# Compare the sum of divisors (excluding the number itself) to the number
return sum_of_divisors == number
def main():
number = int(input("Enter a number: "))
if is_perfect_number(number):
print(f"{number} is a perfect number.")
else:
print(f"{number} is not a perfect number.")
An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each
raised to the power of the number of digits. For example, 153 is an Armstrong number because it has 3 digits, and
13 +53+33 =153
To write a Python program that checks if a given number is an Armstrong number, you need to:
def is_armstrong_number(number):
# Convert the number to a string to easily iterate over its digits
str_number = str(number)
# Calculate the number of digits
num_digits = len(str_number)
# Calculate the sum of digits raised to the power of the number of digits
sum_of_powers = sum(int(digit) ** num_digits for digit in str_number)
def main():
number = int(input("Enter a number: "))
if is_armstrong_number(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
There is a file named Input .Txt. Enter some positive numbers into the file named Input.Txt .Read the contents of the
file and if it is an odd number write it to ODD.Txt and if the number is even , write it to EVEN,Txt
Write a python program to read the content of a file and then create a file COUNT.Txt to write the numbers of letters
and digits of the readed content from the given file .
Unit – 5
Here are some widely used Python packages for various purposes:
NumPy: Numerical computing and array operations.
Pandas: Data analysis and manipulation.
Requests: HTTP requests for humans.
Matplotlib
Matplotlib is a popular Python library used for creating static, animated, and interactive visualizations in Python. It
provides a wide range of plotting tools and features for creating high-quality graphs, charts, and plots.
Here are some of the key components and functions provided by Matplotlib:
Key Components:
Figure: The entire window or page where the plots and charts are drawn.
Axes: The area where data is plotted. It includes the X-axis, Y-axis, and the plot itself.
Axis: The X-axis and Y-axis, which define the scale and limits of the plot.
Artist: Everything that is drawn on the figure (such as lines, text, shapes) is an artist.
Installation:-
python -m pip install -U matplotlib
Lecture26(B):- Matplotlib
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data
visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by
John Hunter in 2002.
Types of Matplotlib
Matplotlib comes with a wide variety of plots. Plots help to understand trends, and patterns, and to make correlations.
They’re typically instruments for reasoning about quantitative information.
Some of the sample plots are covered here.
Matplotlib Line Plot
Matplotlib Bar Plot
By importing the matplotlib module, defines x and y values for a plotPython, plots the data using the plot() function
and it helps to display the plot by using the show() function . The plot() creates a line plot by connecting the points
defined by x and y values.
Eg:-
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot
plt.plot(x, y)
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot the bar
plt.bar(x, y)
# function to show the plot
plt.show()
# Y-axis values
y = [10, 5, 8, 4, 2]
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Data
x = [1, 2, 3, 4, 5]
y1, y2 = [10, 20, 15, 25, 30], [5, 15, 10, 20, 25]
# Area Chart
plt.fill_between(x, y1, y2, color='skyblue', alpha=0.4, label='Area 1-2')
plt.plot(x, y1, label='Line 1', marker='o')
plt.plot(x, y2, label='Line 2', marker='o')
Numpy:-
Features of NumPy
NumPy has various features including these important ones:
● A powerful N-dimensional array object
● Sophisticated (broadcasting) functions
● Tools for integrating C/C++ and Fortran code
● Useful linear algebra, Fourier transform, and random number capabilities
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
Eg:-
import numpy as np
To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be converted
into an ndarray:
Dimensions in Arrays
NumPy arrays can have multiple dimensions, allowing users to store data in multilayered structures.
Dimensionalities of array:
Name Example
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
Example:-
import numpy as np
print(arr)
3-D arrays
Example:-
import numpy as np
print(arr)
Lecture28: - Python Pandas
Introduction to Pandas
Pandas is a name from “Panel Data” and is a Python library used for data manipulation and analysis.
Pandas provides a convenient way to analyze and clean data. The Pandas library introduces two new data structures
to Python - Series and DataFrame, both of which are built on top of NumPy.
Install Pandas
To install pandas, you need Python and PIP installed in your system.
If you have Python and PIP installed already, you can install pandas by entering the following command in the
terminal:
pip install pandas
Import Pandas in Python We can import Pandas in Python using the import statement.
import pandas as pd
What can you do using Pandas?
Pandas are generally used for data science but have you wondered why? This is because pandas are used in
conjunction with other libraries that are used for data science. It is built on the top of the NumPy library which means
that a lot of structures of NumPy are used or replicated in Pandas. The data produced by Pandas are often used as
input for plotting functions of Matplotlib, statistical analysis in SciPy, and machine learning algorithms in Scikit-learn.
Here is a list of things that we can do using Pandas.
● Data set cleaning, merging, and joining.
● Easy handling of missing data (represented as NaN) in floating point as well as non-floating point data.
● Columns can be inserted and deleted from DataFrame and higher dimensional objects.
● Powerful group by functionality for performing split-apply-combine operations on data sets.
● Data Visulaization
Pandas Series
A Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python
objects, etc.). The axis labels are collectively called indexes.
Pandas Series is nothing but a column in an Excel sheet. Labels need not be unique but must be a hashable type. The
object supports both integer and label-based indexing and provides a host of methods for performing operations
involving the index.
Example 1:
# import pandas as pd
import pandas as pd
# simple array
data = [1, 2, 3, 4]
ser = pd.Series(data)
print(ser)
Example 2:-
# import pandas as pd
import pandas as pd
# import numpy as np
import numpy as np
# simple array
data = np.array(['g','e','e','k','s'])
ser = pd.Series(data)
print(ser)
DataFrame
Pandas DataFrame is a two-dimensional data structure with labeled axes (rows and columns).
Creating Data Frame
In the real world, a Pandas DataFrame will be created by loading the datasets from existing storage, storage can be
SQL Database, CSV file, or an Excel file. Pandas DataFrame can be created from lists, dictionaries, and from a list of
dictionaries, etc.
Example:-
import pandas as pd
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks']
root.mainloop()
OUTPUT
Lecture30&31 :- Tkinter Introduction and programming
Tkinter
Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below.
● Tkinter− Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this
option in this chapter.
● wxPython− This is an open-source Python interface for wxWindow shttp://wxpython.org.
● JPython− JPython is a Python port for Java which gives Python scripts seamless access to Java class
libraries on the local machine http://www.jython.org
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to
create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps .
● Import the Tkinter module.
● Create the GUI application main window.
● Add one or more of the above-mentioned widgets to the GUI application.
● Enter the main event loop to take action against each event triggered by the user.
Geometry Management
All Tkinter widgets have access to specific geometry management methods, which have the purpose of organizing
widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes: pack, grid, and
place.
● The pack() Method− This geometry manager organizes widgets in blocks before placing them in the parent
widget.
● The grid() Method − This geometry manager organizes widgets in a table-like structure in the parent widget.
● The place() Method − This geometry manager organizes widgets by placing them in a specific position in the
parent widget (absolute positions).
WIDGETS
Label
ENTRY
● from tkinter import *
● top = Tk()
● L1 = Label(top, text = "User Name")
● L1.pack( side = LEFT)
● E1 = Entry(top, bd = 5)
● E1.pack(side = RIGHT)
● top.mainloop()
Output:
button
● # Code to demonstrate a button
● import Tkinter as tk
● root=tk.Tk()
● l=tk.Label(root,text="name",fg="red",bg="lightgreen")
● l.grid(row=0,column=0)
● e=tk.Entry(root)
● e.grid(row=0,column=1)
● b=tk.Button(root,text="click",fg="red",bg="blue")
● b.grid(row=1,column=1)
● root.mainloop()
OUTPUT
Lecture 32:&33 -Tkinter Widgets and its example
CheckButton
from tkinter import *
import tkinter
top = Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
def show():
print(CheckVar1.get())
print(CheckVar2.get())
C1.pack()
C2.pack()
B1.pack()
top.mainloop()
OUTPUT
label = Label(root)
label.pack()
root.mainloop()
OUTPUT
MessageBox (Showinfo)
from tkinter import *
Frame
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = "Brown", fg="brown")
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text = "Blue", fg = "blue")
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text = "Black", fg = "black")
blackbutton.pack( side = BOTTOM)
root.mainloop()
OUTPUT:-
Important Ques-CO-5
Describe the need for catching exceptions using try and except statements.
What do you understand by module and package in Python.
Write a python program to plot the algebraic equation: 10x + 14.
What is a tkinter in Python and its advantages.
What are Widgets in Tkinter
Lecture34:- Programming Questions
Python Program to exchange the values of two numbers without using a temporary variable.
Python Program to take the temperature in Celsius and convert it to Fahrenheit.
Python Program to read two numbers and print their quotient and remainder.
Python Program to find the area of a triangle given all three sides.
Python Program to read height in centimeters and then convert the height to feet and inches
Python Program to compute simple interest given all the required values.
Python Program to check whether a given year is a leap year or not.
Python Program to take in the marks of 5 subjects and display the grade.
Python Program to check if a number is an Armstrong number.
Python Program to find the sum of digits in a number.
Python Program to print odd numbers within a given range.
Python Program to check whether a given number is a palindrome.
Python Program to print all numbers in a range divisible by a given number.
Python Program to read a number n and print an inverted star pattern of the desired size.
Python Program to find the sum of first N Natural Numbers.
Python Program to read a number n and print and compute the series “1+2+…+n=”.
Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N.
Python Program to find the sum of series: 1 + x^2/2 + x^3/3 + … x^n/n.
Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N.
Python program to find whether a number is a power of two.
Python Program to find the second largest number in a list.
Python Program to put the even and odd elements in a list into two different lists.
Python Program to merge two lists and sort it.
Python Program to find the second largest number in a list using bubble sort.
Python Program to find the intersection of two lists.
Python Program to sort a list of tuples in increasing order by the last element in each tuple.
Python Program to remove the duplicate items from a list.
Python Program to replace all occurrences of ‘a’ with ‘$’ in a string.
Python Program to detect if two strings are anagrams.
Python Program to count the number of vowels in a string.
Python Program to calculate the length of a string without using library functions.
Python Program to check if a string is a palindrome or not.
Python Program to check if a substring is present in a given string.
Python Program to add a key-value pair to a dictionary.
Python Program to read a file and capitalize the first letter of every word in the file