Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Python Final Noteu3to5

Uploaded by

atifuddin70
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Python Final Noteu3to5

Uploaded by

atifuddin70
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

UNIT 3

Lecture 12- Python String

● A String is a data structure in Python that represents a sequence of characters.


● It is an immutable data type, meaning that once you have created a string, you cannot
change it.
● Strings are used widely in many different applications, such as storing and manipulating
text data, representing names, addresses, and other types of data that can be
represented as text.

What is a String in Python?


Python string is the collection of the characters surrounded by single quotes, double quotes, or
triple quotes. Python does not have a character data type, a single character is simply a string
with a length of 1.
Creating String in Python

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

Accessing characters in Python String


● In Python, individual characters of a String can be accessed by using the method
of Indexing.
● Indexing allows negative address references to access characters from the back of
the String, e.g. -1 refers to the last character, -2 refers to the second last character,
and so on.
● While accessing an index out of the range will cause an IndexError. Only Integers
are allowed to be passed as an index, float or other types that will cause a
TypeError.

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.

Consider the following example.

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.

String1 = "Hello, I'm a Geek" Output

print("Initial String: ")


print(String1)
#Method 1
list1 = list(String1) list1[2] = 'p'

String2 = ''.join(list1)

print("\nUpdating character at 2nd Index: ") print(String2)

#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:

Now we are deleting entire string.

Output:

Escape Sequencing in Python


● While printing Strings with single and double quotes in it
causes SyntaxError because String already contains Single and Double Quotes and
hence cannot be printed with the use of either of these.

● 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.

String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life') print("\nPrint


String in order of Keywords: ") print(String1)

Output

Print String in order of Keywords: Life For


Geeks
Lecture-13 Python List & List Slicing

● 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.

Creating a List in Python


Lists in Python can be created by just placing the sequence inside the square brackets[].

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.

The index ranges from 0 to length -1.

We can get the sub-list of the list using the following syntax.

o The beginning indicates the beginning record position of the rundown.

o The stop signifies the last record position of the rundown.

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]

Adding Elements to a Python List

Method 1: Using append() method -


Only one element at a time can be added to the list by using the append() method

List = []
print("Initial blank List: ")
print(List)

List.append(1) List.append(2)

print("List after Addition of Three elements: ")


print(List)

Method 2: Using insert() method-


append() method only works for the addition of elements at the end of the List, for
the addition of elements at the desired
position, insert() method is used.

List.insert(2, 12)

print("List after performing Insert Operation: ")


print(List)

Method 3: Using extend() method-


Extend( ) method is used to add multiple elements at the same time at the end of
the list.

List.extend([8, 'Geeks'])
print("List after performing Extend Operation: ") print(List)
Removing Elements from the List

Method 1: Using remove() method

Elements can be removed from the List by using the built-in remove() function but an

Error arises if the element doesn’t exist in the list.

List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
List.remove(5) List.remove(6)

print("List after Removal of two elements: ") print(List)

Method 2: Using pop() method

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.

Note- Printing of Tuple after deletion results in an Error.


Python

Traceback (most recent call last):

File “/home/efa50fd0709dec08434191f32275928a.py”, line 7, in


print(Tuple1)
NameError: name ‘Tuple1’ is not defined
The zip() Function

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’

Res=list(zip(A,B))# list of tuples print(Res)


Output:

[(1, 'X'), (2, 'Y'), (3, 'Z')]

We can change into tuple of tuples

Res=tuple(zip(A,B))# tuple of tuples

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 Inverse zip(*) Function

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

capitalize() Converts the first character to upper case

count() Returns the number of times a specified value occurs in a string

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

format() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it
was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

islower() Returns True if all characters in the string are lower case

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title


isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

split() Splits the string at the specified separator, and returns a list

replace() Returns a string where a specified value is replaced with a specified


value

startswith( Returns true if the string starts with the specified value
)
title() Converts the first character of each word to upper case

