PYTHON PROGRAMMING
INTRODUCTION TO PYTHON
Python is a high- level programming language, which was created by
GUIDO VAN ROSSUM and released in 1991.
•It supports multiprogramming paradigms, imperative and functional
programming including object oriented.
•It is easy to learn syntax, which emphasizes code readability and
reduces the cost of program maintenance.
APPLICATIONS
Web development
System Scripting
Mathematics
Software Development
WORKING WITH PYTHON
=>To write and run (execute) a python program we need to have a python interpreter
installed on our computer.
=>The symbol >>> called python prompt that indicates the interpreter is ready
to receive instructions.
SYNTAX
The syntax of the python programming language is the set of rules that
defines how a Python program will be written and interpreted
>>> print (“HELLO WORLD”)
DATA TYPES
1.1.1 PYTHON OPERATORS
1
EXAMPLE PROGRAM:
VARIABLES AND CONSTANT VARIABLES
Python variables are simply containers for storing data values.
Variables are the identifier whose value can be change.
In Python, we can use an assignment operator to create new variables and
assign specific values to them.
CONSTANTS
Constant has same value during entire program.
In Python, we indicate a constant using ALL CAPITAL LETTERS.
PYTHON INPUTAND OUTPUT
STATEMENTS INPUT
Any information or data send to the computer from the user through the keyboard is
called input. Input
();
OUTPUT:
The information is produced by the computer to the user is
called [Link] ()
PYTHON EXECUTION
We can execute our python code using a Graphical user interface (GUI). We
can use the python in both interactive as well as script mode in IDE. Execute
python on python prompt and it will display result simultaneously
PARAMETERS AND ARGUMENTS IN PYTHON
2
ARGUMENTS PARAMETERS
We used the variables in the function to We defined the parameters when defining
send the value of the calling function to the the function.
receiving function.
We used the arguments to transfer the To get the value from the arguments, we
values from the calling function to the use the local variables in the function
receiving function in function declaration.
call statements.
These are called as Actual parameters These are called as Formal parameters
COMMENTS IN PYTHON
In python, the # character is used to start a comment. The comment
continues after the # until the end of the line.
EXAMPLE:
#comments can be used to explain the python codes# #
This is a comment - the interpreter will ignore it
x = 5 # This is another comment
def greet(name): # Function documentation
"""Prints a message with the given name."""
print("Hello, " + name + "!")
greet("L&T") # Call the function
# This line is ignored because it's a comment y
= 10 # This is a comment too
print(y) # This will print 10 #
Multi-line comment
this_is_a_comment = """
This is a multi-line comment It spans across several lines And contains some
explanation
Of what the code does
"""
# Print the value of x print(x)
# This will print 5 # Single-
line comment
3
# This line is ignored
z = 15
# Another multi-line comment another_comment
= """
This is another multi-line comment It
also spans across several lines And
contains some more explanation Of
what the code does """
# Print the value of y print(y)
# This will print 10
CONTROL FLOW, LOOPS
A program’s control flow is the order in which the program’s code execute.
The
control flow of a pythonprogram is regulated by conditional statements, loops,
and functional calls.
4
ARRAYS IN PYTHON:
•Arrays are the fundamental part of most programming languages. It is the
collection of elementsof a single data type
Create an array:
We can create an array with comma separated elements between []
We can make an integer array and store it to arr
Ex:- arr = [ 10, 20, 30, 40, 50]
Access elements an array:-
We can access an individual elements of an array using index inside []
Index is the position of an array. Index starts from 0
Ex: -
arr = [ 10, 20, 30, 40, 50]
print(arr[0])
print(arr[1])
print(arr[2])
PYTHON ARRAY METHODS:
5
LISTS, TUPLES, DICTIONARIES
List :
The list is a most versatile data type available in the python which can be
written as a list of commas separated values items between square brackets.
Important thing about a list is that items in list need not be of the same type.
EX:
list1 = [‘physics’, ‘chemistry’, 1997, 2000];
ACCESSING VALUES IN LIST :
To access values in lists, use the square brackets for slicing along with the index
or indices to obtain value available at that index.
EX:
Print “list1[0]:”, list1[0]
1.4.3 BASIC LIST OPERATIONS
6
INDEXING, SLICING, MATRICES
Because lists are sequences, indexing and slicing work the same way for
lists as they do for strings. Assuming the following input:
L= [‘spam’, ‘Spam’, ‘SPAM!’]
L [2] --- ’SPAM!’ offset start zero
L [2] -- ’Spam Negative count from right
L [1] - [‘Spam’, ‘SPAM!’] Slicing fetches section
BUILT-IN LIST FUNCTIONS & METHODS
Python includes the following list
7
TUPLES:
A tuple is a sequence of immutable python object. Tuples are sequences, just
like lists. The difference between tuples and list are, the tuples cannot be
changed unlike list and tuples use parentheses, whereas lists use square
brackets.
Creating a tuple is a simple as putting different comma-separated
values.
Optionally you can put these comma-separated values between
parentheses also.
Ex: tup1 = (‘physics’, ‘chemistry’, 1997, 2000)
The empty tuple is written as tup1 = ();
To write a tuple containing single value tup1 = (20, );
Tuple indices are start at 0.
ACCESSING TUPLE VALUES
To access values in tuple, use the square brackets for slicing along with the
index or indices to obtain values available at that index.
Ex: print “tup1[0]: “, tup1[0]
8
Tuples are also known as strings
By using the keyword del we can delete the tuple del ()
Like, the lists the tuples also has the deleting, built in functions and methods.
DICTIONARIES:
Dictionary are mutable, unordered collection with elements in the form of a KEY: VALUE
pairs that associate pair values. Dictionaries are containers that associate keys to values. In
dictionaries user need to search values based on key.
ACCESSING OF A DICTIONARY:
SYNTAX:
Dictionaryname<”key”>
Example:>>>
subjectandcode[“hindi”]
OPERATIONS AND METHODS IN DICTIONARY
9
Django FRAMEWORK :
Introduction:
Django is a web application framework written in Python programming
language. It is based on MVT (Model View Template) design pattern. The Django
is very demanding due to its rapid development feature. It takes less time to
build application after collecting client requirement.
This framework uses a famous tag line: The web framework for
perfectionists with deadlines
By using Django, we can build web applications in very less time.
Django is designed in
such a manner that it handles much of configure things automatically, so we
can focus on application development only.
Django MVT :
The MVT (Model View Template) is a software design pattern. It is a
collection of three important components Model View and Template. The Model
helps to handle database. It is a data access layer which handles the data.
The Template is a presentation layer which handles User Interface part
completely. The View is used
to execute the business logic and interact with a model to carry data and renders a
template.
Although Django follows MVC pattern but maintains it’s own conventions.
So, control is handled by the
framework itself.
There is no separate controller and complete application is based on Model
View and Template. That’s why it is called MVT application. See the following
graph that shows the MVT based control flow
10
Here, a user requests for a resource to the Django, Django works as a
controller and check to the available resource in URL.
If URL maps, a view is called that interact with model and template, it
renders a template.
Django responds back to the user and sends a template as a response
Django Model :
In Django, a model is a class which is used to contain essential fields and
methods. Each model class maps to a single table in the database.
Django Model is a subclass of [Link] and each field of the
model class represents a database field (column).
Django provides us a database-abstraction API which allows us to create,
retrieve, update and delete a record from the mapped table.
Model is defined in [Link] file. This file can contain multiple models.
Ex:
1. from [Link] import models
2. class Employee([Link]):
3. first_name = [Link](max_length=30)
4. last_name = [Link](max_length=30)
The first_name and last_name fields are specified as class attributes and
each attribute maps to a
database column.
Django Views:
A view is a place where we put our business logic of the application. The view is
a python function which is used to perform some business logic and return a
response to the user. This response can be the HTML contents of a Web page, or
a redirect, or a 404 [Link] the view function are created inside the [Link] file
of the Django app
Ex:
1. import datetime
2. # Create your views here.
3. from [Link] import HttpResponse
4. def index(request):
5. now = [Link]()
6. html = "<html><body><h3>Now time
is %s.</h3></body></html>" % now
11
7. return HttpResponse(html) # rendering the template in
HttpResponse
Let's step through the code. First, we will import DateTime library that
provides a method to get current date and time and
HttpResponse class.
Next, we define a view function index that takes HTTP request and respond back.
View calls when gets mapped with URL in [Link]. For example
1. path('index/', [Link])
Django Templates:
Django provides a convenient way to generate dynamic HTML pages by using
its template system. A template consists of static parts of the desired HTML
output as well as some special syntax describing how dynamic content will be
inserted
In HTML file, we can't write python code because the code is only
interpreted by python interpreter not the browser. We know that HTML is a static
markup language, while Python is a dynamic programming language.
Django template engine is used to separate the design from the python
code and allows us to build
dynamic web pages.
To configure the template system, we have to provide some entries in
[Link] file
1. TEMPLATES = [
2. {
3. 'BACKEND': '[Link]',
4. 'DIRS': [[Link](BASE_DIR,'templates')],
5. 'APP_DIRS': True,
6. 'OPTIONS': {
7. 'context_processors': [
8. '[Link].context_processors.debug',
9. '[Link].context_processors.request',
10. '[Link].context_processors.auth',
11. '[Link].context_processors.messages',
12. ],
13. },
14. },
15. ]
12
Here, we mentioned that our template directory name is templates. By default,
Django Templates
looks for a templates subdirectory in each of the INSTALLED_APPS.
Static files:
In a web application, apart from business logic and data handling, we
also need to handle and manage static resources like CSS, JavaScript, images
etc.
It is important to manage these resources so that it does not affect our
application performance.
Django deals with it very efficiently and provides a convenient manner to
use resources.
The django. [Link] module helps to manage them.
Include the [Link] in INSTALLED_APPS
1. INSTALLED_APPS = [
2. '[Link]',
3. '[Link]',
4. '[Link]',
5. '[Link]',
6. '[Link]',
7. '[Link]',
8. 'myapp'
9. ]
Define STATIC_URL in [Link] file as given below
1. STATIC_URL = '/static/'
Load static files in the templates by using the below expression.
1. {% load static %}
4. Store all images, JavaScript, CSS files in a static folder of the application.
First create a directory static, store the files inside it
13
Django Forms:
Forms are basically used for taking input from the user in some manner and using that
information for logical operations on databases.
Forms[Inserting and Fetching Data in sqlite database]
1. Create a django project
Django-admin startproject forms
2. cd forms
3. Create an application folder
python [Link] startapp testapp
4. Templates folder creation inside project folder md
templates
5. Register both application folder path and templates folder path
Application folder path:
[Link]
Installed_Apps[ 'testapp'
]
import os
BASE_DIR=BASE_DIR = Path( file ).resolve().[Link]
TEMPLATES = [
{
'BACKEND': '[Link]',
'DIRS': [[Link](BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'[Link].context_processors.debug',
'[Link].context_processors.request',
'[Link].context_processors.auth',
14
'[Link].context_processors.messages', ],
},
},
]
6. Create Model Class in [Link]
[Link]
from [Link] import models
class product1([Link]):
pname=[Link](max_length=50)
qty=[Link]() price=[Link]()
7. python [Link] makemigrations
python [Link] migrate
Note: Table will be created [testapp_product1]
8. We have to create [Link] file manually inside testapp folder
[Link]
from django import forms
from [Link] import product1
class productForm([Link]):
class Meta:
model=product1
fields=' all '
Testing:
from django import forms
from .models import product1
class MyForm([Link]):
class Meta:
15
model = product1
fields = ["pname", "qty"] labels = {'pname': "Name", "mobile_number":
"Mobile Number",}
[Link]
from [Link] import render from
[Link] import product1 from
[Link] import productForm def
add_product(request):
form = productForm
pform = {'form': form}
if [Link] == "POST":
form = productForm([Link]) if
form.is_valid():
[Link]()
return render(request,'[Link]') return
render(request, '[Link]',pform) def
productReport(request):
result = [Link]() products
= {'allproducts':result}
return render(request,'[Link]',products)
[Link] :should be created inside templates folder
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
16
<h3> Please fill bellow application form</h3><form method="post">
<table>
{{form.as_table}}
</table>
<button>SAVE</button>
{% csrf_token %}
</form>
<br>
<br>
<a href="product_report"><button type="button" name="button">Product
report</button></a></br><br/>
</body>
</html> [Link]
<html>
<body>
<h2 style="color:red">Record is inserted successfully</h2>
<a href="">Back</a><br/><br/>
</body>
</html>
[Link]
from testapp import views
urlpatterns = [
path('admin/', [Link]),
path('first/',views.add_product),
path('first/product_report/',[Link])
]
17
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Product Report </h1>
<br/>
<table border="1">
<tr>
<th>Product id</th>
<th>Product name</th>
<th>Quantity</th>
<th>Price</th>
</tr>
{% for s in allproducts %}
<tr>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
18
9. python [Link] runserver
Database Connectivity :
The [Link] file contains all the project settings along with database
connection details. By default, Django works with SQLite, database and
allows configuring for other databases as well.
Database connectivity requires all the connection details such as database
name, user credentials,
hostname drive name etc.
To connect with MySQL, [Link] driver is used to
establishing a connection between application and database.
Let's see an example:
we need to provide all connection details in the settings file. Modify The [Link]
of our project:
1. DATABASES = {
2. 'default': {
3. 'ENGINE': '[Link]',
4. 'NAME': 'django_mysql',
5. 'USER':'root',
6. 'PASSWORD':'root',
7. 'HOST':'[Link]',
8. 'PORT':'3306'
9. }
10. }
Django Project :
1 django-admin startproject news_portal
2 cd news_portal
19
3 python [Link] startapp testapp
4 Create a templates folder inside project folder
5 css folder : external css files are stored inside it images
folder: images are stored inside images folder
note: We need to create static folder inside project folder which contains
both css and images
Folders
[Link]
body{
background: pink;
}
img{ width:20%;height:100px
;
}
6. Add application folder path,templates folder path and static folder inside
[Link]
Adding static folder path :
import os
STATIC_DIR=[Link](BASE_DIR,'static')
STATICFILES_DIRS=[
STATIC_DIR,
]
7. [Link]
from [Link] import renderdef movies(request):
20
my_dict={'head_msg':'movies information','sub_msg1':'Jersey Movie got
National Award','sub_msg2':'Jai Bhim Movie got National
Award','sub_msg3':'Rangasthalam Movie got
National Award', 'photo':'images/[Link]'} return
render(request,'[Link]',context=my_dict) def
index(request):
return render(request,"[Link]")
8. html files
[Link]
<!DOCTYPE html>
{%load static%}
<html>
<head>
<link rel="stylesheet" href="{%static 'css/[Link]'%}">
</head>
<body>
<h1>Welcome to abc News Portal</h1>
<ul>
<li> <a href="/movies">Movies Information</a></li>
</ul>
</body>
</html>
[Link]
<!DOCTYPE html>{%load static%}
<html>
<head>
<link rel="stylesheet" href="{%static 'css/[Link]'%}">
</head>
<body>
21
<h1>{{head_msg}}</h1>
<ul>
<li><h2>{{sub_msg1}}</h2></li>
<li><h2>{{sub_msg2}}</h2></li>
<li><h2>{{sub_msg3}}</h2></li>
</ul>
<img src="{%static 'images/[Link]'%}">
</body>
</html>
9. [Link]
from [Link] import admin
from [Link] import path from
testapp import views urlpatterns = [
path('',[Link]),
path('movies/',[Link])
]
10. Start the server
python [Link] runserver
11. Make a request
[Link]
22
SQL PROGRAMMING:
SQL Data Definition and Data Types
Specifying Constraints in SQL
Basic Retrieval Queries in SQL
Set Operations in SQL
Basic SQL
Structured Query Language
Considered one of the major reasons for the commercial success
ofrelational databases
Statements for data definitions, queries, and updates
• Both DDL and DML
• Core specification plus specialized extensions
Terminology:
RELATIONAL MODEL SQL
relation table
tuple row
attribute column
Syntaxnotes:
• Some interfaces require each statement to end with a semicolon.
• SQL is not case-sensitive.
SQL data definition
Create statement
• Main SQL command for data definition
SQL schema
• Identified by a schema name
• Includes an authorization identifier (owner)
• Components are descriptors for each schema element
23
• Tables,
constraints, views, domains, and other constructs
CREATE SCHEMA statement
• CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;
3.2 CREATE table command
Specify a new relation
• Provide name
• Specify attributes and initial constraints
• Base tables (base relations)
• Relation and its tuples are physically stored and managed by
DBMS
Can optionally specify schema:
• CREATE TABLE [Link] ...
or
• CREATE TABLE EMPLOYEE ...
Include information for each column (attribute) plus constraints
• Column name
• Column type (domain)
• Key, uniqueness, and null constraints
Basic data types
Numeric data types
• Integer numbers: INT, INTEGER, SMALLINT, BIGINT
• Floating-point (real) numbers: REAL, DOUBLE, FLOAT
• Fixed-point numbers: DECIMAL(n,m), DEC(n,m), NUMERIC(n,m),
N U M (n,m)
• Character-string data types
• Fixed length: CHAR(n), CHARACTER(n)
• Varying length: VARCHAR(n), CHAR VARYING(n),
CHARACTER VARYING(n),LONG VARCHAR
▪ Large object data types
• Characters:
CLOB, CHAR LARGE OBJECT, CHARACTER
LARGE OBJECT
• Bits: BLOB, BINARY LARGE OBJECT
24
▪ Boolean data type
• Values of TRUE or FALSE or NULL
▪ DATE data type
• Ten positions
• Components are YEAR, MONTH, and DAY in the form YYYY-
MM DD
More data types
Additional data types
• TIMESTAMPdata type
• Includes the DATEand TIMEfields
• Plus a minimum of six positions for decimal fractions of
seconds
• Optional WITH TIME ZONEqualifier
• INTERVALdata type
• Specifies
a relative value that can be used to increment or
decrement an absolutevalue of a date, time, or timestamp
Columns can be declared to be NOT NULL
Columns can be declared to have a default value
• Assigned to column in any tuple for which a value is not specified
Example
CREATE TABLE EMPLOYEE (
…
NICKNAME VARCHAR(20) DEFAULT NULL,
…
Province CHAR(2) NOT NULL DEFAULT 'ON',
25
Domains in SQL
Name used in place of built-in data type
Makes it easier to change the data type used by numerous columns
Improves schema readability
Example:
CREATE DOMAIN SIN_TYPE AS CHAR(9);
Specifying key constraints
PRIMARY KEY clause
• Specifies one or more attributes that make up the primary key of a
relation
Dnumber INT NOT NULL PRIMARY KEY,
• Primary key attributes must be declared NOT NULL
UNIQUE clause
• Specifies alternate (candidate) keys
Dname VARCHAR(15) UNIQUE;
• May or may not allow null values, depending on declaration
If no key constraints, two or more tuples may be identical in all
columns.
• SQL deviates from pure relational model!
• Multiset (bag) behaviour
Referential constraints
FOREIGNKEY clause
FOREIGN KEY (Dept) REFERENCES DEPARTMENT (Dnum),
• Default operation: reject update on violation
• Attach referential triggered action clause in case referenced
tupleis deleted
• Options include SET NULL, CASCADE, and SET DEFAULT
Foreign key declaration must refer to a table already created
26
Specifying Tuple constraints
Some constraints involve several columns
CHECK clause at the end of a CREATE TABLEstatement
• Apply to each tuple individually
Example
• CHECK (Dept_create_date <= Mgr_start_date)
EX: Recall employee function :
27
Basic SQL retrieval queries
All retrievals use SELECT
statement:
SELECT <return list> FROM
<table list>
[ WHERE <condition> ] ;
where
<return list>is a list of expressions or column names whose values are to
be retrieved by the query
<table list> is a list of relation names required to process the query
<condition> is a Boolean expression that identifies the tuplesto be retrieved by the
query
Example
SELECT title,
year, genre
FROM Film
WHERE director = 'Steven Spielberg' AND year > 1990;
Omitting WHERE clause implies all tuples selected.
SEMANTICS for 1 Relation
Start with the relation named in the FROMclause
Consider each tuple one after the other, eliminating those
that donot satisfy the WHEREclause.
• Boolean condition that must be true for any retrieved tuple
• Logical comparison operators
=, <, <=, >, >=, and <>
For each remaining tuple, create a return tuple with columns
for each expression (column name) in the SELECT clause.
• Use SELECT *to select all columns.
28
Tables as sets in SQL
Duplicate tuples may appear in query results
• From duplicates in base tables
• From projecting out distinguishing columns
Keyword DISTINCTin the SELECTclause eliminates duplicates
SET OPERATIONS
Result treated as a set (no duplicates)
• UNION, EXCEPT(difference), INTERSECT
Corresponding multiset (bag) operations:
• UNIONALL, EXCEPTALL, INTERSECTALL
Arguments must be union-compatible
• Same number of columns
• Corresponding columns of same type
29
MySQL Program:
Create a django Prject and make changes in urls,views etc as shown
above
Now make changes in [Link] as shown :
[Link]
DATABASES = {
'default': {
'ENGINE': '[Link]',
'NAME': 'django_mysql',
'USER':'root',
'PASSWORD':'root',
'HOST':'[Link]',
'PORT':'3306'
}
}
pip install mysqlclient
[Link]
from [Link] import models
class product([Link]):
pname=[Link](max_length=50)
qty=[Link]()
python [Link] makemigrations
python [Link] migrate
python [Link] shell
>>> from [Link] import product
>>> p1=product(pname="computer",qty=5)
>>> [Link]()
>>> p1=product(pname="mobile",qty=2)
>>> [Link]()
>>> for x in res:
... print("The product id is ",[Link])... print("The product name",[Link])
... print("The qty is ",[Link]
30
31