0% found this document useful (0 votes)
4 views30 pages

PP Notes

The document provides an overview of Python programming concepts, including types of errors (syntax, runtime, and logical errors), control statements (if, while, for loops), and functions (void and fruitful). It also covers data structures like tuples, lists, and dictionaries, along with built-in exceptions and file handling methods. Additionally, it discusses multithreading and the use of the threading module for concurrent execution.

Uploaded by

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

PP Notes

The document provides an overview of Python programming concepts, including types of errors (syntax, runtime, and logical errors), control statements (if, while, for loops), and functions (void and fruitful). It also covers data structures like tuples, lists, and dictionaries, along with built-in exceptions and file handling methods. Additionally, it discusses multithreading and the use of the threading module for concurrent execution.

Uploaded by

Saad Wasta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT 1

1.write the Different types of errors in python.

Ans)
1) Syntax errors: Errors that occur when you violate the rules of writing python
syntax are
known as syntax errors.
Most frequent syntax errors are:
 Missing Parenthesis (})
 Printing the value of variable without declaring it
 Missing semicolon like this:

2) Run-time Errors : Errors which occur during program execution(run-time)


after
successful compilation are called run-time errors. One of the most common
run-time error
is division by zero also known as Division error.
1) x=4, y=0
2) z=x/y
3) display z
4) end

3) Logical/Semantic Errors: On compilation and execution of a program,


desired output
is not obtained when certain input values are given. These types of errors
which provide
Incorrect output but appears to be error free are called logical errors.
for x in range(1,11):total=x
No output of above program though syntax is correct
2.How to use control statements in python.

Ans)
These statements allow you to control which block of code to execute
based on certain conditions.
• if: Executes a block of code if the condition is True.
• elif: Adds another condition to check if the previous one was
False.
• else: Executes a block of code if none of the previous conditions
were True.
Add some basic code here!
2.while Loop
The while loop is used to repeatedly execute a block of code as long as
the condition is True. This is useful when the number of iterations is
not known beforehand.
Add some basic code here!
3.for loop
in python is used to iterate over the sequence like
tuples,string,list.it useful when we know the iteration.
Example: for x in [1,2,3]:
print(x)
4.break: the break statement is used to exit from the loop.it is useful if
we want to stop loop based on certatin condition.
Example: for x in [1,2,3]:
print(x)
if(x==2):
break
5.continue: the continue statement is used to skip current iteration of
loop and continues to next iteration.it helpful when we want to skip
some iteration but not want to stop loop.
6.pass:it just pass the flow of program do nothing.
3.Write a program to display the no. Is even or odd.
ANS)
n=int(input('Please enter a number'))
if(n%2==0):
print(n,' is even')
else:
print(n,' is odd')

4.Write a program to display reverse digit

ANS)
num= int(input('Please enter a number'))
def reverse(n):
rev=0
while n!=0:
rem=n%10
rev= rev*10+rem
n=n//10
return rev
print(reverse(num))
print("Reverse of a given number is: " + str(reverse(num)))
5.Differences Between Brackets, Braces, and Parentheses in Python
ANS)

1. Brackets [ ]:
Definition: Brackets are used to define lists in Python.
Example: my_list = [1, 2, 3, 4] creates a list containing four
elements. List are mutable it,s mean their values can be changed or
modified

2. Braces { }:
Definition: Braces are used for defining dictionaries (key
value pairs) and sets (unordered collections of unique
elements).

Example: my_dict = {'name': 'Alice', 'age': 30} creates a


dictionary, while my_set = {1, 2, 3} creates a set.

3. Parentheses ( ):
 Definition: Parentheses are used to group expressions,
create tuples (ordered collections), and invoke functions.

 Example: result = (2 + 3) * 4 evaluates the expression inside


the parentheses first, and my_tuple = (1, 2, 3) creates a
tuple.
6.Explain the logical and membership operator with eg.
ANS)

Logical Operators

Logical operators are used to combine conditional statements. The most


common logical operators are:

1. and: Returns True if both operands are true.


2. or: Returns True if at least one of the operands is true.
3. not: Returns True if the operand is false, and vice versa.

Example

a = True
b = False
print(a and b)
print(a or b)
print(not a)
print(not b)

Membership Operators
Membership operators are used to test if a value is present in a sequence (like
a list, tuple, or string). The two membership operators are:

1. in: Returns True if the value is found in the sequence.


2. not in: Returns True if the value is not found in the sequence

Example

my_list = [1, 2, 3, 4, 5]

print(3 in my_list)

print(6 in my_list)

my_string = "Hello, World!"


print("Hello" not in my_string)
print("Python" not in my_string)
UNIT 2

1.Explain the structure of in and not in operator using string.

ANS)

i)in Operator

The in operator returns True if the specified substring is found in the


string, otherwise it returns False.

