0% found this document useful (0 votes)
17 views

Python

Python notes

Uploaded by

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

Python

Python notes

Uploaded by

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

Q)Python Built-in Exceptions:- Python has a number of built-in exceptions, such as

the well-known errors SyntaxError, NameError, and TypeError. These Python


Exceptions are thrown by standard library routines or by the interpreter itself. They
are built-in, which implies they are present in the source code at all times.Python’s
built-in exceptions are organized hierarchically, which means that they derive from
common base classes. As a result, they are nearly identical in terms of attribute and
method scope. The table below lists the built-in exception Types and the most typical
conditions in which they occur.
Q)What is Keras? Keras is a minimalist Python library for deep learning that can run
on top of Theano or TensorFlow.It was developed to make implementing deep
learning models as fast and easy as possible for research and development.It runs on
Python 2.7 or 3.5 and can seamlessly execute on GPUs and CPUs given the underlying
frameworks. It is released under the permissive MIT license.Keras was developed and
maintained by François Chollet, a Google engineer using four guiding
principles:1.Modularity: A model can be understood as a sequence or a graph alone.
All the concerns of a deep learning model are discrete components that can be
combined in arbitrary ways.2.Minimalism: The library provides just enough to
achieve an outcome, no frills and maximizing readability. 3.Extensibility: New
components are intentionally easy to add and use within the framework, intended
for researchers to trial and explore new ideas.Python: No separate model files with
custom file formats. Everything is native Python.
Q)What is Tkinter?Tkinter is the inbuilt python module that is used to create GUI
applications. It is one of the most commonly used modules for creating GUI
applications in Python as it is simple and easy to work with. You don’t need to worry
about the installation of the Tkinter module separately as it comes with Python
already. It gives an object-oriented interface to the Tk GUI toolkit. tkinter is not a thin
wrapper, but adds a fair amount of its own logic to make the experience more
pythonic. This documentation will concentrate on these additions and changes, and
refer to the official Tcl/Tk documentation for details that are unchanged.
Q)What is pandas ?It is one of the most widely used python everything data science.
It provides high performance easy to use structures and data analysis tool.unlike
numpy library which provides object for multi dimensional arrays.Panda is an open
source providing hyperformance easy to use data structures and data analysis tools
for the python programming language.Pandas provides in which memory 2-D table
object called dataframe is a like spreadsheet with column name and labels.The
pandas library emerged into a powerhouse of data manipulation tasks in python
since it was developed 2008 with its intuitive sintex and flexible data structure it's
easy to learn and enables faster data computation.
Q) Lists :- A list is one of the major Python data structures used to contain a setlist of
things called items. Like arrays, list to tuple Python helps keep similar types of data
values together, condensing their code together. This helps perform several detailed
operations on multiple values at the same time. For example, a folder of songs on
your desktop has different other subfolders adjusted following different genres for a
hassle-free collection. List to tuple Python is used to improve efficiency and help the
system manage all the values together.
Q)Tuples:- tuples also contain a set of objects in an ordered manner. These objects
are kept separated by commas. Tuples are immutable and do not allow the entrance
of additional objects once a tuple is created. Tuples are incapable of expanding or
making modifications; therefore, they differ from lists. Removing elements is also not
possible from tuples which restrict its collection. The immutability often serves as an
advantage in delivering faster, efficient results.
Q)Asseration:- Assration is a Boolean expression to self check and assumption about
about the internal state of a function or object. If true nothing happens otherwise
execution halts and an error is thrown.For example file writing a division function
you are confident the divisor shouldn't be zero you assert diviser is not equal to
zero.Asseration are carried out by the assert statement. Program programmers of a
place assertions at the start of a function to check for valid input, and after a function
call to check for valid output.
Q) Raise Statement:-We can reach an existing exception by using red keyword, so we
just simply right age keyword and then the name of the exception.The raise
statement always the programmers to force a specified exception to occur.Exception
is the type of exception and argument is a value for the exception argument. This
argument is optional. The execution argument is known if we does not supply in any
argument the argument traceback is also optional if this is used than the trace back
object is used for the exception this is rarely used in programming.
Q) Numpy:- It is a python library for scientific computing in python. It contains a
collection of tools and techniques that can be used to solve on any computer
mathematical models of problems in science and engineering.One of these tools is a
high performance multidimensional array object that is a powerful data structure of
efficient computation of arrays and matrices to work with these arrays there is a huge
amount of high level mathematical functions operate on the matrices and
arrays.Numpy is a general purpose arrays processing package.Numpy is the core
library of scientific computing in python.
Q) Explain methods for geometry management in tkinter with examples .Tkinter,
geometry management refers to the organization and positioning of widgets within a
container, such as a window or a frame. Tkinter provides three main geometry
managers: pack, grid, and place. Each manager has its own approach to organizing
and placing widgets. 1.Pack Geometry Manager:The pack geometry manager
organizes widgets in blocks before placing them in the parent widget. Widgets are
packed in either a horizontal or vertical direction.2.Grid Geometry Manager:The grid
geometry manager organizes widgets in a table-like structure, allowing you to specify
the row and column in which each widget should be placed.3.Place Geometry
Manager:The place geometry manager allows you to specify the exact position and
size of a widget within its parent widget.
EX. from tkinter import Tk, Button
root = Tk()
button1 = Button(root, text='Button 1')
button1.pack()
button2 = Button(root, text='Button 2')
button2.grid(row=0, column=1
button3 = Button(root, text='Button 3')
button3.place(x=50, y=50)
root.mainloop()
Q)Explain Exception handling in python with example? An exception is an event
which occurs during the education of program that disrupts the normal flow of the
programs instructions.The exception handling is a process that provides a way to
handle exceptions that occur at run time. The exception handling is done by writing
exception handlers in the programs.Python script encounters a situation that it
cannot cope with it raises and exception and exception is a python object at
represents and error.1.try:- top statements that may chords during runtime are to be
written in the tryblock.2.expect block:- it is written to display the execution details to
the user when certain exception occurs in the program. 3.finally block :- this is the
last block return file writing an exception handler in the program which indicates the
set of statements that are used to clean up the resources used by the program.
Ex:-try: x=1/0
except zero division error
Print("you can not devided by zero")
Q)Anonymous Function:- Anonymous functions are the functions that are not bond
name . It means and animals function does not have a name.While normal functions
are defined using a Def keyword in python and anonymous functions are defined using
the lambda keyboard. Hence and anonymous functions are also called lambda
functions.Function can take any number of arguments but can only have one express
and lambda is created without using def keyword.
Q) Explain IS-A Relationship and Has - A relationship with example? In object-
oriented programming (OOP), an IS-A relationship represents inheritance, where one
class inherits from another class. The class that inherits is known as the subclass or
child class, while the class being inherited from is called the superclass or parent class.
The IS-A relationship signifies that the subclass is a type of the superclass. #has-A:- Is
also known as composition. It represents a relationship between a class and an object.
The class contains a reference to the object, and can use the object's properties and
methods. For example, the class Car has a HAS-A relationship with the class Engine.This
means that a Car has an Engine.

