The document provides an overview of object-oriented programming concepts in Python including defining classes, inheritance, methods, and data structures. Some key points:
- Classes define user-created data types that bundle together data (attributes) and functions (methods) that work with that data. Objects are instances of classes.
- Methods are defined within classes and must have "self" as the first argument to access attributes. The __init__ method serves as a constructor.
- Inheritance allows subclasses to extend existing classes, redefining or calling parent methods.
- Python supports lists, tuples, dictionaries, sets and other data structures that can be used to store and organize data. Lists are mutable while tuples are immutable.
The document discusses object-oriented programming in Python. It defines key OOP concepts like classes, objects, and methods. It provides examples of defining classes and methods in Python. It also covers inheritance, polymorphism, and data abstraction in OOP. Database programming in Python is also discussed, including connecting to databases and performing CRUD operations using the Python DB API.
This document discusses using Python to interact with SQLite databases. It provides examples of how to connect to an SQLite database, create tables, insert/update/delete records, and query the database. Key points covered include using the sqlite3 module to connect to a database, getting a cursor object to execute SQL statements, and various cursor methods like execute(), executemany(), fetchone(), fetchall(), commit(), and close(). Example code is given for common SQLite operations like creating a table, inserting records, updating records, deleting records, and selecting records.
This document discusses Python database programming. It introduces databases and how they store data in tables connected through columns. It discusses SQL for creating, accessing, and manipulating database data. It then discusses how Python supports various databases and database operations. It covers the Python DB-API for providing a standard interface for database programming. It provides examples of connecting to a database, executing queries, and retrieving and inserting data.
The document discusses developing a Python scraping API that extracts data from various sources like databases, spreadsheets, PDFs, and text files. It outlines the key steps as:
1. Connecting to databases and extracting data using Python libraries like PyMySQL and Pandas.
2. Extracting data from spreadsheets using openpyxl and extracting text, links, images from PDFs using libraries like PyPDF2, PdfPlumber, and PyMuPDF.
3. Processing and storing the extracted data in a MySQL database with tables created using SQL commands.
The Python DB-API standard supports connecting to and interacting with many database servers like MySQL, PostgreSQL, and Oracle. To access a database, a Python module like MySQLdb must be installed. Code examples demonstrate how to connect to a MySQL database, create tables, insert/update/delete records, and handle errors according to the DB-API. Transactions ensure data integrity using atomicity, consistency, isolation, and durability properties.
This document discusses accessing and working with SQLite databases in Python. It covers the basics of connecting to a SQLite database, creating tables, inserting and updating data, and fetching data. The key steps are importing SQLite3, connecting to a database, using the connection to create a cursor to execute SQL statements like CREATE TABLE, INSERT, UPDATE, and SELECT. It also briefly mentions libraries for connecting to other SQL databases like PostgreSQL, MySQL, and Microsoft SQL Server. The goal is to teach the reader how to perform common CRUD operations with SQLite in Python.
PythonDatabaseAPI -Presentation for Databasedharawagh9999
Python DB API allows Python applications to interact with relational databases in a uniform way. It supports various databases including SQLite, MySQL, PostgreSQL, Oracle, and SQL Server. The document discusses connecting Python to MySQL, executing SQL queries, and fetching data. It provides code to connect to a MySQL database, create a table, insert sample data, run queries, and display results.
The document provides information on how to connect Python to MySQL and perform various operations like creating databases and tables, inserting, updating, deleting and fetching data. It explains how to install the required Python MySQL connector library and connect to a MySQL server from Python. It then demonstrates commands to create databases and tables, insert, update and delete data, and fetch data using where, order by and limit clauses. It also shows how to drop tables and databases and alter table structures.
Connecting Python to MySQL allows storing and retrieving data from a MySQL database. The mysql.connector module provides a bridge between Python and MySQL. To connect, import mysql.connector, create a connection object specifying login details, then use cursor objects to execute queries and extract result sets. Queries can be parameterized by embedding placeholders in SQL strings. Data is inserted or updated using execute() and changes committed with commit().
The document describes an internship training in Python conducted over 6 weeks. It provides an introduction to Python, describing it as a general purpose programming language that can be used for various applications. It then discusses key Python features and concepts like variables, loops, data structures, modules like NumPy, Tkinter, Turtle and how to connect Python to MySQL databases. Code examples are provided to demonstrate basic usage of these features and modules.
The document summarizes the internship training that Shivam Denge completed from July 5th to August 16th 2022 at iBase Technology. The 6-week online training covered topics like Python programming language features, variables, loops, data structures, Numpy, Tkinter, Turtle and MySQL database modules. Key aspects of Python like being an interpreted, object-oriented and cross-platform language were also highlighted.
This document provides an introduction and overview of the Python programming language. It discusses who uses Python and why, gives an overview of Python's features including dynamic typing, modules, exceptions, generators and list comprehensions. It also covers Python paradigms like structural, object-oriented, functional and imperative programming. The document describes Python data types and sequences, provides examples of classes and decorators, and discusses additional Python concepts like special keywords, ranges, generators and resources for learning more.
This document discusses connecting Python to databases. It outlines 4 steps: 1) importing database modules, 2) establishing a connection, 3) creating a cursor object, and 4) executing SQL queries. It provides code examples for connecting to MySQL and PostgreSQL databases, creating a cursor, and fetching data using methods like fetchall(), fetchmany(), and fetchone(). The document is an introduction to connecting Python applications to various database servers.
This document discusses using Python to connect to and interact with a PostgreSQL database. It covers:
- Popular Python database drivers for PostgreSQL, including Psycopg which is the most full-featured.
- The basics of connecting to a database, executing queries, and fetching results using the DB-API standard. This includes passing parameters, handling different data types, and error handling.
- Additional Psycopg features like server-side cursors, transaction handling, and custom connection factories to access columns by name rather than number.
In summary, it provides an overview of using Python with PostgreSQL for both basic and advanced database operations from the Python side.
Certified Professional Diploma in Data Science.pdfromanpaul8888
Become data scientist by enrolling for data science course in best institute in Thane, Andheri, Nerul, Navi Mumbai, Dadar & Kalyan. Offline practical data science training is available at affordable fees with certification and placement.
The document discusses various CRUD (create, read, update, delete) operations in SQLite using Python. It covers creating a database and table, inserting, retrieving, updating, and deleting data from the table. Code examples and explanations are provided for each operation. Key methods for SQLite in Python like connect(), execute(), commit(), close() are also explained.
Interface Python with MySQL connectivity.pptxBEENAHASSINA1
The document discusses connecting a Python application to a MySQL database. It provides steps to install the mysql.connector package to bridge the connection between Python and MySQL. It explains how to open a connection, create a cursor, execute queries to retrieve and manipulate data, and extract results. Methods shown include using cursors to fetch data row by row, parameterized queries using placeholders, and performing INSERT, UPDATE and DELETE operations with commit.
"Hymenoptera: A Diverse and Fascinating Order".pptxArshad Shaikh
Hymenoptera is a diverse order of insects that includes bees, wasps, ants, and sawflies. Characterized by their narrow waists and often social behavior, Hymenoptera play crucial roles in ecosystems as pollinators, predators, and decomposers, with many species exhibiting complex social structures and communication systems.
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...wygalkelceqg
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical Management 2nd Ed Klotz
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical Management 2nd Ed Klotz
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical Management 2nd Ed Klotz
More Related Content
Similar to 9 Python programming notes for ktu physics and computer application semester 4 (20)
PythonDatabaseAPI -Presentation for Databasedharawagh9999
Python DB API allows Python applications to interact with relational databases in a uniform way. It supports various databases including SQLite, MySQL, PostgreSQL, Oracle, and SQL Server. The document discusses connecting Python to MySQL, executing SQL queries, and fetching data. It provides code to connect to a MySQL database, create a table, insert sample data, run queries, and display results.
The document provides information on how to connect Python to MySQL and perform various operations like creating databases and tables, inserting, updating, deleting and fetching data. It explains how to install the required Python MySQL connector library and connect to a MySQL server from Python. It then demonstrates commands to create databases and tables, insert, update and delete data, and fetch data using where, order by and limit clauses. It also shows how to drop tables and databases and alter table structures.
Connecting Python to MySQL allows storing and retrieving data from a MySQL database. The mysql.connector module provides a bridge between Python and MySQL. To connect, import mysql.connector, create a connection object specifying login details, then use cursor objects to execute queries and extract result sets. Queries can be parameterized by embedding placeholders in SQL strings. Data is inserted or updated using execute() and changes committed with commit().
The document describes an internship training in Python conducted over 6 weeks. It provides an introduction to Python, describing it as a general purpose programming language that can be used for various applications. It then discusses key Python features and concepts like variables, loops, data structures, modules like NumPy, Tkinter, Turtle and how to connect Python to MySQL databases. Code examples are provided to demonstrate basic usage of these features and modules.
The document summarizes the internship training that Shivam Denge completed from July 5th to August 16th 2022 at iBase Technology. The 6-week online training covered topics like Python programming language features, variables, loops, data structures, Numpy, Tkinter, Turtle and MySQL database modules. Key aspects of Python like being an interpreted, object-oriented and cross-platform language were also highlighted.
This document provides an introduction and overview of the Python programming language. It discusses who uses Python and why, gives an overview of Python's features including dynamic typing, modules, exceptions, generators and list comprehensions. It also covers Python paradigms like structural, object-oriented, functional and imperative programming. The document describes Python data types and sequences, provides examples of classes and decorators, and discusses additional Python concepts like special keywords, ranges, generators and resources for learning more.
This document discusses connecting Python to databases. It outlines 4 steps: 1) importing database modules, 2) establishing a connection, 3) creating a cursor object, and 4) executing SQL queries. It provides code examples for connecting to MySQL and PostgreSQL databases, creating a cursor, and fetching data using methods like fetchall(), fetchmany(), and fetchone(). The document is an introduction to connecting Python applications to various database servers.
This document discusses using Python to connect to and interact with a PostgreSQL database. It covers:
- Popular Python database drivers for PostgreSQL, including Psycopg which is the most full-featured.
- The basics of connecting to a database, executing queries, and fetching results using the DB-API standard. This includes passing parameters, handling different data types, and error handling.
- Additional Psycopg features like server-side cursors, transaction handling, and custom connection factories to access columns by name rather than number.
In summary, it provides an overview of using Python with PostgreSQL for both basic and advanced database operations from the Python side.
Certified Professional Diploma in Data Science.pdfromanpaul8888
Become data scientist by enrolling for data science course in best institute in Thane, Andheri, Nerul, Navi Mumbai, Dadar & Kalyan. Offline practical data science training is available at affordable fees with certification and placement.
The document discusses various CRUD (create, read, update, delete) operations in SQLite using Python. It covers creating a database and table, inserting, retrieving, updating, and deleting data from the table. Code examples and explanations are provided for each operation. Key methods for SQLite in Python like connect(), execute(), commit(), close() are also explained.
Interface Python with MySQL connectivity.pptxBEENAHASSINA1
The document discusses connecting a Python application to a MySQL database. It provides steps to install the mysql.connector package to bridge the connection between Python and MySQL. It explains how to open a connection, create a cursor, execute queries to retrieve and manipulate data, and extract results. Methods shown include using cursors to fetch data row by row, parameterized queries using placeholders, and performing INSERT, UPDATE and DELETE operations with commit.
"Hymenoptera: A Diverse and Fascinating Order".pptxArshad Shaikh
Hymenoptera is a diverse order of insects that includes bees, wasps, ants, and sawflies. Characterized by their narrow waists and often social behavior, Hymenoptera play crucial roles in ecosystems as pollinators, predators, and decomposers, with many species exhibiting complex social structures and communication systems.
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...wygalkelceqg
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical Management 2nd Ed Klotz
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical Management 2nd Ed Klotz
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical Management 2nd Ed Klotz
Introduction to Online CME for Nurse Practitioners.pdfCME4Life
Online CME for nurse practitioners provides a flexible, cost-effective way to stay current with evidence-based practices and earn required credits without interrupting clinical duties. Accredited platforms offer a wide range of self-paced courses—complete with interactive case studies, downloadable resources, and immediate digital certificates—that fit around demanding schedules. By choosing trusted providers, practitioners gain in-depth knowledge on emerging treatments, refine diagnostic and patient-management skills, and build professional credibility. Know more at https://cme4life.com/the-benefits-of-online-cme-for-nurse-practitioners/
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdfTechSoup
In this webinar we will dive into the essentials of generative AI, address key AI concerns, and demonstrate how nonprofits can benefit from using Microsoft’s AI assistant, Copilot, to achieve their goals.
This event series to help nonprofits obtain Copilot skills is made possible by generous support from Microsoft.
POS Reporting in Odoo 18 - Odoo 18 SlidesCeline George
To view all the available reports in Point of Sale, navigate to Point of Sale > Reporting. In this section, you will find detailed reports such as the Orders Report, Sales Details Report, and Session Report, as shown below.
This study describe how to write the Research Paper and its related issues. It also presents the major sections of Research Paper and various tools & techniques used for Polishing Research Paper
before final submission.
Finding a Right Journal and Publication Ethics are explain in brief.
Pragya Champion's Chalice is the annual Intra Pragya General Quiz hosted by the club's outgoing President and Vice President. The prelims and finals are both given in the singular set.
How to Manage Orders in Odoo 18 Lunch - Odoo SlidesCeline George
The Lunch module in Odoo 18 helps users place their food orders, making meal management seamless and efficient. It allows employees to browse available options, place orders, and track their meals effortlessly.
Order: Odonata Isoptera and Thysanoptera.pptxArshad Shaikh
*Odonata*: Odonata is an order of insects that includes dragonflies and damselflies. Characterized by their large, compound eyes and agile flight, they are predators that feed on other insects, playing a crucial role in maintaining ecological balance.
*Isoptera*: Isoptera is an order of social insects commonly known as termites. These eusocial creatures live in colonies with complex social hierarchies and are known for their ability to decompose wood and other cellulose-based materials, playing a significant role in ecosystem nutrient cycling.
*Thysanoptera*: Thysanoptera, or thrips, are tiny insects with fringed wings. Many species are pests that feed on plant sap, transmitting plant viruses and causing damage to crops and ornamental plants. Despite their small size, they have significant impacts on agriculture and horticulture.
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...RVSPSOA
Principles of statics. Forces and their effects. Types of force systems. Resultant of concurrent and
parallel forces. Lami’s theorem. Principle of moments. Varignon’s theorem. Principle of equilibrium.
Types of supports and reactions-Bending moment and Shear forces-Determination of reactions for
simply supported beams. Relation between bending moment and shear force.
Properties of section – Centre of gravity, Moment of Inertia, Section modulus, Radius of gyration
for various structural shapes. Theorem of perpendicular axis. Theorem of parallel axis.
Elastic properties of solids. Concept of stress and strain. Deformation of axially loaded simple bars.
Types of stresses. Concept of axial and volumetric stresses and strains. Elastic constants. Elastic
Modulus. Shear Modulus. Bulk Modulus. Poisson’s ratio. Relation between elastic constants.
Principal stresses and strain. Numerical and Graphical method. Mohr’s diagram.
R.K. Bansal, ‘A Text book on Engineering Mechanics’, Lakshmi Publications, Delhi,2008.
R.K. Bansal, ‘A textbook on Strength of Materials’, Lakshmi Publications, Delhi 2010.
Paul W. McMullin, 'Jonathan S. Price, ‘Introduction to Structures’, Routledge, 2016.
P.C. Punmia, ‘Strength of Materials and Theory of Structures; Vol. I’, Lakshmi
Publications, Delhi 2018.
2. S. Ramamrutham, ‘Strength of Materials’, Dhanpatrai and Sons, Delhi, 2014.
3. W.A. Nash, ‘Strength of Materials’, Schaums Series, McGraw Hill Book Company,1989.
4. R.K. Rajput, ‘Strength of Materials’, S.K. Kataria and Sons, New Delhi , 2017.
Students will research and orally present a Colombian company using a visual tool, in order to develop their communication skills and intercultural understanding through the exploration of identity, innovation, and local culture, in connection with the IB global themes.
How to Use Owl Slots in Odoo 17 - Odoo SlidesCeline George
In this slide, we will explore Owl Slots, a powerful feature of the Odoo 17 web framework that allows us to create reusable and customizable user interfaces. We will learn how to define slots in parent components, use them in child components, and leverage their capabilities to build dynamic and flexible UIs.
Odoo 18 Point of Sale PWA - Odoo SlidesCeline George
Progressive Web Apps (PWA) are web applications that deliver an app-like experience using modern web technologies, offering features like offline functionality, installability, and responsiveness across devices.
Here is the current update:
CURRENT CASE COUNT: 897
- Texas: 742 (+14) (55% of cases are in Gaines County). Includes additional numbers from El Paso.
- New Mexico: 79 (+1) (83% of cases are from Lea County)
- Oklahoma: 17
- Kansas: 59 (+3) (38.89% of the cases are from Gray County)
HOSPITALIZATIONS: 103
- Texas: 94 – This accounts for 13% of all cases in Texas.
- New Mexico: 7 – This accounts for 9.47% of all cases in New Mexico.
- Kansas: 3 – This accounts for 5.08% of all cases in Kansas.
DEATHS: 3
- Texas: 2 – This is 0.28% of all cases in Texas.
- New Mexico: 1 – This is 1.35% of all cases in New Mexico.
US NATIONAL CASE COUNT: 1,132 (confirmed and suspected)
INTERNATIONAL SPREAD
Mexico: 1,856(+103), 4 fatalities
- Chihuahua, Mexico: 1,740 (+83) cases, 3 fatalities, 4 currently hospitalized.
Canada: 2,791 (+273)
- Ontario, Canada: 1,938 (+143) cases. 158 (+29) hospitalizations
- Alberta, Canada: 679 (+119) cases. 4 currently hospitalized
Coleoptera, commonly known as beetles, is the largest order of insects, comprising approximately 400,000 described species. Beetles can be found in almost every habitat on Earth, exhibiting a wide range of morphological, behavioral, and ecological diversity. They have a hardened exoskeleton, with the forewings modified into elytra that protect the hind wings. Beetles play important roles in ecosystems as decomposers, pollinators, and food sources for other animals, while some species are considered pests in agriculture and forestry.
Types of Actions in Odoo 18 - Odoo SlidesCeline George
In Odoo, actions define the system's response to user interactions, like logging in or clicking buttons. They can be stored in the database or returned as dictionaries in methods. Odoo offers various action types for different purposes.
Order Lepidoptera: Butterflies and Moths.pptxArshad Shaikh
Lepidoptera is an order of insects comprising butterflies and moths. Characterized by scaly wings and a distinct life cycle, Lepidoptera undergo metamorphosis from egg to larva (caterpillar) to pupa (chrysalis or cocoon) and finally to adult. With over 180,000 described species, they exhibit incredible diversity in form, behavior, and habitat, playing vital roles in ecosystems as pollinators, herbivores, and prey. Their striking colors, patterns, and adaptations make them a fascinating group for study and appreciation.
2. Python allows us to connect to various databases through
database interfaces. Python’s database interface is DB-API.
You can choose the right database for your application.
Python Database API supports a wide range of database
servers such as −
GadFly
mSQL
MySQL
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
You must download a separate DB API module for each
database you need to access. For example, if you need to
access an Oracle database as well as a MySQL database,
you must download both the Oracle and the MySQL
database modules.
3. Create a database called SAMPLE in MySQL.
The user id and password used to access SAMPLE database
is “user” and “pass” respectively.
Create a table STUDENT in SAMPLE.
The table STUDENT has fields ROLLNO, NAME, AGE,
COURSE, GRADE.
The following code shows how to connect MySQL database
with Python.
import pymysql
# Open database connection
db = pymysql.connect("localhost","user",“pass",“SAMPLE" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print "Database version : “,data
# disconnect from server
db.close()
4. Once a database connection is established, we are ready
to create tables or records into the database tables
using execute method of the created cursor.
import pymysql
# Open database connection
db=MySQLdb.connect("localhost","testuser","test123","TESTDB"
)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE
( FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# disconnect from server
db.close()I
5. It is required when you want to create your records into a
database table.
import MySQLdb
# Open database connection
db=MySQLdb.connect("localhost","testuser","test123","TESTDB"
)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE,
SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit() except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
6. UPDATE Operation on any database means to update one
or more records, which are already available in the
database.
import MySQLdb
# Open database connection
db=MySQLdb.connect("localhost","testuser","test123","TESTDB"
)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to UPDATE required records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'"
% ('M')
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit() except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
7. DELETE operation is required when you want to delete
some records from your database.
import MySQLdb
# Open database connection
db=MySQLdb.connect("localhost","testuser","test123","TESTDB"
)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit() except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
8. Transactions ensure the data consistency of the database. We
have to make sure that more than one applications must not
modify the records while performing the database operations.
The transactions have the following properties.
Atomicity
Either the transaction completes, or nothing happens. If a
transaction contains 4 queries then all these queries must be
executed, or none of them must be executed.
Consistency
The database must be consistent before the transaction starts
and the database must also be consistent after the transaction is
completed.
Isolation
Intermediate results of a transaction are not visible outside the
current transaction.
Durability
Once a transaction was committed, the effects are persistent,
even after a system failure.
9. Commit is the operation, which gives a green
signal to database to finalize the changes,
and after this operation, no change can be
reverted back.
db.commit()
10. If you are not satisfied with one or more of
the changes and you want to revert back
those changes completely, then
use rollback() method.
db.rollback()
11. To disconnect Database connection, use
close() method.
db.close()
12. There are many sources of errors. A few examples are a syntax
error in an executed SQL statement, a connection failure, or
calling the fetch method for an already canceled or finished
statement handle.
The DB API defines a number of errors that must exist in each
database module. The following table lists these exceptions.
Warning
Used for non-fatal issues. Must subclass StandardError.
Error
Base class for errors. Must subclass StandardError.
InterfaceError
Used for errors in the database module, not the database itself. Must
subclass Error.
DatabaseError
Used for errors in the database. Must subclass Error.
DataError
Subclass of DatabaseError that refers to errors in the data.
13. There are many types of objects which can be used
with a for loop. We can use a for loop for iterating
through a list, string, dictionary or a file. These are
called iterable objects.
The Python iterators object is initialized using
the iter() method. It uses the next() method for
iteration.
__iter__(): The iter() method is called for the
initialization of an iterator. This returns an iterator
object
__next__(): The next method returns the next value
for the iterable. When we use a for loop to traverse
any iterable object, internally it uses the iter()
method to get an iterator object, which further uses
the next() method to iterate over. This method raises
a StopIteration to signal the end of the iteration.
14. Iterators can be materialized as lists or tuples by
using the list() or tuple() constructor functions.
The following program shows how a list can be
converted to an iterator and then to materialize
to a tuple.
list=[1,2,3]
iterator=iter(list)
t=tuple(iterator)
print(t)
Output
(1,2,3)
15. Often, when dealing with iterators, we also need
to keep a count of iterations. Python eases the
programmers’ task by providing a built-in
function enumerate() for this task. The
enumerate () method adds a counter to an
iterable and returns it in the form of an
enumerating object. This enumerated object can
then be used directly for loops or converted into
a list of tuples using the list() function.
Syntax: enumerate(iterable, start=0)
Parameters:
Iterable: any object that supports iteration
Start: the index value from which the counter is
to be started, by default it is 0
16. Generators are a special class of functions that simplify the task
of writing iterators. Regular functions compute a value and
return it, but generators return an iterator that returns a stream
of values. A generator is a special routine that can be used to
control the iteration behaviour of a loop. A generator is similar to
a function returning an array.
A generator has parameters, it can be called and it generates a
sequence of numbers. Function returns a whole array, a
generator yields one value at a time. Generators require less
memory
Generators in Python
are defined with the def keyword
use the yield keyword
may use several yield keywords
returns an iterator
When a function is called, a private namespace is allocated for
the local variables and when a function reaches a return
statement, the local variables are destroyed and the value is
returned to the caller.
But in generators local variables aren’t thrown away on exiting a
function
17. Decorators are used to add functionality to
an existing code.
This is also called metaprogramming as a
part of the program tries to modify another
part of the program at compile time
There are two types of decorators in Python
Function decorators
Class decorators
A decorator in Python is any callable Python
object that is used to modify a function or a
class.
18. The Common Gateway Interface(CGI) is a standard way for
a web server to pass a web user’s request to an application
program and to receive data back to forward to the user.
The Common Gateway Interface, or CGI, is a set of
standards that define how information is exchanged
between the web server and a custom script.
To understand the concept of CGI, let us see what happens
when we click a hyper link to browse a particular web
page or URL.
Your browser contacts the HTTP web server and demands
for the URL, i.e., filename.
Web Server parses the URL and looks for the filename. If it
finds that file then sends it back to the browser, otherwise
sends an error message indicating that you requested a
wrong file.
Web browser takes response from web server and displays
either the received file or error message.
19. All HTTP headers will be in the following
form:
HTTP Field Name: Field Content
Example
Content-type: text/html
20. Environment variables are a series of hidden
values that the web server sends to every CGI
program we run. Our program can parse them
and use the data they send. Environment
variables are stored in a hash named %ENV:.
Some of the environment variables are
DOCUMENT_ROOT : The root directory of our
server.
HTTP_COOKIE : The visitor’s cookie, if one is set.
HTTP_HOST : The hostname of the page being
attempted.
REMOTE_ADDR : The IP address of the visitor
21. A form is an area that can contain form elements.
Form elements allow the user to enter information in
a form
Get method
The GET method is the default method to pass
information from browser to web server and it produces
a long string that appears in your browser's
Location:box. Never use GET method if you have
password or other sensitive information to pass to the
server.
Post method
A generally more reliable method of passing information
to a CGI program is the POST method. This packages the
information in exactly the same way as GET methods,
but instead of sending it as a text string after a ? in the
URL it sends it as a separate message.
22. Radio Buttons are used when only one option is
required to be selected.
Here is example HTML code for a form with two
radio buttons −
<form action = "/cgi-bin/radiobutton.py" method
= "post" target = "_blank">
<input type = "radio" name = "subject" value =
"maths" /> Maths
<input type = "radio" name = "subject" value =
"physics" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
23. Drop Down Box is used when we have many
options available but only one or two will be
selected.
Here is example HTML code for a form with one
drop down box −
<form action = "/cgi-bin/dropdown.py" method =
"post" target = "_blank">
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select> <input type = "submit" value =
"Submit"/>
</form>
24. Checkboxes are used when more than one option
is required to be selected.
Here is example HTML code for a form with two
checkboxes −
<form action = "/cgi-bin/checkbox.cgi" method =
"POST" target = "_blank">
<input type = "checkbox" name = "maths" value =
"on" /> Maths
<input type = "checkbox" name = "physics" value
= "on" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
25. TEXTAREA element is used when multiline
text has to be passed to the CGI Program.
Here is example HTML code for a form with a
TEXTAREA box −
<form action = "/cgi-bin/textarea.py"
method = "post" target = "_blank">
<textarea name = "textcontent" cols = "40"
rows = "4"> Type your text here...
</textarea>
<input type = "submit" value = "Submit" />
</form>
26. An HTTP cookie is a small piece of data sent from a website and
stored on the user’s computer by the user’s web browser while
the user is browsing. Cookies are designed to be a reliable
mechanism for web sites to remember information or to record
the user’s browsing activity.
Cookies are a plain text data record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the
cookie will expire when the visitor quits the browser.
Domain − The domain name of your site.
Path − The path to the directory or web page that sets the
cookie. This may be blank if you want to retrieve the cookie from
any directory or page.
Secure − If this field contains the word "secure", then the cookie
may only be retrieved with a secure server. If this field is blank,
no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key
and value pairs.
27. To upload a file, the HTML form must have
the enctype attribute set to multipart/form-
data.
The input tag with the file type creates a
"Browse" button.