upper() Converts a string into upper case

lower() Converts a string into lower case

swapcase() Swaps cases, lower case becomes upper case and vice versa

Programs on Python Strings

1. WAP to display unique words from the string

str=input("Enter string:") l=str.split()


l1=[]
for i in l:
if i not in l1:
l1.append(i)
str=" ".join(l1)
print(str)

2. WAP to accept a string & replace all spaces by # without using string method.

str=input("Enter string:") str1=""


for i in str:
if i.isspace():
str1+="#"
else:
str1+=i
print(“output is”,str1)

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.

Empty set is created by:


A=set()
print(
A)
Outpu
t:
Set()

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.

Removing elements from the Set

Using remove() method or discard() method:

● 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.

● To remove elements from a set without KeyError, use discard(), if the


element doesn’t exist in the set, it remains unchanged.
Note: If the set is unordered then there’s no such way to determine which

element is popped by using the pop() function.

Python Set in -built functions:


Examples:

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}

>>>

print(S1.difference(S2)) # print(S1-S2) Output:


{1,2,3,4}
>>>
print(S1.symmetric_difference(S2)) # print(S1^S2)

Output:
{1,2,3,4,6,7}

Lecture 17 List manipulating method


Lecture-18 /19 Python Dictionary and its manipulation method

● 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.

Properties of Dictionary Keys


There are two important points to remember about dictionary keys −

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.

Accessing value to a dictionary

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', 'Age': 7, 'Class': 'First'}


print("dict['Name']:",dict['Name'])
print("dict['Age']: ", dict['Age'])
When the above code is executed, it produces the following result −

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.

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} print("Accessing a


element using get:") print(Dict.get(3))

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
}

car.update({"color": "White"}) print(car)

Deleting Elements using del Keyword

The items of the dictionary can be deleted by using the del keyword
Output

Dictionary ={1: 'Geeks', 'name': 'For', 3:


'Geeks'} Data after deletion Dictionary={'name': 'For', 3: 'Geeks'}

Built-in Dictionary Functions & Methods


Python includes the following dictionary functions –

Sr.No. Function with Description


cmp(dict1, dict2)
1
Compares elements of both dict.
len(dict)
2 Gives the total length of the dictionary. This would be equal to the number
of items in the dictionary.
str(dict)
3
Produces a printable string representation of a dictionary
type(variable)
4 Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.

Dictionary methods

Method Description

Remove all the elements from the dictionary


dic.clear()

dict.copy() Returns a copy of the dictionary

dict.get(key, default = “None”) Returns the value of specified key


Returns a list containing a tuple for
dict.items()
each key value pair

dict.keys() Returns a list containing dictionary’s keys

Updates dictionary with specified key- value


dict.update(dict2)
pairs

dict.values() Returns a list of all the values of dictionary

pop() Remove the element with specified key

popItem() Removes the last inserted key-value pair

set the key to the default value if the key is


dict.setdefault(key,default= “None”)
not specified in the dictionary

returns true if the dictionary contains the


dict.has_key(key)
specified key.

used to get the value specified for the passed


dict.get(key, default = “None”)
key.
Lecture-20 Function

Q1. What do you mean by function? Give the syntax to define the function with an example.

Program for sum of digits from range x to y def sum(x,y): –>

Master code

s=0

for i in range(x,y+1): s-s+i

print(“sum of integers from x to y :”,s)

sum(50,75) –> Driver code

Output:

sum of integers from x to y : 1625

Function calling is called driver code and function definition with block of statements is called master code
Q2. Differentiate between argument and parameter.

Ans: Parameters are of two types:

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.

Q3. Explain different types of arguments in

python. Ans:
def display(a='hello',b='world'): # you can have only default arguments

also print(a,b)

display()

Output:

hello world

def display(a,c=10,b): # default argument will always come as last argument


d=a+b+c

print(d)

display(2,3) # error, non default argument follows default argument

