[go: up one dir, main page]

0% found this document useful (0 votes)
6 views75 pages

Python Slides

Uploaded by

vishnudevvd937
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views75 pages

Python Slides

Uploaded by

vishnudevvd937
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

PYTHON

PYTHON AND ITS FRAMEWORK


Basic Introduction

Python is widely used high-level programing language for general-


purpose programming like Java,C,C++ etc.
FEATURES OF PYTHON
1. General purpose programming language
2. High level language
3. Interpreted
4. Interactive
5. Portable(windows,Linux,MAC OS)
6. Multiple Programming paradigms(funtional and object oriented)
7. Easy to Learn
8. Dynamic Typed Language
9. Databases(MY SQL,SQLITE,POSTGRES)
Environment Setup
Go to python website www.python.org and download python 3.9.0
installer then follow the instruction to install it
Modes of Programming
• Interactive Mode Programming
• Script mode Programming
• Using IDLE
IDENTIFIERS
Identifier is the name given to entities like class, functions,variables
etc.It is a combination of a-z or A-Z or 0-9 or _
Rules for writing identifiers
• An identifier cannot start with a digit.
• Keywords cannot be used as identifiers.
• Identifiers cannot use symbols like !,@,#,$,% etc.
• Identifiers can be any length
• python is a case sensitive language so always name identifiers that make
sense
Python Keywords
Keywords are the reserved words in python.They are used to define
the syntax and structure of the python language.
eg: True,False,and,continue,return etc.
Lines and Indentation
Blocks of code are denoted by line indentation.For example:
if(True):
print(“True”)
else:
print(“False”)
Multi-Line Statements
Statements in python typically end with a new line.The line
continuation character(\) to denote that the line should continue.
The statements contained within the [],{},() brackets
do not need to use the line continuation character.
Quotation in Python
Python Accepts single('),double(“) and triple(''' or ”””) quotes to
denote string.
Comments in python
Python supports two types of comments
1. Single lined comment- comment must be start with #
2. Multi-lined comment-comment can be given inside triple quotes '''''
Multiple statements on single line
The semicolon (;) allows multiple statements on a single line
Variables
Variables are the reserved memory location to store values.Based on
the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory.
Single Assignment Multiple Assignment

• c=100 #integer • a=b=c=1 # a=1,b=1,c=1


• d=100.00 #floating • a,b,c=1,2,'python'
• e='python' #string
Numbers
Datatypes Python supports three different
The data stored in memory numerical types:
can be of many types: • int (signed integers)
1. NUMBERS • float (floating point real values)
2. STRING
• complex (complex numbers)
3. LIST
4. TUPLE
String
5. DICTIONARY Strings are identified as a contigous
6. SET set of characters represented in the
quotation marks
• [ ]-index
• [:]-slice operator
• '+'- concatenation operator
• '*'-repetition operator
List
A list contains different type of datatypes seperated by commas and
enclosed within the square brackets([ ]).
list=['python',80,9.5]
The values stored in a list can be accessed using the
slice,concatenation,repetition operator
Tuple
A tuple is another sequence data type that is similar to the list. A
tuple consists of a number of values separated by commas. Unlike
lists, however, tuples are enclosed within parenthesis and
cannot be updated.
tuple=('python',80,9.5)
Dictionary
Dictionary consist of key-value pairs and are enclosed by curly
braces({ }).Values can be assigned and acessed using square
brackets([ ]).They are simply unordered.
dict={'name':'abc','id':23,'sal':20000}
Set
A set is an unordered collection of items.Every element is
unique(no duplicates) and created by placing all the items
inside curly braces({ }) seprated by commas or by using the
built in function set().
set{1,2,3,(4,5)}
List built-in methods Dictionaries built-in methods
append(),clear(),copy(),count(), clear(),copy(),get(),items()
extend(),index(),insert(),pop() keys() ,pop()
remove(),reverse(),sort() update(),values()

Tuples built-in methods Set built-in methods


count(),index() add(),clear(),copy(),discard(),pop(),
remove(),update()
OPERATORS
• Arithemetic operator
+ Adition,-substraction,*multiplication,/division,
%modulus,**exponent,//floor division
• Comparison (Relational) Operators
== double equal, != not equal,> greater than,<less than,>=greater than or
equal,
<= less than or equal
• Assignment operator
=, +=, -=, *=, /=, %=, **=, //=
• Logical operator
AND,OR,NOT
• Membership operator
in,not in
• Identity operator
is, is not
• Bitwise operator
& Binary AND,| Binary OR,^ Binary XOR,~ Binary Ones Complement,
<< Binary Left Shift,>> Binary Right Shift
DECISION MAKING STATEMENTS
statements Explanation Syntax
An if statement consists of a if expression:
if statements boolean expression followed by statement(s)
one or more statements.
An if statement can be followed if expression:
if.....else by an optional else statement, statement(s)
statements which executes when the boolean else:
expression is FALSE. statement(s)
if expression1:
statement(s)
You can use one if or else
if...elif...else elif expression2:
if statement inside
statements statement(s)
another if or else if statement(s).
else:
statement(s)
if expression1:
statement(s)
if expression2:
You can use one if or else statement(s)
if statement inside else:
Nested if statements another if or else if statement(s)
statement(s). elif expression3:
statement(s)
else:
statement(s)
LOOPING STATEMENTS
A loop statement allows us to execute a statement or group of
statements multiple times while a given condition is true. It tests
the condition before executing the loop body.

statements Explanation Syntax

Repeats a statement or group of


statements while a given
while expression:
while loop condition is TRUE. It tests the condition
statement(s)
before executing the
loop body
Executes a sequence of
statements multiple times and for iterating_var in sequence:
for loop
abbreviates the code that statements(s)
manages the loop variable
we can use one or more loop for iterating_var in sequence:
inside any another while, or for iterating_var in sequence:
nested loop
for loop. statements(s)
statements(s)
Infinite loop
A loop becomes infinite loop if a condition never becomes
FALSE.This results in a loop that never ends. Such a loop is called
an infinite loop.
range() function
The built-in function range() is the right function to iterate over a
sequence of numbers. It generates an iterator of arithmetic
progressions.
• range(start,stop,step size).
Loop Control Statements
Loop control statements change execution from its normal
sequence.
break:-Terminates the loop statement and transfers execution to the
statement immediately following the loop.
continue:-The continue statement rejects all the remaining
statements in the current iteration of the loop and moves the control
back to the top of the loop.
pass:-The pass statement in Python is used when a statement is
required syntactically but you do not want any command or code to
execute.
FUNCTIONS
A function is a block of organized, reusable code that is used to
perform a single, related action.It help break our program into
smaller and modular chunks and furthermore it avoids repetition and
makes code reusable.
There are three types of functions in Python:
• Built-in functions:-such as help() to ask for help, min() to get the
minimum value, print()to print an object to the terminal.
• User-Defined Functions:-which are functions that users create
to help them out.
• Anonymous functions:-which are also called lambda functions
because they are not declared with the standard def keyword.
Here are simple rules to define a function in Python:-
• Function blocks begin with the keyword def followed by the
function name and parentheses [ ( ) ].
• Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these
parentheses.
• The first statement of a function can be an optional statement -
the documentation string of the function or docstring.
• The code block within every function starts with a colon (:) and is
indented.
• The statement return [expression] exits a function, optionally
passing back an expression to the caller. A return statement with
no arguments is the same as return None.
Function Argument and Parameter
1) The First type of data is the data passed in the function call. This
data is called arguments
2) The second type of data is the data received in the function
definition. This data is called parameters
How Function works in Python

Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
how to call a function in
python
def funtionname(parameters):
...........
...........
funtionname(arguments)
Global and Local variables
Variables that are defined inside a function body have a local scope,
and those defined outside have a global scope .
The Anonymous Functions
These functions are called anonymous because they are not
declared in the standard manner by using the def keyword. You can
use the lambda keyword to create small anonymous functions.
lambda [arg1 [,arg2,.....argn]]:expression
Python Module
Modular programming refers to the process of breaking a large,
unwieldy programming task into separate, smaller, more
manageable subtasks or modules. A module is simply a Python file,
where classes, functions and variables are defined.
Reusability and Categorization are the major advantages of modules.
Importing a Module:
In this we can import
Using import statement: import <file_name >
only one file
import <file_name1,
Importing Multiple Modules file_name2,... file_name(n) > In this we can import
multiple files
from <module_name> import
only import particular
from.. import statement <attribute1,attribute2,attribute3
attribute from a module
,...attributen>

To import whole module from <module_name> import * import the whole module

Python built in modules


There are many built in modules in Python. Some of them are as
follows:
math, random , threading , collections , os , mailbox , string , time ,
tkinter etc.
Packages
A package is basically a directory with Python files and a file with the
name __init__.py. This means that every directory inside of the
Python path, which contains a file named __init__.py, will be
treated as a package by Python.
Steps to create and import Package:
1) Create a directory
2) Place different modules inside the directory.
3) Create a file __init__.py which specifies attributes in each module.
4) Import the package and use the attributes using package.
File Operations
There are different modes you can open a file with, specified by the
mode parameter. These include:
• 'r' - reading mode. The default. It allows you only to read the file,
not to modify it. When using this mode the file must exist.
• 'w' - writing mode. It will create a new file if it does not exist,
otherwise will erase the file and allow you to write to it.
• 'a' - append mode. It will write data to the end of the file. It does
not erase the file, and the file must exist for this mode.
• 'x'- it creates a new file with the unique name. It causes an error a
file exists with the same name.
eg:-
with open(filename, 'r') as f:
f.read() #read file
with open(filename, 'w') as f:
f.write(filedata) # write data to file
with open(filename, 'a') as f:
f.write('\\n' + newdata) # append data to file
Exception Handling

Exception handling is the


process of responding to
exceptions when a
computer program runs
and attempts to gracefully
handle these situations so
that a program does not
crash
eg:-
ZeroDivisionError,Indentation
Error,IOError,NameError
Classes
Python is purely an object-oriented language.Major priciples of
OOPs are Object,Class,Method,Inheritance etc.
Object:-
The object is an entity that has state and behaviour.It maybe any
real-world object like table,pen,notebook,chair etc.
Class:-
The class can be defined as collection of objects. A class can be
created by using the keyword class, followed by the class name
class Classname
#statement-suite
Method:-
The method is a function that is associated with an object.
Instance:-
A class needs to be instatiated if we want to use the class attributed
in another class or method, The syntax to create instance of the
class.
<object-name>=<class name>(<arguments>)
Constructor:-
constructer is a special method that executes when we create an
object of a class.It is defined using __init__() keyword
Destructor:-
Destructors are called when an object gets destroyed. It's the polar
opposite of the constructor.Destructor is defined using __del__()
keyword.
Inheritance
Inheritance is an important aspect of the object-oriented paradigm.
The child acquires the properties and can access all the data
members and functions defined in the parent class
class derived-class(base class):
<class-suite>
Multi-level Inheritance Multiple inheritance
class class1: class Base1:
<class-suite> <class-suite>
class class2(class1): class Base2:
<class suite> <class-suite>
class class3(class2): class BaseN:
<class suite> <class-suite>
class Derived(Base1, Base2, ......
BaseN):
<class-suite>
Method overriding
Overriding means sub class have the same method with same
name and exactly the same number and type of parameters and
same return type as a super class.
Method overloading
Overloading means Methods of the same class shares the same
name but each method must have different number of parameters or
parameters having different types and order.
Database
SQLite3
It can be used to create a database, define tables, insert and change rows, run
queries and manage an SQLite database file. It also serves as an example for
writing applications that use the SQLite library
Creating a table
import sqlite3
conn = sqlite3.connect('aaa.db')
print "Opened database successfully";
conn.execute('''''CREATE TABLE Employees (ID INT PRIMARY KEY NOT NULL, NAME
TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50),
SALARY REAL);''')
print "Table created successfully";
conn.close()
Inserting data
import sqlite3
conn = sqlite3.connect('aaa.db')
print "Opened database successfully";
conn.execute("INSERT INTO Employees (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, 'abc', 27, 'mno', 23000.00 )");
conn.execute("INSERT INTO Employees (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (2, 'def', 22, 'pqr', 25000.00 )");
conn.execute("INSERT INTO Employees (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (3, 'ghi', 29, 'stu', 34000.00 )");
conn.execute("INSERT INTO Employees (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (4, 'jkl', 22, 'vwxyz ', 55000.00 )");
conn.commit()
print "Records inserted successfully";
conn.close()
view the inserted data
import sqlite3
conn = sqlite3.connect('aaa.db')
data = conn.execute("select * from Employees");
for row in data:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
conn.close();
PostgreSQL
• Download PostgreSQL and install it
• pgAdmin4(pgAdmin is the leading Open Source management tool for
Postgres)
• install psycopg2(Psycopg is the most popular PostgreSQL database adapter
for the Python programming language)
– pip install psycopg2 ##(in cmd)
creating a table
import psycopg2
connection = psycopg2.connect(user="postgres",password="*****",
host="127.0.0.1",port="5432",
database="postgres")
cursor = connection.cursor()
create_table_query = '''CREATE TABLE students
(ID INT PRIMARY KEY NOT NULL,
MODEL TEXT NOT NULL,
PRICE REAL); '''
cursor.execute(create_table_query)
connection.commit()
print("Table created successfully in PostgreSQL ")
inserting data
cur.execute("INSERT INTO students(ID,Model, price) VALUES(
52,'abc',7896)")
GUI programming
Tkinter:-
Python provides the standard library Tkinter for creating the
graphical user interface for desktop based applications.An empty
Tkinter top-level window can be created by using the following
steps.
– import the Tkinter module.
– Create the main application window.
– Add the widgets like labels, buttons, frames, etc. to the window.
– Call the main event loop so that the actions can take place on the user's
computer screen.
There are various widgets like button, canvas, checkbutton, entry,
Example
from tkinter import *
root=Tk()
root.geometry('300x300')
root.title('First Tkinter
Window')
root.mainloop()
Django
Django is a high-level Python Web framework that encourages rapid
development and clean, pragmatic design.
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.
Installation:-
• requiring Python to be installed on your machine
• Before installing django make sure pip is installed in local system.
– Installing with get-pip.py instructions.
• open command prompt and execute the following coomand
DJANGO MVC - MVT Pattern
The Model-View-Template (MVT) is slightly different from MVC. In
fact the main difference between the two patterns is that Django
itself takes care of the Controller part , leaving us with the template.
The template is a HTML file mixed with Django Template Language.
Creating a project
• First open a command prompt/terminal and navigate to where you
want to store your Django apps
• Execute the following command for creating project
– django-admin startproject mypro #(“project name”)
– cd mypro
• Execute the following command for creating application in that
project
– python manage.py startapp myapp #(“application name”)
• To check execute following command
– python manage .py runserver
• copy the url to browser
app:-
is a Web application that does something. An app usually is
composed of a set of models (database tables), views, templates,
tests.
project:-
is a collection of configurations and apps. One project can be
composed of multiple apps, or a single app.
It’s important to note that you can’t run a Django app without
a project
The mypro project sub-folder is the entry point for the website:
• __init__.py is an empty file that instructs Python to treat this
directory as a Python package.
• settings.py contains all the website settings. This is where
we register any applications we create, the location of our static
files, database configuration details, etc.
• urls.py defines the site url-to-view mappings. While this
could contain all the url mapping code, it is more common to
delegate some of the mapping to particular applications.
• wsgi.py is used to help your Django application communicate
with the web server. This file is a simple gateway interface used
for deployment.
• The manage.py script is used to create applications, work with
databases, and start the development web server.
The myapp project sub-folder is
admin.py:-Django-admin configuration files
apps.py:-apps specific configuration file
models.py:-Defines entities in web application. The models are
translated automatically by Django into database tables.
tests.py:-Unit test for the app
views.py:-Request/response cycle of our web application. Each
view of our Application is defined inside view file
let’s configure our project to use it.
step1:-open the settings.py and try to find the INSTALLED_APPS
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles','myapp'
]
step2:-Open the views.py file inside the myapp app, and add the
following code:
views.py
from django.http import HttpResponse
def home(request):
return HttpResponse('Hello, World!')
step3:-open project urls.py file inside mypro and add the following
code
– this would allows to look for any url that has the pattern
127.0.0.1:8000/myapp
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
path('', include('myapp.urls')),
path('admin/', admin.site.urls),
]
step4:-open application urls.py file inside myapp and add the
following code
from django.urls import path
from.import views
urlpatterns=[
path('',views.home,name='home'),
]
step5:-To run the project go to the terminal and execute the
following code
python manage.py runserver
Templates
Django needs a convenient way to generate HTML dynamically. The
most common approach relies on templates. In HTML, we can't really
write Python code, because browsers don't understand it. They know only
HTML. We know that HTML is rather static, while Python is much more
dynamic.
Variables:-Variables associated with a context can be accessed by
{{}} (double curly braces).
⦁ My name is {{name}}.(in html)
Tags:-Tags provide arbitrary logic in the rendering process.Tags are
surrounded by {% %} braces
⦁ {% csrf_token %} ,{% if user.is_authenticated %} ,{% endif %}
• To get started with templates we first need to create templates
directory inside our container folder.
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'template')],
'APP_DIRS': True,
• Create a index.html file inside templates folder
index.html views.py
<!DOCTYPE html> def index(request):
<html lang="en"> render(request,’index.html’)
<head> urls.py(application urls)
<meta charset="UTF-8"> urlpatterns=[
<title>Index</title> path('',views.home,name='home'),
</head> ]
<body> *******************************************
<h2>Welcome to Django!!!</h2> To link views and template, Django
</body> relies on the render function and
</html> the Django Template language.
Passing values to the html file from views.py file
• Inside Views.py file
def index(request):
d={“insert_me”:”I am in Django”}
return render (request,’index.html,context=d)
• Inside index.html add template tags to get the value.
{{insert_me}}
• When the page corresponding to the index view loads, then This will
displays the value I am in Django.
Static Files
In django the additional files such as images, JavaScript, or CSS
refer to as “static files”.
• create a new folder “static” in the root of the main project same
level as the “templates” directory.
• Specify STATICFILES_DIRS In Django Project settings.py File
STATIC_DIR=os.path.join(BASE_DIR,”static”)
STATICFILES_DIRS = [ STATIC_DIR,]
• Create a css ,image and js sub folder in the static folder and save
accodingly
• Adding html files to the template
• Use {% load staticfiles %} at first to load django static tag.
• Use django static tag to reference the static files.
<script src="{% static 'js/click.js' %}"></script>

<link rel=”stylesheet” href=”{% static 'css/style.css' %}”>


<img src="{% static 'image/click.js' %}"></script>
Model
A model is a class that represents table or collection in our DB, and
where every attribute of the class is a field of the table or collection.
We will be using a SQLite database to store our data. This is the
default Django database .
from django.db import models
class person(models.Model):
name = models.CharField(max_length = 50)
age = models.IntegerField()
• Every model inherits from django.db.models.Model.Our class has
2 attributes (1 CharField and 1 IntegerField), those will be the
table fields.
Registering models
Django comes with a built-in admin interface. When you
ran startproject , Django created and configured the default admin
site for you.
• open admin.py in the application.It currently looks like this
from django.contrib import admin
# Register your models here.
• Register the models by copying the following text into the bottom
of the file.
from app1.models import person
admin.site.register(person)
• Then we have to make Django know that we have some changes
in our model.Go to our console window and type :
python manage.py makemigrations.
• To apply migration, we need to run migrate command as follows
python manage.py migrate
Creating a superuser
In order to log into the admin site, we need a user account with staff
status enabled.Call the following command,to create the superuser
You will be prompted to enter a username, email address,and strong
password.
python manage.py createsuperuser
Enter your desired username and press enter.
Username: user1
You will then be prompted for your email address:
Email address: a@example.com
The final step is to enter your password. You will be asked to enter your
password twice, the second time as a confirmation of the first.
Password: **********
Password (again): *********
Superuser created successfully.so we can test the login:
python manage.py runserver
(e.g. http://127.0.0.1:8000/admin)
Click on the Add link to the right of persons to create a new person.
Enter values for the name and age fields. When you're done you
can press SAVE, Save and add another, or Save and continue
editing to save the record.
In order to display the persons, we need to create a view to list all
the persons or filter the persons by selected category.
Edit views.py file of our application and make sure it has this code
write the following code and make link to the views file by urls.py
Views.py <body> #per.html
from django.shortcuts import render {% if users %}
from django.http import HttpResponse <ol> {% for e in users %}
from app1.models import person <li>Person Info</li>
def per(request): <ul>
user_list = person.objects.all() <li>Name: {{e.name}}</li>
return <li>Age: {{e.age}}</li>
render(request,'per.html',{"users":user </ul> {% endfor %}
_list})
</ol>
{% endif %}
</body>
FORMS
Form data is stored in an application's forms.py file, inside the
application directory. To create a Form, we import the forms library,
derive from the Form class, and declare the form's fields.
Django provides a helper class Meta which allows us to create a
Form class from a Django model.
from django import forms
from app1.models import person
class PersonForm(forms.ModelForm):
class Meta:
model =person
fields = "__all__"
views.py method to process model form persons.html
def persons(request): <body>
if request.method == 'POST': <form method="POST">
form = PersonForm(request.POST) {% csrf_token %}
if form.is_valid(): {{form.as_p}}
form.save() <input type="submit" value="Submit form">
return render(index(request)) </form>
else: </body>
HttpResponse("inavalid data") The {% csrf_token %} statement is a Django
return tag. it is a special tag reserved for cases
render(request,'persons.html',{'form':form}) when a web form is submitted via POST and
processed by Django
File uploading
• Create a new folder “media” in the root of the main project same
level as the “templates” directory.
• Specify MEDIA_DIRS In Django Project settings.py File
– STATIC_URL = '/static/'
– MEDIA_ROOT=os.path.join(BASE_DIR,'media')
– MEDIA_URL='/media/'
• In models.py
from django.db import models
class preson(models.Model):
name = models.CharField(max_length = 50)
data=models.FileField
• In project urls.py,
if settings.DEBUG:
urlpatterns +=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
• In veiws.py
form = PersonForm(request.POST,request.FILES)
• In Templates,
– <form action="abcd" method="POST" enctype="multipart/form-data">
– {% for a in user %}
{{a.name}}
<img src="{{a.data.url}}"><br>
{% endfor %}
Setting up Session
Sessions framework can be used to provide persistent behaviour for
anonymous users in the website. Sessions are the mechanism used
by Django for you store and retrieve data on a per-site-visitor basis.
• In views.py,
def login(request):
m = Member.objects.get(username=request.POST['username']) #'member'table name
if m.password == request.POST['password']:
request.session['member_id'] = m.id
return HttpResponse("You're logged in.")
else:
return HttpResponse("Your username and password didn't match.")
• How to logout session
• def logout(request):
try:
del request.session['member_id']
except KeyError:
pass
return HttpResponse("You're logged out.")

You might also like