Syntax: substring in string

Example
text = "Hello, world!"

result = "Hello" in text

print(result)

ii)not in Operator

The not in operator returns True if the specified substring is not found in the
string, otherwise it returns False.

Syntax: substring not in string

Example
text = "Hello, world!"

result = "Hi" not in text

print(result)
2)What is recursion explain with eg

ANS)

Recursion is a programming technique where a function calls itself to


solve a problem. It typically involves breaking down a problem into
smaller, more manageable subproblems. A recursive function usually
has two main components:
 Base Case: This is the condition under which the recursion stops. It
prevents the function from calling itself indefinitely.
 Recursive Case: This is where the function calls itself with modified
arguments, gradually working towards the base case.

def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)
3)How to create void and fruitfull function explain with eg

ANS)

1. Void Functions: These functions do not return a value. They perform a


specific task, such as printing information or modifying data, but they do
not produce a return value.

Example of a Void Function

A void function performs an action but does not return anything. Here’s an
example of a void function that prints a message:

def greet(name):
print(f"Hello, {name}!")

greet("Alice")

2. Fruitful Functions: These functions return a value. They perform a


calculation or processing task and provide a result that can be used later
in the program

Example of a Fruitful Function

A fruitful function performs a task and returns a value. Here’s an example of a


fruitful function that calculates the square of a number:

def square(number):

return number ** 2

result = square(5)

print(result)
4) Explain the traversal with for loop

ANS) Traversal refers to the process of visiting each element in a data


structure, such as a list, tuple, string, or dictionary, in order to perform some
operation on each element. In Python, a for loop is commonly used to traverse
through these data structures.

Using a for Loop for Traversal

A for loop allows you to iterate over elements in a collection, performing


actions on each element as you go. The general syntax of a for loop in Python
is:

for variable in iterable:


# Code to execute for each element

 variable: Represents the current element in the iteration.


 iterable: The collection (e.g., list, tuple, string) you want to traverse.

Example 1: Traversing a List

Let's consider an example of traversing a list of numbers and printing each


number:

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

for num in numbers:

print(num)

Example 2: Traversing a String

You can also traverse a string using a for loop. Here's an example:

message = "Hello, World!"

for char in message:

print(char)
Summary

 A for loop in Python is a powerful and convenient way to traverse


various data structures.
 It allows you to iterate over lists, strings, dictionaries, and other iterable
objects, performing operations on each element.
 The structure of the loop is straightforward and enhances code
readability.
5)Write a short note on Math function

ANS)
Python provides a built-in module called math, which includes a variety of
mathematical functions and constants. This module is useful for performing
mathematical operations that are not readily available in standard Python
operations.

Commonly Used Math Functions

Here are some of the most commonly used functions in the math module:

1. Basic Mathematical Functions:


o math.ceil(x): Returns the smallest integer greater than or equal to
x.
o math.floor(x): Returns the largest integer less than or equal to x.
o math.fabs(x): Returns the absolute value of x.

2. Trigonometric Functions:
o math.sin(x): Returns the sine of x (angle in radians).
o math.cos(x): Returns the cosine of x.
o math.tan(x): Returns the tangent of x.

3. Exponential and Logarithmic Functions:


o math.exp(x): Returns exe^xex, where eee is Euler's number (
o math.log(x[, base]): Returns the logarithm of x to the specified
base. If no base is specified, it defaults to the natural logarithm
(base eee).
o math.pow(x, y): Returns xxx raised to the power of yyy.

4. Constants:
o math.pi: The mathematical constant π
o math.e: The mathematical constant eee

The math module in Python provides a wide array of mathematical functions


and constants that are essential for performing advanced mathematical
calculations efficiently. By importing the math module, you can leverage these
functions to enhance your programming capabilities, particularly in areas such
as data analysis, scientific computing, and graphical computations.
UNIT 3

1.Explain the use of repitition and concationation operator in tuple

ANS)

1. Repetition Operator
The repetition operator * is used to create a new tuple by repeating the
elements of an existing tuple a specified number of times.

Syntax: new_tuple = original_tuple * n

original_tuple: The tuple you want to repeat.

n: The number of times to repeat the tuple.

Example:

tuple1 = (1, 2, 3)

repeated_tuple = tuple1 * 3

print(repeated_tuple)

2. Concatenation Operator
The concatenation operator + is used to combine two or more tuples into a
new tuple.

Syntax:
new_tuple = tuple1 + tuple2
tuple1 and tuple2: The tuples you want to concatenate.

Example :
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple)
2.Explain any 5 built in exceptions

ANS)

1. ValueError

 Description: Raised when a function receives an argument of the right


type but an inappropriate value.
 Example:

try:

num = int("abc")

except ValueError as e:

print(f"ValueError: {e}")

2. TypeError

 Description: Raised when an operation or function is applied to an