def display(a,b,c=10):

d=a+b+c

print(d)

display(2,

3)

Output:

15

Variable length with first extra argument:


Variable length argument Example:

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:

Program to return the minimum of two numbers:

Returning multiple values: It is possible in python to return multiple values def


compute(num):return num*num,num**3 # returning multiple value

square,cube=compute(2)

print(“square = “,square,”cube =”,cube)


Lecture-20 (A) Anonymous function

Lecture-20 Anonymous Function


Program to find cube of a number using lambda function

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.

● Lambda function does not contain a return statements

● It contains a single expression as a body not a block of statements as a body

Q6. Define scope of a variable. Also differentiate local and global

variable. Ans:
1. Program to access a local variable outside a functions

def demo():

q=10

print("the value of local variable is",q)

demo()

print("the value of local variable q is:",q) #error, accessing a local variable


outside the scope will cause an error

Output:

the value of local variable is 10

Traceback (most recent call last):

File "C:/Users/Students/AppData/Local/Programs/Python/Python38-32/vbhg.py", line 5, in


<module>

print("the value of local variable q

is:",q) NameError: name 'q' is not

defined
2. Program to read global variable from a local scope

def demo():

print(s)

s=’I love python’

demo()

Output:

I love python

3. Local and global variables with the same name

def demo():

s=’I love python

print(s)

s=’I love programming’

demo() # first function is called, after that other satements print(s)

Output:

I love python

I love programming

The Global Statement

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()

print(‘the value of an outside function is’,a)

Output:

value of a is 30

the value of an outside function 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’

Q 7. What is recursion? Explain with example.Ans:

Q Program to find the factorial of a number using recursion

def factorial(n):

if n==0: # base condition

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.

Q8. Program to find the fibonacci series using recursion.

Ans:

def fibonacci(n):

if(n <= 1):

return n

else:

return(fibonacci(n-1) +

fibonacci(n-2)) n = int(input("Enter

number of terms:")) print("Fibonacci

sequence:")

for i in range(n):

print

fibonacci(i),

Q9. Program to find the GCD of two numbers using recursion.

Ans:

def gcd(a,b):

if(b==0):

return

else:

return gcd(b,a%b)

a=int(input("Enter first number:"))

b=int(input("Enter second

number:")) GCD=gcd(a,b)

print("GCD is: ")

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:

return arr[size-1] + sum_arr(arr,size-1) n=int(input("Enter the number

of elements for list:")) a=[]

for i in range(0,n):

element=int(input("Enter element:")) a.append(element)

print("The list is:") print(a)

print("Sum of items in list:") b=sum_arr(a,n)

print(b)

Q11. Program to check whether a string is a palindrome or not using recursion. Ans:

def is_palindrome(s):

if len(s) < 1: return True

else:

if s[0] == s[-1]:

return is_palindrome(s[1:-1]) else:

return False a=str(input("Enter string:"))

if(is_palindrome(a)==True):

print("String is a palindrome!") else:

print("String isn't a palindrome!")

Important Ques CO-3

Explain mutuable sequences in python .


Explain output of following function .
def printalpha(abc_list , num_list):
for char in abc_list:
for num in num_list:
print(char, num)
return
printalpha(['a','b','c'],[1,2,3])
Compare list and tuple with suitable example. Explain the concept of list comprehension.
Write a python program that accepts a sentence and calculate the number of digits. Uppercase and lowercase letters
.
Write a program to print fibonnacci series upto n terms using user-defined function .

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.

Disadvantages of File Handling in Python


● Error-prone: File handling operations in Python can be prone to errors, especially if the code is not carefully
written or if there are issues with the file system (e.g. file permissions, file locks, etc.).
● Security risks: File handling in Python can also pose security risks, especially if the program accepts user input that
can be used to access or modify sensitive files on the system.
● Complexity: File handling in Python can be complex, especially when working with more advanced file formats or
operations. Careful attention must be paid to the code to ensure that files are handled properly and securely.
● Performance: File handling operations in Python can be slower than other programming languages, especially
when dealing with large files or performing complex operations.

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

't' for text mode (default)


'+' for updating (reading and writing)

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)

# Read one line at a time


line = file.readline()
print(line)

# Read all lines into a list


lines = file.readlines()

print(lines)
file.close() # Always close the file when you're done with it

Q:-Python code to illustrate read() mode

file = open("cse.txt", "r")


print (file.read())

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.

# Python code to illustrate split() function


with open("geeks.txt", "r") as file:
data = file.readlines()
for line in data:

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()

Using with Statement


The with statement simplifies file handling by automatically taking care of closing the file once it leaves the with block,
even if exceptions occur:
Eg:-
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# File is automatically closed here

Working of Append Mode


# Python code to illustrate append() mode
file = open('geek.txt', 'a')
file.write("This will add this line")
file.close()

Q:- Implementing all the functions in File Handling


import os
def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)

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 append_file(filename, text):


try:
with open(filename, 'a') as f:
f.write(text)
print("Text appended to file " + filename + " successfully.")
except IOError:
print("Error: could not append to file " + filename)

def rename_file(filename, new_filename):


try:
os.rename(filename, new_filename)
print("File " + filename + " renamed to " + new_filename + " successfully.")
except IOError:
print("Error: could not rename file " + filename)

def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)

if name == ' main ':


filename = "example.txt"
new_filename = "new_example.txt"

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:

File example.txt created successfully.


Hello, world!
Text appended to file example.txt successfully.
Hello, world!
This is some additional text.
File example.txt renamed to new_example.txt successfully.
Hello, world!
This is some additional text.
File new_example.txt deleted successfully.

Handling File Paths


For file paths, you can use raw strings (e.g., r'C:\path\to\file.txt') to avoid escaping backslashes in Windows paths, or
use forward slashes which Python understands across platforms (e.g., 'C:/path/to/file.txt' or './folder/file.txt').
Lecture24 – Manipulating File Pointer
In Python, you can manipulate the file pointer, which represents the current position in the file where the next read or
write operation will occur. Python provides the seek() method to move the file pointer to a specific position within the
file.
Syntax:-
f.seek(offset, from_what), where f is file pointer

The seek() method takes two arguments:

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.

By default from_what argument is set to 0.


Note: Reference point at current position / end of file cannot be set in text mode except when offset is equal to 0.

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")

# Second parameter is by default 0


# sets Reference point to twentieth index position from the beginning
f.seek(20)

# prints current position


print(f.tell())

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")

# sets Reference point to tenth


# position to the left from end
f.seek(-10, 2)

# prints current position


print(f.tell())

# Converting binary to string and


# printing
print(f.readline().decode('utf-8'))

f.close()

Output:
47
, its bad.

Example3:- seek() method to manipulate the file pointer:


# Open a file in read mode
file = open('example.txt', 'r')

# Move the file pointer to the 10th byte from the beginning
file.seek(10)

# Read the content from the current position


content = file.read()
print(content)

# Move the file pointer 5 bytes backward from the current position
file.seek(-5, 1)

# Read the content from the current position


content = file.read()
print(content)

# Move the file pointer to the end of the file


file.seek(0, 2)

# Write content at the end of the file


file.write("\nAdding content at the end.")

# Close the file


file.close()

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:

1. Programming and Scripting


In programming, a file of operations might contain a list of commands or function calls that should be executed
sequentially. Here’s how you might approach this:

Reading the File:


Open the file in the appropriate mode (read, write, append, etc.).
Read the file line by line or as a whole, depending on your needs.

Parsing the Operations:


For each line or operation, parse the instruction. This could involve simple string manipulation or more complex
parsing if the instructions are in a specific format (JSON, XML, etc.).
It’s essential to implement error handling to deal with malformed instructions or unsupported operations.

Executing the Operations:


Execute each parsed operation. This might involve calling functions, executing system commands, or performing file
manipulations.
Ensure that operations are executed in the correct order and handle any dependencies between operations.

2. Data Processing
In data processing, a file of operations might list data transformations or analyses to perform on a dataset. This could
involve:

Reading and Writing Data:


Use appropriate libraries for data manipulation (e.g., pandas in Python) to read your dataset.
Read the operations file to determine what transformations or analyses need to be performed.

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.

Ensuring System Integrity:


Implement checks to verify that each operation completes successfully.
Log the outcomes of operations for audit purposes and to troubleshoot any issues that arise.

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.

Above Operation in case of Python Language

1. Programming and Scripting


Suppose you have a file named operations.txt with lines of operations like:

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)

# Mapping operation names to functions


operations = {
'print': handle_print,
'add': handle_add,
}

with open('operations.txt', 'r') as file:


for line in file:
op, *args = line.strip().split(',')
if op in operations:
operations[op](args)
else:
print(f"Unsupported operation: {op}")

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')

with open('data_operations.txt', 'r') as file:


for line in file:
operation, value = line.strip().split(',')
if operation == 'filter':
df = df[df['column_name'] > int(value)]

# Assuming you might want to print or save the filtered data


print(df)

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}")

with open('system_ops.txt', 'r') as file:


for line in file:
operation, path = line.strip().split(',')
if operation == 'backup':
backup_file(path)

General Python Tips for Handling Files of Operations


Use Context Managers: Always use with open(...) as ... for safely opening and closing files.
Error Handling: Wrap operations in try/except blocks to gracefully handle exceptions.
Dynamic Function Mapping: As shown in the programming example, map operation names to functions for a clean
and scalable way to execute operations.
Validate Inputs: Especially when executing system operations or modifying data, validate and sanitize inputs to
prevent errors or security issues.
Lecture26(Examples) :- Python Program (Fibonacci Series)

Program:- Discussed about Fibonacci Series of Program.


The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually
starting with 0 and 1. That is, the sequence starts 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. It's a classic example used in
programming to demonstrate various coding techniques, including recursion, iteration, and dynamic programming.

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)

Program: - Discussed about Addition of two Matrix of Program.


Adding two matrices in Python can be done in various ways, ranging from basic loops to using sophisticated libraries
like NumPy, which is designed for scientific computing and can handle operations on large multi-dimensional arrays
and matrices efficiently.

def add_matrices(matrix1, matrix2):


# Ensure the matrices have the same dimensions

if len(matrix1) != len(matrix2) or len(matrix1[0]) != len(matrix2[0]):


return "Matrices are of different sizes."

# Create a new matrix to store the result


result_matrix = [[0 for _ in range(len(matrix1[0]))] for _ in range(len(matrix1))]

# Iterate over the matrices to add corresponding elements

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

matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]

