Pythpn Cheat

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Explain Special character in Regular Expression.

→Special character in regular expression. in Python are used to match Specfic pettern in
text data *There are dame of the commonly used Special characters in python regular
expression.. *1) ’^’ -- matches the start of a string. 2) $ -- matches the end of the string
(3)’.’matches any single character except newline(4) ‘*’matches zero or more Occurrences
of the preceding character.(5) ‘+’matches one or more Occurrences OF The preceding
character.6)’?’ - matches zero or one occurrences the preceding character..7) ':' - Escape a
special character, allowing it to be used as a regular character. 8)’ []’ matches any charact es
with in the brackets 9) ‘[^]’= matches any character not with in.the brackets. (10)"()" group
character together as a single Unit
These Special characters can be Used with other character & quantifiers By Using there
special Characters in Combination with alphanumeric characters, you can create complex
pattern... to match Specific strings.
3) Explain deadlocks in threads
→A Deadlock in threading Occur when two or more thread are blacked, waiting for each
other to release a resource, but none of them can proceed. Because they are all waiting for
another thread to release a Source. In other words, a deadlock. Occur when there is a
Circular dependency between the threads, & none of them can continue without releasing a
resource that is being held by another thread. To avoid deadlocks in Python, it's important
to Carefully design your code & to manage Shared resources correctly. The includes
ensuring that threads release resources they no longer need & never holds multiple
resources at the Same time you can also Use Synchronization. Primitive like locks &
Semaphores & Condition Variable to help prevent deadlock & ensures Safe access to shared
resources.
Q)write a program to explain the test () & seek ()methods
→Tell ()
Tell () returns the Current position of the file painter from the beginning of the File()
For eg:- "F = Open (" demofile.txt","r")
print (F teu())
Seek ()
If we want to move the File point es to another. Position, we can use the Seek ()method.
For eg:-
F = Open("demofile.txt", "r")
F. Seek (4)
print (f. readline (1)
Q)Explain the difference between readline () & readlines
→in Python readline () & readlines () are two method used for reading input from a file
1)readline ()
readline () is a method that read a single line from a file + return it as a string Each time
readline ()' is called, it reads the next line From the File. If the end of the File is reached.'
readline ()’ return an empty string
eg. with open("File.txt', 'r') as F:
line = f.readline()
while line:
print (line.())
line = F.rendline()
Here readline ()'is Used inside a loop to read. each line of the file & print it to the console.
2) readlines ()
readlines () is a method that read all lines. From a File & return them as a list From a File
&return them as a list of strings Each string in the list represent a line from. the File
Eg :-with Open ('File.txt', 'r') as F·
. lines =F.readlines ().
. For line in lines :
. print( Line strip ())

Q5) Explain calendar module in Python.