object of inappropriate type.
 Example:

try:

result = "hello" + 5

except TypeError as e:

print(f"TypeError: {e}")
3.IndexError

 Description: Raised when trying to access an index that is out of the


range of a list or tuple.
 Example :

my_list = [1, 2, 3]

try:

print(my_list[5])

except IndexError as e:

print(f"IndexError: {e}")

4. KeyError

 Description: Raised when trying to access a dictionary with a key that


does not exist.
 Example:

my_dict = {"name": "Alice", "age": 25}

try:

print(my_dict["gender"])

except KeyError as e:

print(f"KeyError: {e}")
5. ZeroDivisionError

 Description: Raised when attempting to divide a number by zero.


 Example:

try:

result = 10 / 0

except ZeroDivisionError as e:

print(f"ZeroDivisionError: {e}")
3.Explain tell() and seek() method with suitable examples

ANS)
1. tell() Method

The tell() method returns the current position of the file pointer within a file.
This is useful when you need to know where you are in the file for reading or
writing operations.

Syntax: file_object.tell()

Example:

with open('example.txt', 'w') as file:

file.write("Hello, World!")

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

content = file.read(5)

position = file.tell()

print(f"Current position after reading: {position}")


2. seek() Method

The seek() method is used to change the file pointer's position within the file. It
allows you to move to a specific byte location in the file, which is essential for
random access operations.

Syntax: file_object.seek(offset, whence)

Example:
with open('example.txt', 'w') as file:
file.write("Hello, World!")

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


file.seek(7
content = file.read(5
print(content)
4. Write the different methods of directories
1. os.mkdir()

Creates a new directory at the specified path.

Example

import os
os.mkdir('new_folder')

2. os.makedirs()

Creates a directory and any necessary intermediate directories. It raises an


error if the target directory already exists unless exist_ok is set to True.

Example

import os

os.makedirs('new_folder/sub_folder', exist_ok=True)

3. os.listdir()

import os

Returns a list of all files and directories in the specified directory.

Example

files_and_dirs = os.listdir('.') print(files_and_dirs)

4. os.rename()

Renames a directory (or file)

Example

import os

os.rename('old_folder', 'new_folder')
5. os.rmdir()

Removes an empty directory.

Example

import os

os.rmdir('new_folder')

6. os.removedirs()

Removes a directory and any empty intermediate directories. Raises an error if


any directory is not empty.

Example

import os

os.removedirs('new_folder/sub_folder')

7. os.getcwd()

Returns the current working directory.

Example

import os

current_directory = os.getcwd()

print(f"Current Directory: {current_directory}")


8. os.chdir()

Changes the current working directory to the specified path.

Example

import os

os.chdir('new_folder')

print(os.getcwd()) # Output: Current Directory: new_folder

9. os.path.join()

Joins one or more path components intelligently. This is particularly useful for
creating file paths that are platform-independent.

Example:

import os
path = os.path.join('new_folder', 'file.txt')
print(path) # Output: new_folder/file.txt (on POSIX)
5. Write a program to either read or write the content from the file
6.
ANS)
def file_operations():
choice = input("Do you want to read or write to a file? (r/w): ").strip().lower()

if choice == 'w':
filename = input("Enter the filename to write to: ")
content = input("Enter the content to write to the file: ")

with open(filename, 'w') as file:


file.write(content)

print(f"Content written to {filename} successfully.")

elif choice == 'r':


filename = input("Enter the filename to read from: ")

try:
with open(filename, 'r') as file:
content = file.read()
print(f"Content of {filename}:\n{content}")

except FileNotFoundError:
print(f"Error: The file {filename} does not exist.")

else:
print("Invalid choice. Please enter 'r' to read or 'w' to write.")

file_operations()

1. What is multithreading and explain the thread module with


suitable example
ANS)

Multithreading is a programming technique where multiple threads run at the


same time within a program. Threads are small units of a process that share
the same memory space, allowing tasks to
execute concurrently, improving performance in I/O-bound tasks(like reading
files or making web requests).

In Python, the threading module is used to create and manage threads.


import threading

def print_numbers():
for i in range(5):
print(i)

t = threading.Thread(target=print_numbers)

t.start()

t.join()

 Thread: A separate flow of execution.


 Creating a thread: Thread(target=function_name) creates a new thread.
 Starting a thread: start() begins the execution of the thread.
 Joining a thread: join() waits for the thread to finish.

2. Explain any 2 methods of regular expression with example


ANS)

1. re.search()

This method searches for a pattern within a string. It returns the first match
object if found, or None if
there’s no match.
import re
pattern = r"\d+" # Looks for one or more digits
text = "The price is 100 dollars"
match = re.search(pattern, text)
if match:
print(f"Found match: {match.group()}")
else:
print("No match found.")
Explanation:
• Pattern \d+: Searches for one or more digits.
• Output: It will print Found match: 100 because 100 is the first sequence of
digits in the text.