print("Resultant Matrix:")

for row in add_matrices(matrix1, matrix2):


print(row)
Lecture26:- Python Program(Transpose Matrix of Program.)

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.

Program(Using Python Loops)

def transpose_matrix(matrix):
# Initialize the transposed matrix with zeros
transposed = [[0 for _ in range(len(matrix))] for _ in range(len(matrix[0]))]

# Iterate through rows


for i in range(len(matrix)):
# Iterate through columns
for j in range(len(matrix[i])):
# Assign transposed values
transposed[j][i] = matrix[i][j]

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)

Program:- Python identity Matrix of Program.

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)

Python Program (Multiplication table)

Python Program:- Python program to Print any no of table Program.

def print_multiplication_table(number, range_limit):


"""
Prints the multiplication table for a given number up to a specified range.

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: "))

# Print the multiplication table


print(f"\nMultiplication table for {number} up to {range_limit}:")
print_multiplication_table(number, range_limit)

if name == " main ":


main()

Python Program (Leap Year)

Program:- Python Program how to check given year is leap or not

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.")

if name == " main ":


main()
Python Program (Perfect Number)

Program:- Python Perfect number program

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.")

if name == " main ":


main()

Python Program (Armstrong Number)

Program:- Python Armstrong number program

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:

● Get the number of digits in the number.


● Calculate the sum of the digits each raised to the power of the number of digits.
● Compare the sum to the original number.

Here's a Python program that performs these steps:

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)

# Compare the sum to the original number


return sum_of_powers == 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.")

if name == " main ":


main()

Important Ques -CO4

Discuss various file opening mode in python


Differentiate between text file and binary file .

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

What are file input and output operations in python programming?

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

Lecture26(A):-Introduction to Python Packages


Python Packages
Python packages are a way of organizing and distributing Python code. They allow you to bundle multiple files or
modules into a single, importable package, making code reuse and distribution easier. Python packages can include
libraries, frameworks, or collections of modules that provide additional functionality or enable specific tasks. Here's an
overview of key concepts and steps related to Python packages:
Key Concepts
Module: A Python file containing Python definitions, statements, and functions. It's the smallest unit of code reuse in
Python.
Package: A way of collecting related modules together within a single tree-like hierarchy. Very complex packages may
include subpackages at various levels of the hierarchy.
Installing Packages
To install packages, you generally use pip, Python's package installer
Commonly Used Packages

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

Matplotlib Histograms Plot


Matplotlib Scatter Plot

Matplotlib Pie Charts


Matplotlib Area Plot

1. Matplotlib Line 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:-

# importing matplotlib module


from matplotlib import pyplot as plt

# 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)

# function to show the plot


plt.show()
2. Matplotlib Bar Plot

# importing matplotlib module


from matplotlib import pyplot as plt

# 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()

3. Matplotlib Histograms Plot

# importing matplotlib module


from matplotlib import pyplot as plt

# Y-axis values
y = [10, 5, 8, 4, 2]

# Function to plot histogram


plt.hist(y)

# Function to show the plot


plt.show()

4. Matplotlib Scatter Plot

# importing matplotlib module


from matplotlib import pyplot as plt

# x-axis values
x = [5, 2, 9, 4, 7]

# Y-axis values
y = [10, 5, 8, 4, 2]

# Function to plot scatter


plt.scatter(x, y)

# function to show the plot


plt.show()

5. Matplotlib Pie Charts

import matplotlib.pyplot as plt

# Data for the pie chart


labels = ['Geeks 1', 'Geeks 2', 'Geeks 3']
sizes = [35, 35, 30]

# Plotting the pie chart


plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.title('Pie Chart Example')
plt.show()

6. Matplotlib Area Plot


import matplotlib.pyplot as plt

# 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')

# Labels and Title


plt.xlabel('X-axis'), plt.ylabel('Y-axis'), plt.title('Area Chart Example')

# Legend and Display


plt.legend(), plt.show()
Lecture27:- Python NumPy

Numpy:-

NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object


and tools for working with these arrays. It is the fundamental package for scientific computing with Python. It is open-
source software.

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

Install Python NumPy


pip install numpy

Create a NumPy ndarray Object

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

arr = np.array([1, 2, 3, 4, 5])


print(arr)
print(type(arr))

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

0D (zero-dimensional) Scalar – A single element

1D (one-dimensional) Vector- A list of integers.

2D (two-dimensional) Matrix- A spreadsheet of data


Name Example

3D (three-dimensional) Tensor- Storing a color image

2-D Arrays

An array that has 1-D arrays as its elements is called a 2-D array.

These are often used to represent matrix or 2nd order tensors.

Example:-
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)

3-D arrays

Example:-
import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

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.

Why Use Pandas?


1. Handle Large Data Efficiently
2. Tabular Data Representation
3. Data Cleaning and Preprocessing
4. Free and Open-Source

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 Data Structures


Pandas generally provide two data structures for manipulating data, They are:
● Series
● DataFrame

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

# Calling DataFrame constructor


df = pd.DataFrame()
print(df)

# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks']

# Calling DataFrame constructor on list


df = pd.DataFrame(lst)
print(df)
Lecture29 :- GUI Programs

Q:- Hello World Window:


Sol:-
import tkinter as tk

# Create the main window


root = tk.Tk()
root.title("Hello World")

# Create a label widget with "Hello, World!" text


label = tk.Label(root, text="Hello, World!")
label.pack()

# Run the main event loop


root.mainloop()

Q:- Design a GUI for calculator using tkinter


Q:- Python Tkinter Program to show onclick event on button
Source Code:
import Tkinter as tk
root=tk.Tk()
def click():
a=e.get()
a1="Hello "+a
l1.config(text=a1)
l=tk.Label(root,text="name",fg="red",bg="lightgreen")
l.grid(row=0,column=0)
l1=tk.Label(root)
l1.grid(row=1,column=1)
e=tk.Entry(root)
e.grid(row=0,column=1)
b=tk.Button(root,text="click",fg="red",bg="blue",command=click)
b.grid(row=1,column=0)
#button =tk.Button(root, text="Quit", command=root.destroy)

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.

Tk provides the following widgets:


● button
● canvas
● checkbutton
● combobox
● entry
● frame
● label
● labelframe
● listbox
● menu
● menubutton
● message
● notebook
● tk_optionMenu
● progressbar
● radiobutton
● scale
● scrollbar
● separator
● sizegrip
● spinbox
● text
● treeview

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

● from tkinter import *


● root = Tk()
● var = StringVar()
● label = Label( root, textvariable = var, relief = RAISED )
● var.set("Hey!? How are you doing?")
● label.pack()
● root.mainloop()
● OUTPUT

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 = Checkbutton(top, text = "Music", variable = CheckVar1, \


onvalue = 5, offvalue = 0, height=5, \
width = 20, )
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, \
onvalue = 6, offvalue = 0, height=5, \
width = 20)
B1=Button(top,text="show",command=show)

C1.pack()
C2.pack()
B1.pack()
top.mainloop()

OUTPUT

Radiobutton (int as well as string)


from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()

R1 = Radiobutton(root, text = "Option 1", variable = var, value = 1,command = sel)


R1.pack( )

R2 = Radiobutton(root, text = "Option 2", variable = var, value = 2, command = sel)


R2.pack( )

R3 = Radiobutton(root, text = "Option 3", variable = var, value = 3, command = sel)


R3.pack( )

label = Label(root)
label.pack()
root.mainloop()

OUTPUT

MessageBox (Showinfo)
from tkinter import *

from tkinter import messagebox


top = Tk()
top.geometry("300x100")
def hello():
messagebox.showinfo("Say Hello", "Hello World")

B1 = Button(top, text = "Say Hello", command = hello)

B1.place(x = 35,y = 50)


top.mainloop()
OUTPUT:-

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 concatenate two dictionaries into one dictionary.


Python Program to check if a given key exists in a dictionary or not.

Python Program to remove the given key from a dictionary.


Python Program to count the frequency of words appearing in a string using a dictionary.
Python Program to create a dictionary with key as first character and value as words starting with that
character.
Python Program to count the number of vowels present in a string using sets
Python Program to check common letters in the two input strings.
Python Program to display which letters are present in both the strings.
Python Program to find the fibonacci series using recursion.

Python Program to find the factorial of a number using recursion.


Python Program to find the GCD of two numbers using recursion.

Python Program to reverse a string using recursion.


Python Program to read the contents of a file.
Python Program to count the number of words in a text file.
Python Program to copy the contents of one file into another.
Python Program to append the contents of one file to another file.

Python Program to read a file and capitalize the first letter of every word in the file

You might also like