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

python ❤️

The document provides an overview of various Python programming concepts, including advantages of libraries like Pandas and NumPy, exception handling, and the use of classes and methods. It discusses data types, inheritance, and built-in functions, along with practical examples for clarity. Additionally, it highlights the significance of GUI development using Tkinter and the creation of custom exceptions.

Uploaded by

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

python ❤️

The document provides an overview of various Python programming concepts, including advantages of libraries like Pandas and NumPy, exception handling, and the use of classes and methods. It discusses data types, inheritance, and built-in functions, along with practical examples for clarity. Additionally, it highlights the significance of GUI development using Tkinter and the creation of custom exceptions.

Uploaded by

Shreya Gosavi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

what are the list out any 4 What is the use of What is a class What is the use of What

What is the use of What is the use of Write the definition of custom
advantages of label option. the random() variable? * and ** operators a try-finally block? a class method. exception
pandas? •text module? A variable shared on tuples? Ensures that the A class method is a A custom
Provides fast, •bg It generates random by all instances of * unpacks the tuple finally block is method that operates on exception in
flexible, and (background numbers or performs a class, defined into individual executed regardless the class rather than Python is a user-
powerful data color) random operations within the class but elements. of whether an instances. It is defined defined exception
manipulation. •fg (foreground like shuffling a outside any ** is used in function exception occurs using the @classmethod that allows you to
Handles missing color) sequence or selecting method. arguments for How is the grid() decorator. create specific
data efficiently. •font random items.
Define the term unpacking geometry python error messages or
Explain any two management class MyClass:
Supports various what are the bind method. dictionary-like data. handle specialized
file formats (CSV, tuple operations method used in @classmethod def
properties of The bind method How is the grid() error conditions in
Excel, SQL). with an example. Tkinter? example(cls): print("This
dictionary? links a specific geometry your application.
Allows easy data •Indexing: Access an The grid() method is a class method.")
•Unordered.
element by position.
event (e.g., mouse management Write the syntax of
You can create
cleaning and organizes widgets in a
•Key-value pairs.
python
clicks) to a method used in the raise statement
custom exceptions
analysis. grid layout using rows
•Keys must be function in a GUI Tkinter? and explain it.
by subclassing the
state the uses of unique and
t = (1, 2, 3) print(t[1])
application. The grid() method
.
and columns. built-in Exception
tensor flow? immutable.
# Output: 2
What are special organizes widgets in python Syntax: class. Steps to
Machine learning •Concatenation: button = Button(root, python Create a Custom
•Values can be of
Combine two tuples. operators in a grid layout using raise
and deep text="Click Me") Exception:
any data type.
python Python? rows and columns. ExceptionType("Message
learning button.grid(row=0, 1.Subclass the
development. list out t1 = (1, 2) t2 = (3, 4) Identity operators: python
column=0) ") Exception class:
Image and geometry print(t1 + t2) # is, is not button = Button(root, Explanation: Used to Create a new class
managemen Output: (1, 2, 3, 4) Membership text="Click Me") Write the use of an trigger an exception
speech import statement that inherits from
t methods operators: in, not button.grid(row=0, explicitly.
recognition. List out any 5 button column=0) with an example. the Exception
Natural language •. pack() options in Python.
in What is Tkinter in class or any of its
•grid() Write any two What is the The import statement Python?
processing text subclasses.
•place() common use of a try- is used to include Tkinter is Python’s
(NLP). command 2.Optionally,
Difference exceptions in finally block? external modules or standard GUI library for
Building neural bg (background customize the
between Python. Ensures that the libraries. creating graphical user
networks. color) __init__ method:
write syntax Python list fg (foreground color)
ValueError finally block is python interfaces. You can provide
of raise and NumPy font
IndexError executed import math Break and Pass additional
statement? array. regardless of print(math.sqrt(16)) # statements in Python.
How to create functionality, such
Lists can hold What is Seaborn? whether an Output: 4.0 •Break: Exits a loop
raise a class and exception What is Scikit- as custom error
mixed data Seaborn is a Python prematurely.
Exception("Er object in occurs. learn? messages or
types; NumPy data visualization python
ror message") Python? attributes.
arrays require library built on What is the A Python library for for i in range(5): if i == 3:
State any four uniform data Matplotlib, providing
python
syntax of a machine learning and break print(i)
3.Raise the custom
time module types. advanced statistical
class MyClass:
constructor in data analysis, •Pass: A placeholder
exception: Use the
functions. NumPy arrays plots.
def __init__(self,
Python? offering tools for statement that does
raise keyword to
time() name): self.name classification, trigger the custom
support faster python nothing.
ctime() = name obj = regression, exception in your
mathematical class MyClass: def python
sleep() MyClass("Exampl clustering, and more. code.
operations. __init__(self): pass if True: pass
strftime() e")
explain different explain inheritance explain Exception explain Principal of explain any explain Anonymous how to define
Datatypes in in brief with syntax Handling and its keras three widgets in function function in
python. types in python tkinter in brief An anonymous python?explain with
Inheritance is a feature Keras is a high-level
1. Numeric Types deep learning library
Tkinter is the function in Python is a suitable example
in object-oriented Exception handling in standard GUI function that is defined
int: Represents integers, designed for building a function is a block of
programming that Python is used to (Graphical User without a name. These
e.g., 1, -5. and training deep reusable code that
allows a class manage errors that Interface) library for are also known as
float: Represents learning models performs a specific
(child/derived class) to occur during program Python, offering a lambda functions. The
decimal or floating-point efficiently. Its principles task. Functions help
inherit properties and execution, preventing variety of widgets to purpose of using
numbers, e.g., 3.14, -0.1. are: organize code, reduce
methods from another the program from create interactive anonymous functions
complex: Represents 1.User-Friendliness: repetition, and make it
class (parent/base crashing. It allows applications. Here are is to simplify code
complex numbers, e.g., Keras is simple and easier to
class). It promotes code developers to respond three commonly used when a simple
3+5j. intuitive, allowing users manage.syntax
reuse and allows for to runtime errors widgets: function is needed for
2. Sequence Types to quickly build and train Def
creating hierarchical gracefully and ensure •1. LabelPurpose: a short period,
str (String): Represents neural networks with function_name(parame
relationships. the program's flow The Label widget is typically as an
a sequence of minimal code. ters):executed
Types of Inheritance continues. Types of used to display text argument to higher-
characters, e.g., "Hello", 2.Modularity: return result
1.Single Inheritance: Exceptions in Python or images on the GUI. order functions like
'Python'. Models are constructed •def: This keyword is
One child inherits from 1.Built-in Exceptions: •Usage: It is mainly map(), filter(), or
list: Represents an using modular used to define a
one parent. Predefined exceptions used to show static sorted()
ordered, mutable components like layers, function.
2.Multiple Inheritance: A like:ValueError: Raised content like Key Features of
collection, e.g., [1, 2, 3]. optimizers, and loss •function_name: The
child inherits from when a function gets an headings, Anonymous Functions
tuple: Represents an functions, which can be name of the function
multiple parents. argument of the wrong descriptions, or (Lambda Functions):
ordered, immutable easily combined or (should follow
3.Multilevel Inheritance: type.IndexError: Raised instructions. 1.No Name: Unlike
collection, e.g., (1, 2, 3). customized. standard variable
A child inherits from a when accessing an 2. Button Widget normal functions
range: Represents a 3.Extensibility: naming rules).
parent, and that parent index that is out of •Purpose: The Button defined using the def
sequence of numbers, It supports •parameters: Optional.
inherits from another range.ZeroDivisionError widget is used to keyword, anonymous
commonly used in customization by These are the values
class. : Raised when dividing create clickable functions are defined
loops, e.g., range(5). allowing users to create passed to the function
4.Hierarchical by zero.TypeError: buttons in the GUI using the lambda
3. Set Types their own layers, when called.
Inheritance: Multiple Raised when performing that can trigger keyword, and they
set: Represents an metrics, and loss •return: Optional. If
children inherit from one unsupported operations. functions when don't have a name.
unordered, mutable functions, making it ideal present, it returns a
parent. 2.User-Defined pressed. 2.Single Expression:
collection of unique for both beginners and value from the function
5.Hybrid Inheritance: A Exceptions: Custom 3. Entry Widget They are limited to a
items, e.g., {1, 2, 3}. researchers. to the caller.example-
combination of two or exceptions defined by •Purpose: The Entry single expression,
frozenset: An immutable 4.Integration with def greet():
more types of the user using classes. widget is used to which is evaluated and
version of a set. TensorFlow: print("Hello, welcome
inheritance. python accept single-line returned when the
5. Boolean Type Keras is tightly to Python!")
6.Syntax-class Parent: class user input, such as function is called.
bool: Represents True integrated with greet()
def func1(self): CustomError(Exception) names, passwords, 3.Return Value: The
or False, used in logical TensorFlow, supporting
print("This is the parent : pass try: raise or search queries. result of the
operations. efficient model training
class.") # Derived class CustomError("This is a Usage: It's commonly expression is
6. NoneType on CPUs, GPUs, or TPUs
class Child(Parent): def custom exception.") used in forms where automatically returned
None: Represents the and deployment across
func2(self): print("This except CustomError as users need to type in without the need for a
absence of a value or a various platforms.
is the child class.") e: print(e) data. return statement.
null value, e.g., None.
explain math built-in- The cmath module in NumPy Pandas Advantages of explain Built-in
module with examples? Python is designed for NumPy (Numerical Python) is Pandas is a Python library Pandas dictionary functions
The math module in working with complex a popular library in Python
numbers. import cmath designed to make data 1.Ease of UsePandas Dictionaries in Python are a
Python provides a wide used for scientific analysis easier and more
z1 = complex(3, 4) print(z1) a provides an intuitive and collection of key-value pairs,
range of mathematical computing, data efficient. It provides two
complex number is easy-to-understand where each key is unique.
functions to perform manipulation, and numerical primary data structures:
represented as a + bj, where a syntax for working with These functions allow you to
operations such as calculations. It provides Series: A one-dimensional
is the real part and b is the data, which is perfect for add, remove, modify, and
trigonometric functions, support for large, multi- labeled array.
imaginary part, and j is the both beginners and access data within dictionaries.
logarithmic functions, and dimensional arrays and DataFrame: A two-
imaginary unit. experienced data 1.len()
more. Functions in the matrices, along with a
1.datetime Module dimensional labeled data scientists. The functions •Returns the number of items
math Module collection of high-level structure, similar to a table
Provides classes for and methods are (key-value pairs) in the
math.sqrt(x)Purpose: mathematical functions to or a spreadsheet.
manipulating dates and times. optimized for speed and dictionary.
Returns the square root of
Functions: datetime.now(),
operate on these arrays.
Features of Pandas simplicity. •Example:
a number x. Key Features of NumPy
datetime.date(), 1.Data Structures (Series and 2.High python
math.factorial(x) 1.Efficient Array Operations:
datetime.strptime(), etc. DataFrame) PerformancePandas is my_dict = {'a': 1, 'b': 2, 'c': 3}
Purpose: Returns the NumPy provides an ndarray
Example: •Series: A one-dimensional built on top of NumPy, print(len(my_dict))
factorial of a number x (x!). (n-dimensional array) object,
from datetime import datetime labeled array that can hold which allows it to 2.clear()
math.pow(x, y) which is much more efficient
print(datetime.now()) data of any type. perform complex •Removes all the elements from
Purpose: Returns x raised and compact compared to
2.sys Module 2.DataFrame: A two- operations efficiently. It the dictionary, leaving it empty.
to the power of y (i.e., x^y). Python’s built-in list for handles large datasets •Example:
Provides access to system- dimensional labeled data
math.pi handling large datasets.
specific parameters and structure that resembles a with high performance python
Purpose: Returns the 2.Mathematical Functions:
functions. Useful for handling table, with rows and and speed. my_dict = {'a': 1, 'b': 2, 'c': 3}
value of π (pi), which is NumPy includes a variety of
command-line arguments and columns, and is ideal for 3.Data Handling my_dict.clear() print(my_dict) #
approximately 3.14159. mathematical functions,
interacting with the Python handling large datasets. CapabilitiesPandas can Output: {}
Example- including those for linear
runtime. 3.Data Importing and handle and manipulate 3. get(key, default=None)
Import math algebra, statistics, Fourier
Functions: sys.argv, sys.exit(), Exporting data of varying formats •Returns the value for the
Print(math.sqrt(16)) transforms, etc.
sys.version, etc. •Pandas can read from and (e.g., CSV, Excel, SQL specified key. If the key does
Built-in module 3.Vectorization: NumPy
write to various file formats databases, JSON) not exist, it returns the default
Example:
Python comes with a large allows vectorized operations, seamlessly. It also offers value (which is None by default).
import sys print(sys.version) such as CSV, Excel, JSON,
set of built-in modules that meaning you can perform robust support for 4. keys()
3.os Module and SQL databases.
provide functions and operations on entire arrays handling missing or •Returns a view object that
Provides functions for 4.Handling Missing Data
tools for performing rather than looping over
interacting with the operating •Pandas provides functions inconsistent data. displays all the keys in the
various tasks without individual elements
system, such as file to detect and handle missing 4.Rich Functionality for dictionary.
needing to install any 4.Random Number Data AnalysisWith its 5. values()
manipulation, environment data, such as filling or
external libraries. These Generation: built-in functions for data •Returns a view object that
variables, and process dropping missing values.
modules cover a wide •NumPy has a powerful
management. 5.Data Selection and Filtering cleaning, transformation, displays all the values in the
range of functionalities random module that allows
Functions: os.path.join(), •Pandas allows easy and statistical analysis, dictionary.
such as file I/O, system you to generate random Pandas makes data 6.copy()
os.remove(), os.listdir(), selection, filtering, and
operations, mathematical numbers and arrays, analysis and •Returns a shallow copy of the
os.getenv(), etc. subsetting of data.
computations, data including random integers,
Example: •Example:df['Age'] manipulation easier and dictionary
processing, and much floating-point numbers, faster.
import os print(os.getcwd()) df[df['Age'] > 30]
more. random sampling, and more.
Math module
IS - A HAS - A Frame widget in different between which are Built-in Package Assertion
relationship with relationship with Tkinter with list and tuple exception in python a package is a way of assertion is a
example example example •List: A list is mutable, structuring Python's debugging tool
exceptions are errors that
The HAS-A The Frame widget in meaning you can change module namespace used to test if a
The IS-A relationship occur during the execution
relationship in object- Tkinter is a container its elements after by using directories condition in your
is a type of of a program. These built-in
oriented programming widget that is used to creation. You can add, and files. It allows you code is True. If the
relationship used in exceptions help in
refers to the organize and group other remove, or modify items to organize related condition is False,
object-oriented managing error conditions
relationship between widgets. It acts as a in a list. Python code into it raises an
programming (OOP) and ensure that the
two classes where container to hold and Tuple: A tuple is reusable and AssertionError with
to indicate program runs smoothly
one class contains an arrange widgets in a immutable, meaning once hierarchical modules. an optional error
inheritance. It even when unexpected
instance of another graphical user interface it is created, its contents Here's an overview: message. It is
represents an "is a" situations arise.
class as an attribute. (GUI). Frames do not cannot be changed. You Key Components of a commonly used to
kind of relationship 1. RuntimeError:
This relationship display anything by cannot add, remove, or Package catch bugs during
between a class and •A generic error that occurs
indicates composition themselves but are used modify elements of a tuple 1.Directory Structure: development.
its subclass, where during the execution of a
or aggregation, where to hold other widgets. after it has been created. A package is Syntax
the subclass is a program when no other
one object "has" They are helpful in Syntax: essentially a directory python
specialized version of more specific exceptions
another object as a creating complex layouts •List: Lists are created containing a assert condition,
the parent class. This are applicable.
part of its structure. and separating different using square brackets []. collection of modules message
means the subclass is 2. KeyError:
Unlike the IS-A parts of the interface. •Tuple: Tuples are created (.py files) and/or sub- •condition: The
a type of the parent •: Raised when a dictionary
relationship (which Example-import tkinter as using parentheses (). packages. expression to
class, and it inherits key is not found.
indicates inheritance), tk •List: Lists have a slightly 2.__init__.py evaluate. If it
the behavior 3. ValueError:
the HAS-A root = tk.Tk() lower performance File:Previously evaluates to False,
(attributes and •Raised when a function
relationship root.title("Frame Widget compared to tuples required (Python 2.x an exception is
methods) of the receives an argument of the
represents a "has-a" Example") because they are mutable and early 3.x raised.
parent class. correct type but an
or "part-of" frame = tk.Frame(root, •Tuple: Tuples are faster versions), but •message
Example- inappropriate value.
relationship, where bg="lightblue", width=300, than lists when it comes optional in modern (optional): A string
class Animal: 4. TypeError:
one object contains height=200, bd=5) to iteration and access Python (3.3+).It message that
def speak(self): •Raised when an operation
another object within frame.pack(padx=20, speed. indicates that the provides context
print("Animal makes a or function is applied to an
it.example- pady=20) # Packing the Methods: directory is a package about the error.
sound")) object of inappropriate
class Engine: def frame into the main •List: Lists have more and can include Example
class Dog(Animal): type.
start(self): window built-in methods available initialization code for python
def speak(self): 5. ZeroDivisionError:
print("Engine label = tk.Label(frame, for modifying their the package.Example: # Example 1:
print("Dog barks") •: Raised when a number is
started") class Car: text="This is a label inside contents (e.g., append(), You might import Simple assertion x
class Cat(Animal): divided by zero.
def __init__(self, the frame", extend(), remove(), pop(), certain modules or = 10 assert x > 5 #
def speak(self): 6. FileNotFoundError:
engine): self.engine = bg="lightblue") sort(), reverse()). set up variables in No error, as x > 5 is
print("Cat meows") •Raised when trying to
engine def drive(self): label.pack(pady=10) •Tuple: Tuples have fewer this file. True # Example 2:
dog = Dog() open a file that does not
self.engine.start() button = tk.Button(frame, methods available since exist. Assertion with a
cat = Cat()
print("Car is driving") text="Click Me", they are immutable. They 7. NameError: message y = -1
dog.speak()
command=lambda: primarily support •Description: Raised when assert y >= 0, "y
cat.speak()
print("Button clicked")) methods like count() and a local or global name is must be non-
button.pack(pady=10) index(). not found. negative"
root.mainloop()
Abstract class Raise Statement list out any 5 button EXCEPT Clause explain methods for Geometric
Geometric management
and label options management in tkinter with exam
An abstract class in Python is a The raise statement in The except clause in Python tools
class that cannot be instantiated Python is used to Button Options: is part of the try...except the geometry management refers to
Geometric management tools
directly and serves as a blueprint explicitly trigger an 1.text: Specifies the block used for handling how widgets are arranged in the
are software or methodologies
for other classes. It often exception. It allows you text displayed on exceptions. It catches parent container (like a window or
used for handling, analyzing,
contains one or more abstract to handle error the button. specific exceptions raised frame). Tkinter provides three main
and manipulating geometric
methods, which are methods scenarios or create 2.command: during the execution of the geometry managers to control
data in various fields like
declared but not implemented in custom exceptions. Specifies the try block and executes widget layout: pack(), grid(), and
engineering, architecture, GIS
the abstract class.Abstract Syntaxraise[ExceptionT function to call alternative code. place().
(Geographic Information
classes are typically used to ype[(message)] when the button is Syntax 1. pack()
Systems), computer graphics,
define a common interface that •ExceptionType: The clicked. python The pack() method organizes
and CAD (Computer-Aided
derived classes must follow. type of exception to 3.fg (foreground): try: # Code that may raise widgets in blocks, one after the
Design). These tools enable
Creating an Abstract Class raise (e.g., ValueError, Sets the text color an exception except other. You can specify the widget’s
users to create, edit, measure,
Python provides the abc module TypeError, or a custom of the button. ExceptionType as e: # Code side (top, bottom, left, right) and
and optimize geometric shapes
(Abstract Base Classes) to exception). 4.bg (background): to handle the exception other properties like padding and
and structures.
define abstract classes. •message (optional): A Sets the Key Points expansion.example
Examples of Geometric
Steps to Create an Abstract description of the error. background color of 1.Catch Specific import tkinter as tk
Management Tools
Class: Examples the button. Exceptions: Specify the root = tk.Tk()
1.CAD Software (Computer-
1.Import the ABC and Raising Built-in 5.state: Controls the exception type to handle label1 = tk.Label(root, text="Label 1")
Aided Design):Tools: AutoCAD,
abstractmethod decorators from Exceptions button's state specific errors. label1.pack(side="top", pady=10)
SolidWorks, CATIA, Rhino,
the abc module. python (normal, disabled, or python label2 = tk.Label(root, text="Label 2")
SketchUp.Purpose: Design and
2.Inherit the class from ABC. # Raise a ValueError active). try: x = 1 / 0 except label2.pack(side="bottom", padx=10)
model 2D and 3D geometric
3.Use the @abstractmethod with a message x = -1 if Label Options: ZeroDivisionError: root.mainloop()
objects, often used in
decorator to define abstract x < 0: raise 1.text: Specifies the print("Cannot divide by 2. grid()
engineering and architecture.
methods. ValueError("x must be text displayed in the zero!") The grid() method places widgets in
2.GIS Tools:Tools: ArcGIS,
from abc import ABC, non-negative") label. 2.Catch Multiple Exceptions: a table-like structure (rows and
QGIS, GRASS GISPurpose:
abstractmethod 2.font: Sets the font Use a tuple to handle columns). You can define the
Manage and analyze spatial and
class Animal(ABC): style and size (e.g., multiple exception types. position of widgets by specifying the
geographic data, including
@abstractmethod "Arial 12 bold"). print("Invalid value or row and column, and also set
shapes, areas, and distances.
def sound(self): 3.fg (foreground): type!") column/row spans, padding, etc.
3.3D Modeling Software:Tools:
pass Sets the text color 3.Catch All Exceptions: Use label2.grid(row=1, column=1,
Blender, Maya, 3ds
@abstractmethod of the label. a bare except to catch any padx=5, pady=5)
MaxPurpose: Create and
def habitat(self): 4.bg (background): exception (not 3. place()
manipulate complex 3D
pass Sets the recommended for specific The place() method allows you to
geometries for animation,
class Dog(Animal): background color of handling). position widgets at specific
games, and simulations.
def sound(self): the label. python coordinates (x, y) within the parent
4.Finite Element Analysis (FEA)
return "Bark" 5.image: Displays try: x = 1 / 0 except: container. It gives the most control
Tools:Tools: ANSYS, Abaqus,
def habitat(self): an image instead of print("An error occurred!") over widget placement but can be
COMSOLPurpose: Analyze
return "Domestic" text in the label. 4.Access Exception Details: less flexible compared to pack() and
geometric structures under
dog = Dog() Use as to store the grid().
physical constraints like stress,
print(dog.sound()) exception object and access label2.place(x=150, y=80)
heat, or vibration.
print(dog.habitat()) details.
Data Visualization slicing dictionaries Function Arguments PYTHON difference between explain loop control
function arguments are Python is a high-level, local and global statement used in python
Data visualization in slice a dictionary in
Python refers to the Python, you can’t use
the values passed to a interpreted, and general- variable with example
function when it is called. purpose programming 1. break Statement
graphical representation traditional slicing like
They enable a function to language, its simplicity, 1. Local Variable •Purpose: Terminates
of data using libraries with lists, but you can
work with different inputs readability, and ease of use, It A local variable is a the loop immediately,
and tools to understand extract a subset of the
each time it is called. supports multiple programming variable that is declared regardless of the
trends, patterns, and dictionary by selecting
There are several types of paradigms, including within a function or block condition.
insights. Python offers specific keys or filtering
function arguments in procedural, object-oriented, and of code. It is only for i in range(1, 10):
powerful libraries for based on conditions.
Python that provide accessible within that if i == 5:
creating visualizations Below are three common functional programming.
flexibility in how a break
ranging from simple methods to achieve this: Benefits of Using Python specific function or block
function can accept and cannot be accessed print(i)
plots to complex 1. Using Dictionary 1.Easy to Learn and
inputs. outside it. Scope: The 2. continue Statement
interactive dashboards. Comprehension ReadPython’s syntax is clean
1. Positional Arguments scope of a local variable is •Purpose: Skips the
Popular Python You can create a new and easy to understand, making
Positional arguments are limited to the function or current iteration and
Libraries for Data dictionary by selecting it accessible for beginners. It is
the most common type. block in which it is moves to the next
Visualization specific key-value pairs designed to be readable.
These arguments are defineddef iteration.
1.Matplotlib:Basic using a dictionary 2.Large Standard Library and
passed to the function in example_function(): for i in range(1, 10):
plotting library for comprehension. Ecosystem
the order in which they local_var = 10 if i == 5:
creating static, 2D 2. Using dict() with Python has a vast standard
appear in the function print(local_var) continue
plots.Example: items() library that provides modules
definition. The function example_function() print(i)
import matplotlib.pyplot You can use the items()
assigns each argument to and packages for a variety of 2. Global Variable 3. pass Statement
as plt x = [1, 2, 3, 4] y = method to iterate over the
its corresponding tasks, including file handling, A global variable is a •Purpose: Acts as a
[10, 20, 25, 30] plt.plot(x, dictionary and filter key-
parameter based on the web development, data variable that is declared placeholder and does
y) plt.title("Line Plot") value pairs based on a
position. def greet(name, manipulation, and more. outside any function or nothing; used to
plt.xlabel("X-axis") condition.
age): 3.Cross-Platform Compatibility block of code. It is maintain structure
plt.ylabel("Y-axis") 3. Using pop() for Key
print(f"Hello {name}, Python is cross-platform, accessible from any part when a statement is
plt.show() Removal
you are {age} years old.") meaning that Python code can of the code, including syntactically required
2.Seaborn:Built on If you want to remove
greet("Alice", 25) run on various operating inside functions (if not but no action is
Matplotlib, provides specific keys from the
•Keyword arguments: systems, such as Windows, shadowed by a local needed.
high-level functions for dictionary, you can use
Passed with parameter macOS, and Linux, without variable). for i in range(5):
attractive and the pop() method to
names. requiring modifications. •Scope: The scope of a if i == 3:
informative statistical exclude certain keys.
•Default arguments: global variable extends to pass # Placeholder for
graphics. 4.Versatile and Used in Various
Provide fallback values. the entire program. It can future logic
3.Plotly:Interactive Domains
•*args: Accepts arbitrary be accessed from print(i)
plotting library for 2D •Web development: With
positional arguments as a anywhere in the program.
and 3D visualizations, frameworks like Django and
tuple. global_var = 20
including dashboards. Flask.
•**kwargs: Accepts def example_function():
4.4.Pandas •Data Science: With libraries
arbitrary keyword print(global_var)
Visualization:Quick and like pandas, matplotlib, and
arguments as a example_function()
easy plots directly from scikit-learn.
dictionary. print(global_var)
pandas data structures.
Write a python Write a python class to Write python GUI Write a python Define an abstract class shape Python Class to
program to create a accept a string and number program to program to swap the and its subclass (square / Find the Validity of
class circle and 'n' from user and display 'n' generate a random value of two circle). The subclass has an init Parentheses
compute the Area and repetition of strings by password with variables. function which takes an class
the circumferences of overloading *operator. upper and lower argument (length/radius) Both ParenthesesValidat
the circle. (Use case letters. a = input("Enter the classes have an area & volume
class StringRepetition: or:
parametrized first variable: ") function which can print the
def __init__(self, string): import tkinter as tk def is_valid(self, s):
constructor). b = input("Enter the area and volume of shape
self.string = string import random stack = []
second variable: ") where the area of shape by
import math def __mul__(self, n): import string matching_brackets
a, b = b, a default 0.
class Circle: return self.string * n def = {')': '(', '}': '{', ']': '['}
print("After
def __init__(self, radius): input_string = input("Enter generate_password(): from abc import ABC, for char in s:
swapping:")
self.radius = radius a string: ") length = 12 abstractmethod if char in
print("First variable:",
def area(self): n = int(input("Enter the characters = class Shape(ABC): matching_brackets.
a)
return math.pi * (self.radius ** 2) number of repetitions: ")) string.ascii_letters + @abstractmethod values():
print("Second
def circumference(self): repetition = string.digits + def area(self): stack.append(char)
variable:", b)
return 2 * math.pi * self.radius StringRepetition(input_strin string.punctuation return 0 elif char in
circle = Circle(5) g) password = Write a Python @abstractmethod matching_brackets:
print("Area of Circle:", print("Repeated String:", ''.join(random.choice(c program to check def volume(self): if stack and stack[-
circle.area()) repetition * n) haracters) for i in whether a number return 0 1] ==
print("Circumference of Circle:", range(length)) is in a given range. class Circle(Shape): matching_brackets[
circle.circumference()) Write a python program def check_range(number, def __init__(self, radius): char]:
password_label.config
to accept string and self.radius = radius
Write a python script remove the characters
(text="Generated start, end): stack.pop()
using class to reverse Password: " + if start <= number <= def area(self): else:
which have odd index return 3.14 * (self.radius ** 2)
a string word by values of given string
password) end: return False
word? root = tk.Tk() return True def volume(self): return not stack
using user defined else: return 0 validator =
root.title("Password
class StringReversal: function. return False class Square(Shape): ParenthesesValidat
Generator")
def __init__(self, string): def password_label = number = int(input("Enter def __init__(self, side): or()
self.string = string remove_odd_index_chars(i tk.Label(root, a number: ")) self.side = side expression =
def reverse_words(self): nput_string): text="Generated start = int(input("Enter def area(self): input("Enter a string
words = self.string.split() return Password: ") the starting range: ")) return self.side ** 2 of parentheses: ")
reversed_words = ' ''.join([input_string[i] for i password_label.pack() end = int(input("Enter the def volume(self): if
'.join(reversed(words)) in range(len(input_string)) generate_button = ending range: ")) return 0 validator.is_valid(ex
return reversed_words if i % 2 == 0]) tk.Button(root, if check_range(number, circle = Circle(5) pression):
input_string = input("Enter input_string = input("Enter text="Generate start, end): print("Circle Area:", circle.area()) print("Valid
a string: ") a string: ") Password", print(f"{number} is in the print("Circle Volume:", parentheses")
reversal = print("String after command=generate_p range.") circle.volume()) else:
StringReversal(input_strin removing characters at assword) else: square = Square(4) print("Invalid
g) odd indices:", generate_button.pack( print(f"{number} is not in print("Square Area:", parentheses")
print("Reversed String:", remove_odd_index_chars(i ) the range.") square.area())
reversal.reverse_words()) nput_string)) root.mainloop() print("Square Volume:",
square.volume())
Python Program to Python Script to Generate Anonymous Function
Implement the Fibonacci Terms Using a to Find Area of
Concept of Queue Generator Function Rectangle
Using List
def fibonacci(n): area_of_rectangle = lambda
queue = [] a, b = 0, 1 length, width: length * width
def enqueue(element): for _ in range(n): length = float(input("Enter the
queue.append(element) yield a length of the rectangle: "))
def dequeue(): a, b = b, a + b width = float(input("Enter the
if queue: n = int(input("Enter the width of the rectangle: "))
return queue.pop(0) number of Fibonacci print("Area of Rectangle:",
else: terms: ")) area_of_rectangle(length,
return "Queue is empty." print("Fibonacci width))
enqueue(10) sequence:") Python Program to Display
enqueue(20) for num in fibonacci(n): Current Date and Time
enqueue(30) print(num, end=" ")
print("Queue after import datetime
enqueue:", queue) Python GUI Program to current_datetime =
dequeue() Create Background datetime.datetime.now()
print("Queue after with Changing Colors print("Current Date and
dequeue:", queue) Time:",
import tkinter as tk current_datetime)
Python Program to import random
Find Factors of a def Python Program to
Given Number change_background_colo Check if a Given Key
r(): Exists in a Dictionary
def colors = ["red", "green", and Replace
find_factors(number): "blue", "yellow", "pink",
factors = [] "purple"] color = my_dict = {"name": "Alice",
for i in range(1, random.choice(colors) "age": 25}
number + 1): root.config(bg=color) key = input("Enter the key to
if number % i == 0: root.after(1000, check: ")
factors.append(i) change_background_colo if key in my_dict:
return factors r) print(f"Key exists. Replacing
number = root = tk.Tk() value of {key}.")
int(input("Enter a root.title("Background new_value = input(f"Enter
number: ")) Color Changer") new value for {key}: ")
print("Factors:", change_background_colo my_dict[key] = new_value
find_factors(number)) r() else:
root.mainloop() print("Key doesn't exist.")
print("Updated dictionary:",
my_dict)

You might also like