Juice pilaadooooo chu chu ka
Juice pilaadooooo chu chu ka
!!!UNIT 1ST!!!
Lists in Python
Lists are one of the most versatile and frequently used data structures in Python. They are ordered
collections of elements enclosed in square brackets ([]) and can store elements of various data types,
including numbers, strings, and even other lists.
Key Characteristics:
a. Elements in a list are arranged in a specific sequence, allowing you to access them by their
index (starting from 0).
b. You can modify individual elements or the entire list after it's created.
c. Lists can contain elements of different data types.
d. The size of a list can change as needed during runtime.
A. Creating Lists: You can create a list by enclosing elements within square brackets, separated
by commas.
my_list = [1, 2, 3, "hello", True]
B. Accessing Elements: Use the index of an element to access it:
first_element = my_list [0] # Output: 1
last_element = my_list [-1] # Output: True
C. Slicing Lists: Extract a portion of a list using slicing:
sublist = my_list[1:4] # Output: [2, 3, "hello"]
D. Modifying Lists: Change elements or add/remove elements:
my_list [2] = 5
my_list.append(7)
my_list.insert(3, "world")
my_list.remove("hello")
del my_list[1]
List Methods:
Python provides numerous methods for working with lists:
Syntax:
Example:
Dictionary Comprehension:
Dictionary comprehension is a syntactically compact way to construct dictionaries. It creates a new
dictionary by applying an expression to generate both the keys and the values from items in an
iterable, optionally filtering elements using a condition.
Syntax:
Key_expression: The operation that determines the key for each element.
Value_expression: The operation that determines the value for each element.
Item: The element being processed in the iterable.
Iterable: A sequence or collection (like a list or range).
Condition (optional): A filtering condition that can be applied to the elements.
Example:
List comprehension
List comprehension in Python is a concise way to create lists by using a for-loop in a single line. It
allows you to apply an expression to each item in an iterable, and you can also include an optional
condition (filter).
Syntax:
squares = []
squares. append(x**2)
print(even_odd) # Output: ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd',
'even']
for i in range(5):
print(i)
Output:
b. Example 2: range() with a Start and Stop Value.You can specify both a start and stop value.
# Iterate over numbers from 2 to 6 (exclusive of 6)
print(i)
Output:
list1 = [1, 2, 3]
print(num, letter)
Output:
1a
2b
3c
b. Example 2: Iterating Over Three Lists Using zip()
# Using zip() to combine three lists
list1 = [1, 2, 3]
Output:
1 a True
2 b False
3 c True
Creating a Module:
a. Create a new Python file with a .py extension (e.g., mymodule.py).
b. Define functions, classes, and variables within the file.
Importing a Module:
1. Use the import statement to import the entire module:
import mymodule
Creating a Package:
a. Create a directory with the desired package name (e.g., mypackage).
b. Inside the directory, create an empty file named __init__.py. This file indicates that the
directory is a Python package.
c. Place modules within the package directory.
Importing a Package:
1. Use the import statement to import the entire package:
import mypackage
2. Access elements within the package using dot notation:
mypackage.mymodule.my_function()
def main():
Lambda Function
A Lambda Function in Python is an anonymous, single-line function defined using the lambda
keyword. It's often used for small, throwaway functions that are not meant to be reused elsewhere.
Lambda functions are commonly used with functions like map(), filter(), and sorted(), where a small
function is needed temporarily.
print(add_ten(5)) # Output: 15
Passing functions as arguments to functions.
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma
my_function("Emil")
my_function("Tobias")
my_function("Linus")
return x * x
numbers = [1, 2, 3, 4]
Filter:
The filter() function in Python is used to filter elements from an iterable based on a condition defined
by a function. It returns an iterator that contains only the elements for which the
function returns True.
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
a. _iter_(): The iter() method is called for the initialization of an iterator. This returns an iterator
object
b. _next_(): The next method returns the next value for the iterable.
Generators in Python
Generators are a type of iterable, like lists or tuples, that allow you to produce items one at a time
and only when requested. They are memory-efficient and are particularly useful when working with
large datasets or streams of data. A generator function is defined like a normal function, but instead
of return, it uses the yield keyword to return data one piece at a time.
Object-oriented Programming
In Python object-oriented Programming (OOPs) is a programming paradigm that uses objects and
classes in programming. It aims to implement real-world entities like inheritance, polymorphisms,
encapsulation, etc. in the programming. The main concept of object-oriented Programming (OOPs)
or oops concepts in Python is to bind the data and the functions that work together as a single unit
so that no other part of the code can access this data.
Classes
A class is like a blueprint for creating objects. It defines the attributes (data) and methods (functions)
that objects of that class will have.
Object
An object is a fundamental concept in object-oriented programming (OOP). It represents a real-
world entity with specific characteristics and behaviors.
Inheritance
Inheritance is the capability of one class to derive or inherit the properties from another class. The
class that derives properties is called the derived class or child class and the class from which the
properties are being derived is called the base class or parent class.
Attributes
Attributes in Python are the variables that belong to an object or class. They are used to store
information about the object or the class. Attributes can be classified into two main types: instance
attributes and class attributes.
1. Instance Attributes: These attributes are specific to an instance (object) of a class. They are
defined within the constructor method (_init_) or dynamically added to an instance.
2. Class Attributes: These attributes are shared across all instances of a class. They are defined
directly within the class and not in the _init_ method.
Overloading in Python
Overloading in Python refers to the ability to define multiple behaviors for a function or operator,
depending on the types or number of arguments passed.
1. Function Overloading: Python does not support traditional function overloading because a
function name can only be associated with one definition.
2. Operator Overloading: In Python, operators like +, -, *, etc., can be overloaded by
redefining their behavior using special methods (also called magic methods).
3. Method Overloading: in Classes Python does not directly support method overloading, but
you can achieve it using multiple dispatch or conditional logic.
Overriding in Python
Overriding in Python occurs when a child (subclass) redefines or changes the behavior of a method
inherited from its parent (superclass). This is a key feature of polymorphism in object-oriented
programming, enabling subclasses to provide their own specific implementation for methods.
When a method in a subclass has the same name, parameters, and return type as a method in the
parent class, the subclass's method overrides the parent's implementation. The subclass method is
called when invoked on an instance of the subclass.
Data Hiding in Python
Data hiding is a crucial concept in object-oriented programming (OOP) that involves protecting the
internal state of an object from unauthorized access and modification. This helps maintain data
integrity, security, and prevents accidental changes.
To make private attributes in Python, we add two underscores (__) before their name. This tells
other parts of the program to not directly access these attributes. While it's not completely hidden,
it's a strong signal to other programmers to avoid direct access. Example:
class MyClass:
Abstract classes
• An Abstract class is a class which contains one or more abstract methods.
• An abstract method the method is the one which is just define it but not implemented.
Methods in python.
try:
except ExceptionType:
Try block
The try block in Python is used to wrap code that may raise exceptions (errors) during execution. The
code inside the try block is executed, and if an exception occurs, the program jumps to the
corresponding except block to handle the error.
try:
except ExceptionType:
Finally, clause
The finally clause is part of the try-except-finally block and is used to define code that should always
execute, regardless of whether an exception occurred or not in the try block. This is useful for
cleaning up resources, closing files, or releasing network connections, ensuring that certain actions
always take place even if an error happens.
Syntax of try-except-finally:
try:
except ExceptionType:
finally:
To create a custom exception, you simply define a new class that inherits from the built-in
Exception class:
class MyCustomException(Exception):
pass
!!!!UNIT2nd!!!!!
Multi-threading in Python
Multithreading in Python is a way to run multiple threads (smaller units of a process) concurrently
within a single process. This can help you take advantage of multi-core systems and improve the
performance of certain types of programs, especially those involving I/O-bound tasks.
A. Thread-Based Multitasking
Threads are the smallest unit of a CPU's execution. They run within a process and share the
same memory space, which makes communication between threads easier. Python provides the
threading module to handle thread-based multitasking.
B. Process-Based Multitasking
Processes are independent units of execution, each with its own memory space. The
multiprocessing module in Python allows creating and managing processes. Unlike threads,
processes are not affected by the GIL (Global Interpreter Lock), making process-based
multitasking better for CPU-bound tasks (like computations or data processing).
Network programming
Python plays an essential role in network programming. The standard library of Python has full
support for network protocols, encoding, and decoding of data and other networking concepts, and
it is simpler to write network programs in Python than that of C++.
There are two levels of network service access in Python. These are:
A. Low-Level Access: Programmers can use Python's libraries to access the basic socket
features of the operating system. This allows them to implement both connection-less and
connection-oriented protocols.
B. High-Level Access: Application-level network protocols can be accessed using high-level
access provided by Python libraries. These protocols are HTTP, FTP, etc.
Client/Server programming
Client/Server programming refers to the communication model where one machine, the server,
provides resources or services, and another machine, the client, accesses those resources or
services. This architecture is fundamental to modern networking and can be found in applications
like web servers, email servers, and database management systems.
Basic Concepts:
a. Client: The client is typically a machine or application that requests services from the server.
b. Server: A server is a machine or software that waits for incoming client requests and provides
resources or services.
c. Network: The network is the communication pathway that allows clients and servers to
interact.
d. Sockets: A socket is a software endpoint that facilitates communication
between two machines.
Introduction to HTML
HTML (Hypertext Markup Language) is the standard language used to create and structure content
on the web. It provides the basic structure for web pages, such as text, images, links, and other
media. HTML consists of elements, which are the building blocks of web content. These elements
are represented by tags, which help the browser understand how to display the content.
1. Install Required Libraries: If you don't have requests and beautifulsoup4 installed, you
can install them using pip:
2. Make a GET Request to a Remote HTML Server: The requests library allows you to
send HTTP requests. Here is an example of how to fetch HTML data from a remote server:
3. Make a POST Request: If you need to send data (e.g., form data) to the server, you can use
the POST method:
4. Handling Cookies and Sessions: If you need to maintain session information, such as
login cookies, use the requests.Session() object:
5. Handling JSON Data (If the Server Responds with JSON): If the server returns JSON
data, you can use the.json() method to parse it.
Running HTML-based queries
Running HTML-based queries in Python typically involves using libraries designed for web scraping or
working with HTML content. Here are a few approaches depending on your needs:
1. Parsing and Querying Static HTML: If you already have an HTML document or a URL, you
can use libraries like BeautifulSoup from the bs4 module.
2. Fetching and Querying Web Content: If the content is online, use requests to fetch it,
then parse with BeautifulSoup.
3. Running Queries with XPath (lxml): XPath is a powerful query language for selecting
elements from an XML/HTML document.
Example: facebook.ico.py
a. import requests
b. url=https://www.facebook.com/favicon.ico
c. r=requests.get(url)
d. open(facebook.ico'wb').write(r.content)
CGI programming
Common Gateway Interface (CGI) is a standard protocol that allows web servers to execute external
programs, typically scripts, to dynamically generate web page content.
1. Setup Environment: Ensure you have Python installed. Have a web server installed,
such as Apache or use the built-in server in Python for testing.
2. Write a CGI Script: Create a Python script that will be executed by the web server.
Here's a basic example:
print ("Content-Type: text/html\n")
print("<html><head><title>CGI Script Output</title></head>")
print("<body>")
print("<h1>Hello, CGI!</h1>")
print("</body></html>")
3. Save the Script: Save your script with a .cgi or .py extension and make sure it is
executable. For example, name it hello.cgi.
4. Configure the Server: Place your CGI script in the appropriate directory for CGI scripts
on your web server. Ensure the script has execution permissions:
5. Run the Script
Access your CGI script through the web browser. For example:
http://yourdomain.com/cgi-bin/hello.cgi
Django: A Powerful Python Web Framework
Django is a high-level Python web framework that simplifies the process of building complex web
applications. It's designed to promote rapid development and clean, pragmatic design. With its
robust features and extensive community support, Django has become a popular choice for
developers worldwide.
At its core, NumPy revolves around the concept of multidimensional arrays. These arrays are
essentially grids of numbers, where each element has a specific index. The number of dimensions in
an array is known as its rank, and the size of each dimension is its shape. For instance, a 2D array (a
matrix) has two dimensions: rows and columns.
Pandas
Pandas is a powerful and popular data manipulation and analysis library in Python. It provides data
structures and functions that make it easy to work with structured data, such as tabular data. The
two primary data structures in pandas are:
1. Series: A one-dimensional array-like object, similar to a list or an array, but with labeled
indices.
Syntax: pd.Series(data, index=index)
2. Data-Frame: A two-dimensional table-like data structure with labeled rows and columns,
similar to a spreadsheet or SQL table.
Syntax: pd.DataFrame(data, index=index, columns=columns)
Matplotlib
Matplotlib is a popular Python library used for creating static, interactive, and animated
visualizations in Python. It is highly customizable and works well with other libraries and tools in the
Python ecosystem. Below are some key features and concepts related to Matplotlib:
Key Features
• Wide Range of Plots: Line plots, Scatter plots, Bar plots, Histograms, Pie charts, 3D plots.
• Customization: Fine control over line styles, colors, markers, and more. Custom axes, labels,
and legends.
1. Pyplot Interface (matplotlib.pyplot): High-level interface for creating quick and simple
visualizations.
2. Object-Oriented Interface: Provides finer control and customization by working with Figure
and Axes objects.
Seaborn
Seaborn is a Python data visualization library built on top of Matplotlib. It provides a high-level 1
interface for creating visually appealing and informative statistical graphics. Seaborn 2 is particularly
useful for exploring and understanding complex datasets.
Key Features of Seaborn:
1. High-level Interface: Seaborn's API is designed to be intuitive and easy to use, allowing you to
create sophisticated visualizations with minimal code.
2. Statistical Graphics: Seaborn offers a wide range of statistical plot types, including scatter
plots, histograms, box plots, and heatmaps, to help you visualize relationships and trends in
your data.
Tkinter module
Python offers multiple options for developing GUI out of all the GUI methods tkinter is the most
commonly used method. python tkinter is the fastest and easiest way to create GUI applications. t
tkinter is the standard UGI library for python some of the key modules in tkinter are
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title("Advanced GUI")
root.geometry("400x300")
# Label
label = tk.Label(root, text="Enter your name:", font=("Arial",
14), fg="blue")
label.pack(pady=10)
# Entry Field
entry = tk.Entry(root, font=("Arial", 14), width=30)
entry.pack(pady=10)
# Button
button = tk.Button(root, text="Greet",
command=on_button_click, font=("Arial", 14), bg="green",
fg="white")
button.pack(pady=20)
# Main Frame
main_frame = tk.Frame(root, bg="lightgrey")
main_frame.pack(fill="both", expand=True, padx=10, pady=10)
# Nested Frame 1
frame1 = tk.Frame(main_frame, bg="lightblue", bd=2, relief="sunken")
frame1.pack(fill="both", expand=True, padx=5, pady=5)
# Nested Frame 2
frame2 = tk.Frame(main_frame, bg="lightgreen", bd=2,
relief="sunken")
frame2.pack(fill="both", expand=True, padx=5, pady=5)