#Short Questions
[Link] Output Using the Format Method with example.
=The format() method takes more manual effort than other methods. We use
{} to mark the substitution of variables and provide detailed formatting
directives, but we also need to provide the formatted information.
Example:
print('{} {}'.format('Hello', 'World'))
print('{0} to {1}'.format('Welcome', 'JavaTpoint'))
print('{1} to {0}'.format('Welcome', 'JavaTpoint'))
Output:
Hello World
Welcome to JavaTpoint
JavaTpoint to Welcome
[Link] output using the String Method
=We can also format the output using the string slicing and concatenation
operations. The string type has some methods that help format output in a
fancier way. Few methods which helps to formatting an output - [Link](),
[Link](), and [Link]().
[Link] to read file in python
# Opening the file with absolute path
fp = open(r'E:\demos\files\[Link]', 'r')
# read file
print([Link]())
# Closing the file after reading
[Link]()
Output:
Welcome to [Link]
This is a [Link]
Line 3
Line 4
Line 5
[Link] two file methods with example.
1. read(): This method is used to read the entire contents of a file and return them as a
string.
Example:
# Open a file for reading
file = open("[Link]", "r")
# Read the entire contents of the file and assign it to a variable
content = [Link]()
# Close the file
[Link]()
# Print the contents of the file
print(content)
2. write(): This method is used to write data to a file. If the file does not exist, it will be
created. If it does exist, the contents will be overwritten.
Example:
# Open a file for writing
file = open("[Link]", "w")
# Write some text to the file
[Link]("Hello, world!")
# Close the file
[Link]()
[Link] and Except statement with example.
=Try and except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try clause and the
statements that handle the exception are written inside except clause.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
[Link] keyword in python
In this keyword finally, It always executed after the try and except blocks. The
final block always executes after normal termination of try block or after try
block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
[Link] in Object Oriented Python
Polymorphism contains two words "poly" and "morphs". Poly means many,
and morph means shape. By polymorphism, we understand that one task can
be performed in different ways.
[Link] constructor with example
A constructor is a special type of method (function) which is used to initialize
the instance members of the class. It is used to create an object.
Constructors can be of two types.
1. Parameterized Constructor
2. Non-parameterized Constructor
1. class Employee:
2. def __init__(self, name, id):
3. [Link] = id
4. [Link] = name
5.
6. def display(self):
7. print("ID: %d \nName: %s" % ([Link], [Link]))
8.
9.
10. emp1 = Employee("John", 101)
11. emp2 = Employee("David", 102)
12.
13. # accessing display() method to print employee 1 information
14.
15. [Link]()
16.
17. # accessing display() method to print employee 2 information
18. [Link]()
Output:
ID: 101
Name: John
ID: 102
Name: David
[Link]() function with example
Python's [Link]() function finds and delivers the very first appearance of a
regular expression pattern. In Python, the RegEx Match function solely
searches for a matching string at the beginning of the provided text to be
searched.
Example
1. import re
2. line = "Learn Python through tutorials on javatpoint"
3. match_object = [Link]( r'.w* (.w?) (.w*?)', line, re.M|re.I)
4.
5. if match_object:
6. print ("match object group : ", match_object.group())
7. print ("match object 1 group : ", match_object.group(1))
8. print ("match object 2 group : ", match_object.group(2))
9. else:
10. print ( "There isn't any match!!" )
Output:
There isn't any match!!
[Link]() function with example
The [Link]() function will look for the first occurrence of a regular
expression sequence and deliver it. It will verify all rows of the supplied string,
unlike Python's [Link]().
Example
1. import re
2.
3. line = "Learn Python through tutorials on javatpoint";
4.
5. search_object = [Link]( r' .*t? (.*t?) (.*t?)', line)
6. if search_object:
7. print("search object group : ", search_object.group())
8. print("search object group 1 : ", search_object.group(1))
9. print("search object group 2 : ", search_object.group(2))
10. else:
11. print("Nothing found!!")
Output:
search object group : Python through tutorials on javatpoint
search object group 1 : on
search object group 2 : javatpoint
[Link]() function
The findall() function is often used to look for "all" appearances of a pattern.
The search() module, on the other hand, will only provide the earliest
occurrence that matches the description. In a single operation, findall() will
loop over all the rows of the document and provide all non-overlapping regular
matches.
[Link] to connect to mysql database.
To test database connection here we use pre-installed MySQL connector and
pass credentials into connect() function like host, username and password.
Syntax to access MySQL with Python:
import [Link]
db_connection = [Link](
host="hostname",
user="username",
passwd="password"
)
Q. Fetchall(), Fetchmany() methods to read data from mysqltable
The fetchall() method retrieves all the rows in the result set of a query and
returns them as list of tuples. (If we execute this after retrieving few rows it
returns the remaining ones).
The fetchone() method fetches the next row in the result of a query and returns
it as a tuple.
The fetchmany() method is similar to the fetchone() but, it retrieves the next set
of rows in the result set of a query, instead of a single row.
[Link] of Seek() Method in file operations.
The seek() method is used to change or move the file's handle position to the
specified location. The cursor defines where the data has to be read or written in the
file
seek()= Set file pointer position in a file
#Long Question
[Link] to demonstrate inheritance in python
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. [Link]()
10. [Link]()
Output:
dog barking
Animal Speaking
[Link] to demonstrate method overriding
1. class Animal:
2. def speak(self):
3. print("speaking")
4. class Dog(Animal):
5. def speak(self):
6. print("Barking")
7. d = Dog()
8. [Link]()
Output:
Barking
[Link] to demonstrate operator overloading.
1. print (14 + 32)
2.
3. # Now, we will concatenate the two strings
4. print ("Java" + "Tpoint")
5.
6. # We will check the product of two numbers
7. print (23 * 14)
8.
9. # Here, we will try to repeat the String
10. print ("X Y Z " * 3)
Output:
46
JavaTpoint
322
XYZXYZXYZ
[Link] program to create File menu having New and Open options.
from tkinter import *
root = Tk()
menu = Menu(root)
[Link](menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=[Link])
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()
Output:
[Link] program to fetch records from employee table of mydb database and
display them.
import [Link]
# establish connection to database
mydb = [Link](
host="localhost",
user="yourusername",
password="yourpassword",
database="mydb"
)
# create a cursor object
mycursor = [Link]()
# execute SQL query to fetch records from employee table
[Link]("SELECT * FROM employee")
# fetch all the rows using fetchall() method
rows = [Link]()
# display the records
for row in rows:
print(row)
[Link] to Create a Table in MySQL with Python
import [Link]
db_connection = [Link](
host="localhost",
user="root",
passwd="",
database="my_first_db"
)
db_cursor = db_connection.cursor()
#Here creating database table as student'
db_cursor.execute("CREATE TABLE student (id INT, name
VARCHAR(255))")
#Get database table'
db_cursor.execute("SHOW TABLES")
for table in db_cursor:
print(table)
Output:
('student',)
[Link] program for simply using the overloading operator for adding two
objects.
1. print (14 + 32)
2.
3. # Now, we will concatenate the two strings
4. print ("Java" + "Tpoint")
5.
6. # We will check the product of two numbers
7. print (23 * 14)
8.
9. # Here, we will try to repeat the String
10. print ("X Y Z " * 3)
Output:
46
JavaTpoint
322
XYZXYZXYZ
[Link] to perform multiple inheritance in python
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print([Link](10,20))
12. print([Link](10,20))
13. print([Link](10,20))
Output:
30
200
0.5
[Link] to demonstrate parametric constructor.
1. class Student:
2. # Constructor - parameterized
3. def __init__(self, name):
4. print("This is parametrized constructor")
5. [Link] = name
6. def show(self):
7. print("Hello",[Link])
8. student = Student("John")
9. [Link]()
Output:
This is parametrized constructor
Hello John
[Link] to demonstrate non-parametric constructor.
1. class Student:
2. # Constructor - non parameterized
3. def __init__(self):
4. print("This is non parametrized constructor")
5. def show(self,name):
6. print("Hello",name)
7. student = Student()
8. [Link]("John")
[Link] to create class and instance of employee.
class Employee:
def __init__(self, name, salary):
[Link] = name
[Link] = salary
emp1 = Employee("John Doe", 50000)
print([Link])
print([Link])
[Link] to depict Raising Exception
# Program to depict Raising Exception
try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or not
output:
Traceback (most recent call last):
File "/home/[Link]", line 5, in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there
[Link] program to demonstrate finally
# Python program to demonstrate finally
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
[Link] to handle multiple errors with one except statement
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print(f"The result is {result}.")
except (ValueError, ZeroDivisionError):
print("Invalid input or division by zero.")
[Link] program to handle simple runtime error
# Python program to handle simple runtime error
#Python 3
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
[Link] program to demonstrate [Link](), [Link](), and [Link]()
formatting
1. str1 = "I love JavaTpoint"
2. # Printing the center aligned
3. # string with fillchr
4. print ("Center aligned string with fillchr: ")
5. print ([Link](30, '$'))
6.
7. # Printing the left aligned
8. # string with "-" padding
9. print ("The left aligned string is : ")
10. print ([Link](40, '&'))
11.
12. # Printing the right aligned string
13. # with "-" padding
14. print ("The right aligned string is : ")
15. print ([Link](40, '-'))
Output:
Center aligned string with fillchr:
$$$$$$I love JavaTpoint$$$$$$$
The left aligned string is:
I love JavaTpoint&&&&&&&&&&&&&&&&&&&&&&&
The right aligned string is :
-----------------------I love JavaTpoint