2. re.findall()

• This method returns a list of all matches of the pattern in the string.
import re
pattern = r"\d+" # Finds all digit sequences
text = "There are 3 cats, 7 dogs, and 10 birds."
matches = re.findall(pattern, text)

print(matches)

Explanation:
• Pattern \d+: Finds all sequences of digits.
• Output: ['3', '7', '10'] — it found all occurrences of numbers in the string.
Both methods help in finding and extracting parts of strings based on patterns.

3. Explain the inheritance concept with example

ANS)
Inheritance is a fundamental concept in object-oriented programming (OOP)
where a class (called a child
or subclass) derives properties and behaviors (methods) from another class
(called a parent or
superclass). This allows code reuse and the ability to extend or modify the
inherited properties without
changing the original code.
Exmpale:
class parent:
def __init__(self,name,age):
self.name=name
self.age=age
def _display(self):
print(‘the name is’,self.name)
class child(parnet):
def __init__(self,name,age,roll):
super(). __init__(name,age)
self.roll=roll

x=child(“deepak”,12,44)
x.display()
so above code gives example of inheritance where we called function of parent
class and we inherits it
contructor also.

4. Explain the method overloading and method overriding with suitable


example
ANS)
1Method Overriding:
• Definition: Occurs when a child class provides a specific implementation of a
method that is already defined in the parent class.
• Key Point: The method name and parameters must be the same in both the
parent and child classes.

class Animal:

def sound(self):

return "Some generic sound"

class Dog(Animal):

def sound(self):

return "Bark"

dog = Dog()

print(dog.sound())

2. Method Overloading:
• Definition: Occurs when a class has multiple methods with the same name
but different parameters. Python does not support true overloading but can
achieve it using default
arguments.
class Calculator:

def add(self, a, b=0, c=0):

return a + b + c

calc = Calculator()

print(calc.add(5))
print(calc.add(5, 10))
print(calc.add(5, 10, 15))

UNIT 5

1.Write a short note on TK message box module

Ans)
The Tkinter message box module is a part of the Tkinter library in Python,
which provides a simple interface for creating graphical user interfaces (GUIs).
The tkinter.messagebox module specifically is used to display message boxes
to the user.

Key Features:

1. Types of Message Boxes: The module includes several types of message


boxes, including:
o Information Boxes: Used to display informative messages.
o Warning Boxes: Used to alert the user about potential issues.
o Error Boxes: Used to indicate errors in operations.
o Question Boxes: Used to ask the user a question with Yes/No or
OK/Cancel options.

2. Common Functions:
o showinfo(title, message): Displays an information message box.
o showwarning(title, message): Displays a warning message box.
o showerror(title, message): Displays an error message box.
o askquestion(title, message): Displays a question message box,
returning "yes" or "no".
o askokcancel(title, message): Displays a message box with OK and
Cancel options, returning a Boolean value.

3. Customization: While the basic appearance of the message boxes is


controlled by the operating system, you can customize the title and
message content.

Example

import tkinter as tk
from tkinter import messagebox
def show_message():
messagebox.showinfo("Information", "This is a message box!")

root = tk.Tk()
root.withdraw()
show_message()
root.mainloop()

2. Write a program based on insert command using mysql

ANS)
import mysql.connector
from mysql.connector import Error

def insert_user(name, age, email):


try:
connection = mysql.connector.connect(
host='localhost',
database='sample_db',
user='your_username',
password='your_password'
)

if connection.is_connected():
cursor = connection.cursor()
insert_query = "INSERT INTO users (name, age, email) VALUES (%s, %s,
%s)"
record = (name, age, email)
cursor.execute(insert_query, record)
connection.commit()
print("User inserted successfully.")

except Error as e:
print(f"Error: {e}")

finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed.")

if __name__ == "__main__":
user_name = input("Enter name: ")
user_age = int(input("Enter age: "))
user_email = input("Enter email: ")
insert_user(user_name, user_age, user_email)
3.How to Retrive Data from my Sql
Ans)

import mysql.connector
from mysql.connector import Error

def retrieve_users():
try:
connection = mysql.connector.connect(
host='localhost',
database='sample_db',
user='your_username',
password='your_password'
)

if connection.is_connected():
cursor = connection.cursor()
select_query = "SELECT * FROM users"
cursor.execute(select_query)
records = cursor.fetchall()
print("Total number of users:", cursor.rowcount)

for row in records:


print("ID:", row[0])
print("Name:", row[1])
print("Age:", row[2])
print("Email:", row[3])
print("------------")

except Error as e:
print(f"Error: {e}")

finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed.")

if __name__ == "__main__":
retrieve_users()

You might also like