PP Notes
PP Notes
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:
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')
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).
3. Parentheses ( ):
Definition: Parentheses are used to group expressions,
create tuples (ordered collections), and invoke functions.
Logical Operators
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:
Example
my_list = [1, 2, 3, 4, 5]
print(3 in my_list)
print(6 in my_list)
ANS)
i)in Operator
Example
text = "Hello, world!"
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.
Example
text = "Hello, world!"
print(result)
2)What is recursion explain with eg
ANS)
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)
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")
def square(number):
return number ** 2
result = square(5)
print(result)
4) Explain the traversal with for loop
numbers = [1, 2, 3, 4, 5]
print(num)
You can also traverse a string using a for loop. Here's an example:
print(char)
Summary
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.
Here are some of the most commonly used functions in the math module:
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.
4. Constants:
o math.pi: The mathematical constant π
o math.e: The mathematical constant eee
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.
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
try:
num = int("abc")
except ValueError as e:
print(f"ValueError: {e}")
2. TypeError
try:
result = "hello" + 5
except TypeError as e:
print(f"TypeError: {e}")
3.IndexError
my_list = [1, 2, 3]
try:
print(my_list[5])
except IndexError as e:
print(f"IndexError: {e}")
4. KeyError
try:
print(my_dict["gender"])
except KeyError as e:
print(f"KeyError: {e}")
5. ZeroDivisionError
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:
file.write("Hello, World!")
content = file.read(5)
position = file.tell()
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.
Example:
with open('example.txt', 'w') as file:
file.write("Hello, World!")
Example
import os
os.mkdir('new_folder')
2. os.makedirs()
Example
import os
os.makedirs('new_folder/sub_folder', exist_ok=True)
3. os.listdir()
import os
Example
4. os.rename()
Example
import os
os.rename('old_folder', 'new_folder')
5. os.rmdir()
Example
import os
os.rmdir('new_folder')
6. os.removedirs()
Example
import os
os.removedirs('new_folder/sub_folder')
7. os.getcwd()
Example
import os
current_directory = os.getcwd()
Example
import os
os.chdir('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: ")
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()
def print_numbers():
for i in range(5):
print(i)
t = threading.Thread(target=print_numbers)
t.start()
t.join()
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.
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.
class Animal:
def sound(self):
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:
return a + b + c
calc = Calculator()
print(calc.add(5))
print(calc.add(5, 10))
print(calc.add(5, 10, 15))
UNIT 5
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:
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.
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()
ANS)
import mysql.connector
from mysql.connector import Error
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)
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()