→ The Calendar module in Python provides Function & classed to work with calendars It
allows you to generate calendars For Specific month d years, determine whether A year is a
leap year, I find the day of the Week for a given date. The module includes Function such as
calendar month ()to generat Calendars Calendar isleap () to determine leap year, and
calendar weekday (1'to Find the day of the week for a given date. The "Calendar' module is
Useful For working with date & time data in Python Program.
Q6) Write A program to write the text "Good Morning" into a file.
→Here's a Python Program that creates a File named ‘greeting.txt' & Writes the text "good
morning" into it:
with open("greeting txt", "w") as File:
. File.write("Good Morning")
In this Program, the "with" statement is used. to Open the File named "greeting.txt" in write
mode("w") "The created a new file or overwrites an existing file with the same name. "The
'as' keyword is used to assign the file object to take the Variable "File". "The Write (1.
method is then called on the file object to write the text "Good morning" to the File
Q1) Write a program to Create table & insert records to the table in Python. --
→impact Sqlite3.
Conn = Sqlites3 connect ('example.db’)
Conn.execute(" CREATE TABLE USERS.
. (ID INT PRIMARY KEY NOT NULL,
. NAME TEXT NOT NULL,
. AGE INT NOT NULL);")
Conn execute ("INSERT INTO USERS (NAME AGE). VALUES (' John, 30)")
Conn execute ("INSERT INTO USER (NAME. AGE). VALUES ('Jane', 25)").
print (" Table Created successfully")
Conn.commit()
Conn.close()
Q2) Explain Assert Statement in Python.
→ In Python, the 'assert' Statement is used to check whether a given expression is true or
False. If the expression is true then. nothing happens But if the expression is false then an
Assection Error is raised with an Optional error message.
The Syntax of the 'assent' statement is as Follows
asset expression, message. If no message is specified, a default error message is used. The
assert statement is often Used For debugging purposes to catch Unexpected. Condition
&ensure that a program be haves. as expected However, it is important Io. note that 'assest
statement should only be used for debugging & not as a form of error handling in
production Code
Q3) What is exception? Explain with examples.
→ In Python an. exception is an error that Occur during the execution of a program when an
exception Occurs, the program tops runnings & an errors message is displayed. Exception
can be caused by a variety of reason, such as an invalid input, incorrect Syntax, or a problem
with a file. There are many types of exception in Python, and each has its some example of
exception in Python
1) Zero Division Error: Occurs when a number is divided by zero
x = 5/0
. Zero Division Error: Division by Zero..
2) Name Error: Occur when a Variable is not defined
. punt (x)
Name Error: name y is not defined...
the object
(3) Type Error Occurs when an Operation or Function is applied to the wrong type of object
. 5+3
Q4) write anagram to show client Server. Communication using top in Python.
→ server cade..
.Impact Socket
PORT 65432
with Sacket Socket(Socket AF_INET, socket.sock_STREAM)
sblind (HOST, PORT))
S.listen()
print('Server listening on{}:{}’ Format (HOST,PORT)
Conn addr = S. accept ()
with Conn
print('Connected by; addr).
while True:
data = conn recv (1024).
if not data:
break
Conn send all (data)
Client Code:-
import Socket
HOST=’127.0.0.1’
PORTE=65931
with socket. Sacket (Socket AF INET, Socket.sock_STREAM) as s
s.Connect ((HOST, PORT)
S. Sendall (b'Hello, world')
data= S.recv (1024)
print ((Received, repr (data))
To run this program, first run the Server Code in One terminal window.
$ Python Seaver.py
Then run the client Code in another terminal window
$ Python client.py
You should see the message. "Received 'Hello. World" printed in the client window,
indicating that the Server received the message fit back to the client.
Q5) Write a program to Create a frame widget in. Python
→Import tkinter as tk
root = tR. Tr ()
Frame = tk. Frame (root, by = "Value", bd=5)
labell= tR.Label (Frame, text = "Hello, world!"
Font ("Arial, 18))
label pack (side ="top")
button 1 = tk. Button (Frame, text = "click me!", root destroy, Font = ( "Arial", 12
button 1 pack (Side = "left", pady = 10).
Button2=tR. Button (Frame text "Quit", Commands root destroy font (""Arial", 18]).
button & pack (side="right", pndy = 10)
Frame pack
root mainloop().
Q6) write a program to show execution of finally black in Python
→try: x=5/0
except Zero Division Error:
print ·("Cannot divide by zero")
Finally
print(" This Code always run, regardless of whether an exception was raised or not")
Q7)Write a Program to draw rectangle On Canvas.
→ Import tkinter as tk
root = tk. TR()
Canvas = tk. Canvas (root, width = 400 height=400)
Canvas pack ()
rat = Canvas. Create rectangle (50,50, 150, 150 "Fill = "blue", outline "red," width= 2) rout
mainloop()
Q3) what is duck typing in Python.
→Duck typing in a concert in Python (and other Programming languages) that focuses on an
object behaviour father than its type. it means that if an object walks like a ducks, like a
duck, & quacks like a duck, then it's a duck-Or, more precisely, it can be treated. asif it were
a duck. *In Python this means that if an object has the methods or attributes that are
required For a particular nice of code to run Correctly, then that object can be Used in that
code. regardless of its actual class or type. This allows. For more Flexible & dynamic
programming as Subject can be Used in a wider range of Contexts, as long as they be have
approximately.
Q)Explaia multilevel inheritance with Example:
→1)when first class is herited by second class, Second class is herited by third class & So. On
Caused multilevel in heritance2) in the type of inheritance each desired. class is the base
class for the next class. 3) in the type of inheritance atleast three class are Compulsory
Base class A //base of B
Base/derived B //Base of c but derived of A
Derived C // Derived of B
EX:-
Class Rectangle :
. def rec_area (self, width, height).
. area = height* width.
. "print ("Area of Rectangle." area)
class Square (Rectangle):
. def Sau area (Self, side):
. area: Side* side.
. print ("Area of Square:", area)
class Triangle (Square):
. deftri_area (self,length, breadin):
. area = 0.5" length breadth
. print("Alen of Triangle!", area)
Obj=Triangle ()
Object,rec_area (10, 20)
obj.Squ_area. (12)
obj.tri_are (12,25)
Output:-Area of Rectangle :200
. Area of Square: 144
. Area of Triangle: 150.0
Q.) Explain Operator Overloading in Python
→Operator Overloading in Python refer to the Lability to define custom behaviours For
Operator (+, -, +, /, %, etc) when Used with Custom object. The allows programmers to make
their objects behave like built in types, providing more natural & intritive Syntax *In Python,
Operator Overloading us achieved by defining Special method. Such as add O For the 'F'
Operator or _mul ()' For the +) Operator, with in a class. These method define how the
Operator should behave applied to instances of the class. *For examples!- a class
representing a complex. number could define the add_()' method to add two complex
numbers togethers in the expected way "Then, the Operator can be Used with instance of
the class, & the Custom Ladd. (I' method will be called automatically. Operator Overloading
can be a powerful tool For Creating more expressive & readable Code,. but it should belised
judiciously to avoid. Confusion + maintain readability.
04) write a program to show polymorphism in Python..
→ class Animal:
def_init_ (Self, name):
Self name = name
def Speak (self):
pass
Class Dag (Animal):
def Speak (self):
"return" woof!"
class cat (Animal)..
def Speak (self):
return "meow!”
class cow (Animal):
def Speak (Self)
return “(mob)”
def animal Speak (animal).
-print (animal Speak())
dog = Dog ("Rover")
Cat= Cat (" FLUFFY").
Cow = cow("Bessie")
animal. Speak (dog)
animal. Speak (Cat).
animal Speak (Cow)
Q5) What is Interface in Python
→ In Python an interface is a set of methods. that a class must implement. It defines a
Contract between a class & the code that Users it, ensuring that the class will behave in a
certain way. In other words, an inter Face in Python is a blue print or a set of guidelines. For
a class to follow.
Python doesn't have a Specific keyword or Syntax For interface, but they can be Created
Using abstract base classes defined in the abc' module ABC, define a set of abstract methods
that must be implemented by any Concrete class that inherits from them. This ensure that
any class that claims to be implement the interface will have the necessary method #
behaviours
Interfaces help of promote code reuse madulasity, allowing different put at a Program to
interact with other without Knowing the details of how earn class is implemented They also
make it easier to write textable code by isolating the bekas of each class & allowing it to be
tested indipendently.
Q) Write a program to show multiple inheritance in Python
→class Rectangle
def rec area (Self, height, width):
area = height*width
print ("Area of Rectangle.", area).
class Square:
def Square (Self, Side).
area = Side *Side
print("Area of Square.", area).
Class Triangle (Rectangle Square)
def trian_area (self, length breadth).
area =0.5" length* bredth
print ("Area of Triangle L", area)
Obj = Triangle ()
obj rec_area (l0,20)
obj Squ _area (12)
obj. teri area (12,25)
Output:- Area of Rectangle :200
Area of Square 144
Area of Triangle: 150.0
Here Rectangle & Square are Bare class z Triangle is derived class so we can call al the
Function Using object of Triangle class.

You might also like