Q)Explain function Arguments in detail? function arguments are used to pass


information into functions. They allow us to provide input values to a function, which
the function can then use to perform specific tasks. There are several types of function
arguments in Python, including: 1.Positional Arguments: These are arguments that
are passed to a function in the order they are defined in the function's parameter list.
The values are assigned to the corresponding parameters based on their position. 2.
Keyword Arguments: These are arguments that are passed to a function using the
parameter names as keywords. This allows us to specify the values for specific
parameters, regardless of their position in the parameter list. 3. Default Arguments:
These are arguments that have pre-assigned default values. If no value is provided for
these arguments when the function is called, the default values are used. 4. Arbitrary
Arguments: These are arguments that allow us to pass a varying number of values to
a function. In Python, we can use args to represent arbitrary positional arguments.

Q) Explain any three widgets in tkinter in brief in python. Ans :- 1) Button The Button
widget is used to display buttons in your application. You can use buttons to perform
actions, such as opening a new file, saving a file, or closing an application. 2) Label The
Label widget is used to display text in your application. You can use labels to display
information, such as the name of your application, the current date and time, or the
instructions for using your application. 3) Entry The Entry widget is used to display a
single-line text field in your application. You can use Entry widgets to allow users to
enter text, such as their name, email address, or password.
Q) what is inheritance write its benefits and syntax? Ans :- 1) Inheritance allows us to
define a class that inherits all the methods and properties from another class. 2) Parent
class is the class being inherited from, also called base class. 3) Child class is the class
that inherits from another class, also called derived class. 4) Inheritance provides code
reusability, readability, and transition of properties which helps in optimized and
efficient code building.. Benefits :- 1. Less code repetition, as the code which is
common can be placed in the parent class, hence making it available to all the child
classes. 2. Structured Code: By dividing the code into classes, we can structure our
software better by dividing functionality into classes. 3. Make the code more scalable.
Syntax :- class BaseClass : Body of base class class Derived Class (BaseClass) : Body of
derived class.
Q)Write a Python program to check whether a number is in a given range.
def is_number_in_range(number, lower_limit, upper_limit):
return lower_limit <= number <= upper_limit
lower_limit = 10
upper_limit = 50
user_input = float(input("Enter a number to check if it's in the range: "))
if is_number_in_range(user_input, lower_limit, upper_limit):
print(f"{user_input} is in the range between {lower_limit} and {upper_limit}.")
else:
print(f"{user_input} is outside the range between {lower_limit} and {upper_limit}.")
Q) Write a Python program to display current date and time.
import datetime
current_datetime = datetime.datetime.now()
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print("Current Date and Time:", formatted_datetime)
Q) Write a python class to accept a string and number 'n' from user and display 'n'
repetition of strings by overloading *operator
class StringRepeater:
def _init_(self, input_string):
self.input_string = input_string
def repeat(self, n):
return self.input_string * n
user_string = input("Enter a string: ")
user_n = int(input("Enter the number of repetitions (n): "))
string_repeater = StringRepeater(user_string)
result = string_repeater.repeat(user_n)
print(f"{user_string} repeated {user_n} times: {result}")
Q)Write python GUI program to generate a random password with upper and
lower case letters
import random
import string
def generate_password(length):
characters = string.ascii_
letters password = ''.join(random.choice(characters) for _ in range(length))
return password
length = int(input("Enter the desired length of the password: "))
password = generate_password(length)
print("Generated password:", password)
Q)Write a python program to accept string and remove the characters which have
odd index values of given string using user defined function. def
remove_odd_characters(string):
new_string = ""
for index in range(len(string)):
if index % 2 == 0:
new_string += string[index]
return new_string
input_string = input("Enter a string: ")
result = remove_odd_characters(input_string)
print("String with odd-indexed characters removed:", result)

Q)Write a python program to create a class circle and compute the Area and the
circumferences of the circle. (Use parametrized constructor)
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return math.pi * self.radius ** 2
calculate_circumference(self):
return 2 * math.pi * self.radius
radius = float(input("Enter the radius of the circle: "))
circle = Circle(radius)
print("Area of the circle:", circle.calculate_area())
print("Circumference of the circle:", circle.calculate_circumference())

Q)Write a python script using class to reverse a string word by word


class StringReverser:
def __init__(self, string):
self.string = string
def reverse_words(self):
return ' '.join(self.string.split()[::-1])
input_string = input("Enter a string: ")
reverser = StringReverser(input_string)
reversed_string = reverser.reverse_words()
print("Reversed string:", reversed_string)

You might also like