0% found this document useful (0 votes)
22 views76 pages

Lab Manual On Scripting Languages - CST 2nd - 2023-24

Uploaded by

ranajitbarik2005
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)
22 views76 pages

Lab Manual On Scripting Languages - CST 2nd - 2023-24

Uploaded by

ranajitbarik2005
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/ 76

K G Engineering Institute

Department of Computer Science & Technology


Bishnupur Bankura
West Bengal - 722122

SCRIPTING LANGUAGES (PYTHON)


(CST213)
LAB MANUAL

Topic Covered:
PROGRAM: DIPLOMA
1. Introduction, Variables SEMSTER : 3rd
and Data Types
YEAR : 2nd
2. Control Structures

3. Functions,
Modules and
Packages

4. File I/O, Text


Processing,
Regular
Expressions

5. Frameworks

Prepared by:
Mr. Raj Kumar Datta (Lecturer)
Department of Computer Science & Technology
K G Engineering Institute,
Bishnupur, Bankura, West Bengal - 722122

Department of Computer Science & Technology

[Assignment on Scripting Languages (Python) Laboratory Page 1


K. G. Engineering Institute
Department of Computer Science & Technology
Laboratory Assignment on Scripting Languages
(Python) (Code: CST213)
Year 2nd - Semester 3rd – Part II
Session – 2023-24
INDEX PAGE
Week Sl. No. List of Program / Assignment Page Actual Signature
No No Date
a. Write down the steps for Installing Python
interpreter. 21-08-
1 1 b. Write down the instructions of setting up 23
the path and running a script in Interactive
and Script mode in python.
a. Write a script to purposefully raise
Indentation Error and correct it.
b. Explain and Demonstrate print(), Input(),
2 format(), int() method with examples of each.
c. Define type casting and explain Implicit and
Explicit type casting with example.
d. Write a code to demonstrate comment
statement in Python. 25-08-
2 a. Create a file named as “add.py” that takes 2 23
3 numbers as command line argument and print
the sum.
a. What do you mean slicing? Write down the
Syntax of Slicing.
b. Write a program to demonstrate the
characters of a string in reverse order using
4 slicing.
c. Write down a script using slicing to check
whether a given string is palindrome or not.

a. Write a script on given 2 strings, S1 and S2;


create a new string by appending S2 in the 28-08-
middle of S1. 23
b. Write a code implementing different string
methods:
3 5 i. split() ii. join() iii. replace()
iv. capitalize() v. count() vi. index()
vii. strip() viii. upper() ix. lower()
x. partition()

[Assignment on Scripting Languages (Python) Laboratory Page 2


Week List of Program / Assignment Page No Actual Signature
Sl. No.
No Date
a. State the purpose of using the Datetime
module.
b. What are the different classes available in
the Datetime module? Explain each of them.
c. Write a code implementing the following
Datetime module with syntax and example: 01-09-
4 6 i. datetime.now() 23
ii. datetime.today()
iii. datetime.datetime()
d. Demonstrate other examples of Datetime
module implementing date and time object.
e. State the purpose of using timedelta object
with python code.

a. Write a script to create, append, and remove 04-09-


lists in python.
23
b. Write a script to demonstrate different
5 7 methods in List.
c. Demonstrate the following programs :
i) List slicing
ii) List Comprehensions
a. Write a script to demonstrate the different
08-09-
ways of creating tuple objects in python.
23
b. Write a script to demonstrate swapping

6 8. values within a tuple assignment.


c. Find the maximum number of a tuple
contained integer numbers.

a. a. Write a script to show the different ways of


creating dictionary objects in python.
b. Write a script that combines more than one list
into a dictionary.
11-09-
c. Write a script to count the numbers of characters
23
in the string and store them in a dictionary data
structure.
7 9
d. Demonstrate the following methods which
operates on dictionary in Python with suitable
examples: i) dict() ii) len() iii) clear()
iv) update() v) pop( ) vi) popitem()
vii) keys() viii) values() x) items() x)
copy()

[Assignment on Scripting Languages (Python) Laboratory Page 3


Week List of Program / Assignment Page No Actual Signature
Sl. No.
No Date
a. Write a program to print a number is positive / 15-09-23
negative using if-else.
b. Write a program to find the largest number
8 10
among three numbers.
c. Write a Program to read a number and display
corresponding day using if_elif_else?
a. Write a program to demonstrate different data
types available in python.
b. Write a script demonstrating different types of
loops are available in Python.
c. Write a program in python, to print even
numbers in range 0 to (last number not less than
10). Using while construct.
9 11 22-09-23
d. Write a program in Python that prints the square
of the numbers in the list, using for loop
construct.
e. Write a script to find Sum and average of first n
numbers (where n = {1…..α}).
f. Write a script to check whether a given string is
palindrome or not.

a. Write a script to check if a number is prime


number or not.

b. Write a script to find all primes within a given


10 12 range. 29-09-23

c. Write a script to find the square root of a


number.
a. Write a script to create a menu with the
following options 1. To Perform Addition
2. To Perform Subtraction 3. To Perform
Multiplication 4. To Perform Division
Accepts Users Input And Performs The Operation
accordingly. Use Functions With Arguments.
11 13 b. Write a python program to find factorial of a 03-10-23
number using Recursion.
c. Write a script to find First n Fibonacci numbers
using a function.
d. Write a Python function that takes two lists and
returns True if they are equal otherwise false
using function.

[Assignment on Scripting Languages (Python) Laboratory Page 4


Week List of Program / Assignment Page No Actual Signature
Sl. No.
No Date

a. Write a python program to define a module and


import a specific function in that module to another
program.
b. Write a Python program to convert temperatures
to and from Celsius, Fahrenheit using Python
module. [ Formula : c/5 = f-32/9 ]
c. Write a python program to define a module to
find Fibonacci Numbers and import the module to
another program.
d. Develop a module named calculator.py in
12 14
Python, which contain three function –
factorial(n) : to find factorial of a number,
fibonacci(n) : to find Fibonacci series to a given
number. Perform following tasks:
a) Import the developed module
b) call the functions available in the module
i) to generate Fibonacci series upto a number, and
ii) to determine factorial of a number entered by
user.

a. Create a package in Python named as “Interest”


and within this package create two modules
simple.py and compound.py. The simple.py module
contains function Simple_Interest() and
compound.py module contains function
Compound_Interest().
b. Write a script named copyfile.py. This script
should prompt the user for the names of two text
files. The contents of the first file should be input
and written to the second file
c. Write a program that inputs a text file. The
13 15 program should print all of the unique words in the
file in alphabetical order.
d. Write a Python program that reads a text file and
prints its contents in reverse order (from the last
line to the first line).
e. Create a Python function make_copy() that reads
a text file 'input.txt' and writes its contents to a new
file 'output.txt', capitalizing the first letter of each
word. For example, if 'input.txt' contains the
following content.

[Assignment on Scripting Languages (Python) Laboratory Page 5


Week List of Program / Assignment Page No Actual Signature
Sl. No.
No Date
a. Demonstrate the following in-built functions to
use Regular Expressions very easily in our
applications.
i) compile() ii) finditer() iii) match()
iv) fullmatch() v) search() vi) findall() vii) sub()
viii) subn() ix) split()
b. Write a Regular Expression to represent all 10
14 16
digit mobile numbers. Rules:
1. Every number should contains exactly 10
digits.
2. The first digit should be 7 or 8 or 9.
Write a Python Program to check whether the
given number is valid mobile number or not?
Django Framework
a. Frameworks - The MVC framework,
b. Django- What is Django and why should you use
Django?
a. Creating URL, Templates
b. Send data to a template
15 17 c. Display data in a template
d. Display object lists in a template
e. Handle chains with filters in Django
f. Use URLs effectively
g. Create base templates in order to
extend other templates
a. Insert static files in our templates
Django Form
a.Create an HTML form
b.Handle the data sent by a form
18 c.Create a Django form
16
d.Validate and manipulate data sent from a
Django form
e. Create forms based on models
Customize error messages and usage of widget

[Assignment on Scripting Languages (Python) Laboratory Page 6


Scripting Languages (Python)
Course Code : CST213

Unit : 1 – Introduction, Variables and Data Types

History of Python Programming :


 Python is a high-level, general-purpose, interpreted, interactive and object-
oriented scripting language.
 It was created by Guido van Rossum during 1985- 1990.
 Like Perl, Python source code is also available under the GNU General Public
License (GPL).
Why the name python?
 Guido van Rossum was interested on watching a comedy show, which is
telecasting on the BBC channel from 1969 to 1974. The complete Monty
Python's Flying Circus.
 Guido Van Rossum thought he needed a name that was short, unique, and
slightly mysterious for his programming language, so he decided to call the
language Python.
Applications of Python Programming
 Web Development
 Game Development
 Scientific and Numeric applications
 Artificial Intelligence and Machine Learning based applications
 Data Science related applications
 Desktop GUI applications
 Software Development
 Enterprise-level/Business Applications
 Education programs and training courses
 Web Scraping Applications
 Image Processing and Graphic Design Applications

[Assignment on Scripting Languages (Python) Laboratory Page 7


 Data Analysis
Features of Python programming
 Simple and Easy to Learn
 Freeware and Open Source
 Dynamically typed
 Object Oriented Programming and Procedure Oriented Programming
 Extensive Library
 Embedded
 Extensible
 Interpreted
 Portability
 Platform Independent

Now, we are having a bit of clarity about the Python as a programming


language. Now, we need to work on the IDEs (Integrated Development
Environments) of Python, there are many IDEs like Jupyter Notebook,
Spyder, VS Code, R Programming etc., all are collectively available in
Anaconda (Anaconda is a free and open-source distribution of the Python and
R programming languages for scientific computing (data science, machine
learning applications, large-scale data processing, predictive analytics, etc.).

we may also go for the cloud versions Like Google Colab Notebook, where
we need not to have high configuration hardwares, only internet is required
and through our gmail account we can work on Python using Jupyter
notebook.

[Assignment on Scripting Languages (Python) Laboratory Page 8


Assignment 1a:
Write down the steps for Installing Python interpreter.
Just browse for https://www.python.org/downloads/ and perform following
steps :
 Download the latest version of Python for the operating system installed on
your computer, as in my case its windows 64 bit, so I downloaded python-
3.7.7 (python-3.7.7-amd64.exe) from
https://www.python.org/downloads/release/python-377/

 Now Run this exe file and install the Python, just click next and go ahead, till
the setup installation is finished

[Assignment on Scripting Languages (Python) Laboratory Page 9


 Finally we are having an interface for Python programming

 Assignment 1b:
Write down the instructions of setting up the path and running a script in
Interactive and Script mode in python.

In Python, there are two options / methods for running code:


o Interactive mode
o Script mode
Now, we will see the difference between the modes and will also discuss
the
pros and cons of running scripts in both of these modes.
 Interactive Mode :
Interactive mode, also known as the REPL (Read, Evaluate, Print, and
Loop) provides us with a quick way of running blocks or a single line of
Python code. The code executes via the Python shell, which comes with
Python installation. Interactive mode is handy when we just want to execute
basic Python commands or we are new to Python programming and just want
to get ourselves comfortable with this beautiful language.
To access the Python shell, open the terminal of our operating system

[Assignment on Scripting Languages (Python) Laboratory Page 10


(Windows + R) and then type "python". Press the enter key and the Python
shell will appear. This is the same Python executable we use to execute
scripts, which comes installed by default on Mac and Unix-based operating
systems.

The >>> indicates that the Python shell is ready to execute and send our
commands to the Python interpreter. The result is immediately displayed on
the Python shell as soon as the Python interpreter interprets the command.

To run your Python statements, just type them and hit the enter key. You will
get the results immediately, unlike in script mode. For example, to print the

text "Hello World", we can type the following:


Here are other example :

Pros and Cons of Interactive Mode


The following are the advantages of running your code in interactive mode:
 Helpful when our script is extremely short and we want immediate results.
 Faster as we only have to type a command and then press the enter key to get
the results.
 Good for beginners who need to understand Python basics.

[Assignment on Scripting Languages (Python) Laboratory Page 11


The following are the disadvantages of running our code in the interactive
mode:
 Editing the code in interactive mode is hard as you have to move back to the
previous commands or else you have to rewrite the whole command again.
 It's very tedious to run long pieces of code.
Consider the following example :

Next, we will be discussing the script mode.

 Script Mode :
If we need to write a long piece of Python code or our Python script spans
multiple files, interactive mode is not recommended. Script mode is the way
to go in such cases. In script mode, we write our code in a text file then save
it with a .py extension which stands for "Python". Note that we can use any
text editor for this, including Sublime, Atom, notepad++, notepad etc.

If we are in the standard Python shell or in Notepad, we can click "File" then
choose "New" or simply hit "Ctrl + N" on our keyboard to open a blank
script in which we can write our code. We can then press "Ctrl + S" to save
it.
Let us create a new file from the Python shell and give it the name
"hello.py". We
need to run the
"Hello World"
program. Add
the following
code to the file:

[Assignment on Scripting Languages (Python) Laboratory Page 12


or
For running python Code in Script Mode use the following Syntax :

Pros and Cons of Script Mode

The following are the advantages of running your code in script mode:
 It is easy to run large pieces of code.
 Editing your script is easier in script mode.
 Good for both beginners and experts.

[Assignment on Scripting Languages (Python) Laboratory Page 13


The following are the disadvantages of using the script mode:
 Code can be tedious when we need to run only a single or a few lines.
 We must create and save a file before executing our code.

Key Differences Between Interactive and Script


Mode
Here are the key differences between programming in interactive mode and
programming in script mode:
 In script mode, a file must be created and saved before executing the code to
get results. In interactive mode, the result is returned immediately after
pressing the enter key.
 In script mode, we are provided with a direct way of editing your code. This
is not possible in interactive mode.

Assignment 2a :
Write a script to purposefully raise Indentation Error and correct it.
As an interpreted, high-level and general-purpose programming language,
Python increasingly garners accolades as the programming world‘s most
promising, leading and emerging platforms. Python is nothing without its
ingenious design philosophy. A key characteristic is an emphasis drawn to
the notable use of significant indentation to enhance code-readability.
The ‗Indentation Error: Expected an indented block‘ occurs for all sorts of
users; whether they are newbies or experienced. Since Python arranges all of
its code by correct whitespaces, if WE have a bad indentation, the code will
not compile and we will be returned an error message. According to the
conventions followed in PEP8, there should be four whitespaces where
required. It is ideal for every programmer to use proper indentations so code
readability improves.

What causes Indentation Error in Python?

Like mentioned before, this error primarily occurs because there are space or
tab errors in our code. Since Python uses procedural language, we may

[Assignment on Scripting Languages (Python) Laboratory Page 14


experience this error if we have not placed the tabs/spaces correctly. The
program may run properly but if the interpreter finds this error, the error
message will come forth in the middle. Some of the causes of the error are:

 We are using both spaces and tabs in your code. If both are used
interchangeably, the interpreter will not be able to determine which item to
use.
 We have placed some indent wrong. If the indentation practice is not
followed, we will have this error inevitably.
 We forgot to indent the compound statements such as ‗if‘, ‗for‘, ‗while‘ etc.
 We forgot to indent user-defined functions or classes.

So, Indentation refers to the spaces at the beginning of a code line. Where in
other programming languages the indentation in code is for readability only,
the indentation in Python is very important. Python uses indentation to
indicate a block of code. The number of spaces is up to us as a programmer,
but it has to be at least one. We have to use the same number of spaces in the
same block of code; otherwise Python will give you an error.

So the correct form is as follows:

[Assignment on Scripting Languages (Python) Laboratory Page 15


Assignment 2b :
Explain and Demonstrate print(), Input(), format(), int() method with
examples of each.
Python Output
In Python, we can simply use the print() function to print output. For
example,

Here, the print() function displays the string enclosed inside the single
quotation.
Syntax of print() :
In the above code, the print() function is taking a single parameter.
However, the actual syntax of the print function accepts 5 parameters

print(object=”” separator=”” end=”” file=”” flush=””)

Here,
 object - value(s) to be printed
 sep (optional) - allows us to separate multiple objects inside print().
 end (optional) - allows us to add add specific values like new line "\n",
tab "\t"
 file (optional)- where the values are printed. It's default value
is sys.stdout (screen)
 flush (optional) - boolean specifying if the output is flushed or buffered.
Default: False
Example 1: Python Print Statement
We can use print() function to display output to the console for end user sake.

[Assignment on Scripting Languages (Python) Laboratory Page 16


Multiple forms are there related to print() function.

Example 2: Python Print Statement without argument

Note:
[Assignment on Scripting Languages (Python) Laboratory Page 17
If both arguments are string type then + operator acts as concatenation operator.
If one argument is string type and second is any other type like int then we will get Error.
If both arguments are number type then + operator acts as arithmetic addition operator.

[Assignment on Scripting Languages (Python) Laboratory Page 18


[Assignment on Scripting Languages (Python) Laboratory Page 19
[Assignment on Scripting Languages (Python) Laboratory Page 20
Assignment 2c :
Define type casting and explain Implicit and Explicit type casting with
example.

[Assignment on Scripting Languages (Python) Laboratory Page 21


[Assignment on Scripting Languages (Python) Laboratory Page 22
Assignment 2d :
Write a code to demonstrate comment statement in Python.
Comments in Python are the inclusion of short descriptions along with the
code to increase its readability. A developer uses them to write his or her
thought process while writing the code. It explains the basic logic behind
why a particular line of code was written. Comments are completely ignored
by the interpreter. They are meant for fellow programmers.

What Are Comments in Python Used For?


Comments in Python are identified with a hash symbol, #, and extend to the
end of the line. Hash characters in a string are not considered comments,
however. There are three ways to write a comment - as a separate line, beside
the corresponding statement of code, or as a multi-line comment block. There
are multiple uses of writing comments in Python. Some significant uses
include:

 Increasing readability
 Explaining the code to others
 Understanding the code easily after a long-term
 Including resources
 Re-using the existing code

What Are the Advantages of Using Comments in Python?

Comments in Python provide numerous advantages. Their primary benefits


include:
 Makes the code easily understandable by other programmers
 The code becomes self-explanatory
 Helps remember why we used a specific command, method, or function in the
code
 Enables the interpreter to ignore some part of the code while testing

[Assignment on Scripting Languages (Python) Laboratory Page 23


What Are the Different Types of Comments in Python?

There are three types of comments:


i. Single-Line Comments
ii. Multi-line Comments and
iii. docstring comments.
The syntax of comments varies depending on the type. Here we will explore
every kind of comment individually, along with examples.

i. Single-Line Comments
Single-line comments begin with the ―#‖ character. Anything that is written in
a single line after ‗#‘ is considered as comment. The syntax for writing single-
line comments is:
# This is the way to write comment statement in python
There are two ways of using single-line comments in Python. We can use it
before the code or next to the code. The example depicted below shows the
use of comments in both ways.We can also write a comment next to a code
statement. The next example shows that:

ii. Multi-line Comments :


Python doesn't offer a separate
way to write multiline
comments. However, there are
[Assignment on Scripting Languages (Python) Laboratory Page 24
other ways to get around this issue. We can use # at the beginning of each line
of comment on multiple lines. For example, Version 1 combines single-line
comments as follows:

Version 2 is simpler than version 1. It's


originally intended to be used for
creating documentation (see more
about this below), but it can also be
used for multi-line comments.

iii. Docstring Comments :


Python has a built-in concept called docstring, which is a great way to
associate documentation we've written with Python modules, functions, and
methods. A docstring is added as a comment right below the function, or
module, and describes what the function, module, or object does. It is
expected to follow these rules:

A docstring is either a single line, or a multi-line comment. In the latter case,


the first line is a short description, and after the first line an empty line
follows.

Begin the docstring with a capital letter, and end it with a period. This is a
basic example of what it looks like:

[Assignment on Scripting Languages (Python) Laboratory Page 25


Assignment 3:
a. Create a file named as “add.py” that takes 2 numbers as command line
argument and print the sum.

1. With Explicit Type Casting: Here the input arguments are converted as
integer and assigned to 2 variables after that sum of them is generated.

2. Without Type Casting: Here the input arguments which are by default
string type assigned to 2 variables and after sum of them is generated.

[Assignment on Scripting Languages (Python) Laboratory Page 26


Assignment 4 :
a. What do you mean slicing? Write down the Syntax of Slicing.
Slicing is a process of extracting data from a collection of data by specifying
the starting and ending indices and steps to be taken. It is the extraction of a
part of a string, list, or tuple. It enables users to access the specific range of
elements by mentioning their indices.
SYNTAX: - OBJECT [START: STOP: STEP]
➢ ―Start‖ specifies the starting index of a slice.
➢ ―Stop‖ specifies the ending element of a slice.
➢―Step‖ is an optional argument that determines the increment between each
index for slicing.

b. Write a program to demonstrate the characters of a string in reverse


order using slicing.

c. Write down a script using slicing to check whether a given string is


palindrome or not.

[Assignment on Scripting Languages (Python) Laboratory Page 27


Assignment 5 :
a. Write a script on given 2 strings, S1 and S2; create a new string by
appending S2 in the middle of S1.

b. Write a code implementing different string methods:


split() :-

join():-

[Assignment on Scripting Languages (Python) Laboratory Page 28


replace():-

capitalize():-

count():-

index():-

[Assignment on Scripting Languages (Python) Laboratory Page 29


strip():-

upper():-

lower():-

[Assignment on Scripting Languages (Python) Laboratory Page 30


partition():-

Assignment 6 :
a. State the purpose of using the Datetime module.
The ―datetime‖ module in python is used for working with dates and times. It
provides classes and functions to create, manipulate, format and perform
various operations on dates, times and time intervals. This module is essential
for tasks that involve handling time sensitive data, calculating durations
formatting timestamps, scheduling events and many other time related
operations. It simplifies complex date and calculations, ensuring accuracy and
consistency in applications that requires time related functionalities.

b. What are the different classes available in the Datetime module?


Explain each of them.
The datetime module is categorized into 6 main classes –
 Date  Timedelta
 Time  Tzinfo
 Datetime  Timezone

1. Date class: -
The date class is used to instantiate date objects in Python. When an object of
this class is instantiated, it represents a date in the format YYYY-MM-DD.
The constructor of this class needs three mandatory arguments year, month,
and date.

[Assignment on Scripting Languages (Python) Laboratory Page 31


SYNTAX: - CLASS DATETIME.DATE(YEAR, MONTH, DAY)
The arguments must be in the following range –
• MINYEAR <= year <= MAXYEAR
• 1 <= month <= 12
• 1 <= day <= number of days in the given month and year

<-----Valid parameter

<-----Nonvalid parameter

• There is different type of date class methods / functions –

2. Time class: - The time class creates the time object which represents local
time, independent of any day.
SYNTAX: - CLASS DATETIME.TIME (HOUR=0, MINUTE=0, SECOND=0,
MICROSECOND=0, TZINFO=NONE)

All the arguments are optional. tzinfo can be None otherwise all the attributes

[Assignment on Scripting Languages (Python) Laboratory Page 2


must be integer in the following range –
• 0 <=hour<24 • 0 <= minute < 60
• 0 <= second < 60 • 0 <= microsecond < 1000000

There is also different type of time class methods / functions –

Function Name Description


dst() Returns tzinfo.dst() is tzinfo is not None
Returns a time object from the string representation
fromisoformat()
of the time
Returns the string representation of time from the
isoformat()
time object
Changes the value of the time object with the given
replace()
parameter
Returns a string representation of the time with the
strftime()
given format
tzname() Returns tzinfo.tzname() is tzinfo is not None
utcoffset() Returns tzinfo.utcffsets() is tzinfo is not None

3. Datetime class: -
The Datetime class contains information on both date and time. Like a
date object, datetime assumes the current Gregorian calendar extended in
both directions; like a time, object, datetime assumes there are exactly
3600*24 seconds in every day.
SYNTAX: - CLASS DATETIME.DATETIME(YEAR, MONTH, DAY, HOUR=0,
MINUTE=0, SECOND=0, MICROSECOND=0, TZINFO=NONE)

The year, month, and day arguments are mandatory. tzinfo can be None,
rest all the attributes must be an integer in the following range –

[Assignment on Scripting Languages (Python) Laboratory Page 3


• MINYEAR <= year <= MAXYEAR
• 1 <= month <= 12
• 1 <= day <= number of days in the given month and year
• 0 <= hour < 24
• 0 <= minute < 60
• 0 <= second < 60
• 0 <= microsecond < 1000000

Note – Passing an argument other than integer will raise a Type Error and
passing arguments outside the range will raise Value Error.

[Assignment on Scripting Languages (Python) Laboratory Page 2


• Different type of datetime methods/functions –

Function Name Description

Returns the DateTime object containing timezone


astimezone()
information.

Combines the date and time objects and return a DateTime


combine()
object

ctime() Returns a string representation of date and time

date() Return the Date class object

Returns a datetime object from the string representation of


fromisoformat()
the date and time

Returns a date object from the proleptic Gregorian ordinal,


fromordinal() where January 1 of year 1 has ordinal 1. The hour, minute,
second, and microsecond are 0

fromtimestamp() Return date and time from POSIX timestamp

isocalendar() Returns a tuple year, week, and weekday

isoformat() Return the string representation of date and time

Returns the day of the week as integer where Monday is 1


isoweekday()
and Sunday is 7

now() Returns current local date and time with its parameter

replace() Changes the specific attributes of the DateTime object

[Assignment on Scripting Languages (Python) Laboratory Page 3


Returns a string representation of the DateTime object
strftime()
with the given format

Returns a DateTime object corresponding to the date


strptime()
string

time() Return the Time class object

timetuple() Returns an object of type time.struct_time

timetz() Return the Time class object

today() Return local Datetime with tzinfo as None

Return the proleptic Gregorian ordinal of the date,


toordinal()
where January 1 of year 1 has ordinal 1

tzname() Returns the name of the timezone

utcfromtimestamp() Return UTC from POSIX timestamp

utcoffset() Returns the UTC offset

utcnow() Return current UTC date and time

Returns the day of the week as integer where


weekday()
Monday is 0 and Sunday is 6

4. Timedelta class: -
Python timedelta class is used for calculating differences in dates and also can be
used for date manipulations in Python. It is one of the easiest ways to perform
date manipulations.
SYNTAX:- class datetime.timedelta(days=0, seconds=0, microseconds=0,
milliseconds=0, minutes=0, hours=0, weeks=0)

[Assignment on Scripting Languages (Python) Laboratory Page 4


 Operations supported by timedelta class –

Operator Description

Addition (+) Adds and returns two timedelta objects

Subtraction (-) Subtracts and returns two timedelta objects

Multiplication (*) Multiplies timedelta object with float or int

Division (/) Divides the timedelta object with float or int

Divides the timedelta object with float or int and


Floor division (//)
return the int of floor value of the output

Divides two timedelta object and returns the


Modulo (%)
remainder

+(timedelta) Returns the same timedelta object

-(timedelta) Returns the resultant of -1*timedelta

Returns the +(timedelta) if timedelta.days > 1=0


abs(timedelta)
else returns -(timedelta)

Returns a string in the form (+/-) day[s],


str(timedelta)
HH:MM:SS.UUUUUU

Returns the string representation in the form of


repr(timedelta)
the constructor call

5. Tzinfo class: -

The datetime.now() does not have any information about the time zones. It
just uses the current system time. In some situations, the time zone details may
be needed. In such cases the tzinfo abstract class is used. tzinfo is an abstract
base class. It cannot be instantiated directly. A concrete subclass has to derive

[Assignment on Scripting Languages (Python) Laboratory Page 5


it and implement the methods provided by this abstract class. The instance of
the tzinfo class can be passed to the constructors of the datetime and time
objects. It finds its applications in situations such as the conversion of local
time to UTC or to account for daylight saving time.
• List of python datetime.tzinfo objects:-

Function Description
Name

dst() Returns tzinfo.dst() is tzinfo is not None

The purpose of this function is to adjust the date time


fromutc()
data, returning an equivalent DateTime in self‘s local time.

tzname() Returns tzinfo.tzname() is tzinfo is not None

utcoffset() Returns tzinfo.utcffsets() is tzinfo is not None

6. Timezone class: -
Timezones in datetime can be used in the case where one might want to display
time according to the timezone of a specific region. This can be done using the
pytz module of Python. This module serves the date-time conversion
functionalities and helps users serving international client bases.
After installation import the pytz package and now let‘s see how we can pass in
the timezones. Basic syntax in Python to get the date and time information is:
datetime.datetime.now()
The above syntax returns the current local date-time without any timezone
information. But with the use of the pytz package we can handle this date-time
information in the various timezones –now() gives us the option to pass in a time
zone, so if you leave the time zone empty then it will also return the current local
date-time. The output of now() depends upon the machine. The local time and
time zone settings of the host machine will determine the output. So, in order to
work with the timezone smoothly, it is recommended to use the UTC as your
base timezone. To get the Universal Time Coordinated i.e. UTC time we just
pass in the parameter to now() function. To get the UTC time we can directly use
the ‗pytz.utc‘ as a parameter to now() function as ‗now(pytz.utc)‘. The offset will
be shown at the end as (+ or – hours). The below code shows the local time of
the machine and the UTC time with offset
[Assignment on Scripting Languages (Python) Laboratory Page 6
c. Write
a code implementing the following Datetime module with
syntax and example:
i. datetime.now(): - It returns a datetime value that represents the current
date and time on the local computer.
SYNTAX:- datetime.datetime.now()
(here class is datetime)

ii. datetime.today():- It is the alternative method of datetime.now()


method. It also returns a datetime value that represents the local date
and time. Its syntax is similar as datetime.now().
SYNTAX:- datetime.datetime.today()
(here class is datetime)

[Assignment on Scripting Languages (Python) Laboratory Page 7


iii. datetime.datetime(): -
To create a date, we can use the datetime() class of the datetime module.
The datetime() class requires three parameters to create a date: year,
month, day. The datetime() class also takes parameters for time and
timezone (hour, minute, second, microsecond, tzone), but they are
optional, and has a default value of 0, (None for timezone).
SYNTAX:- datetime.datetime(year, month, day, hour=0, minute=0,
second=0, microsecond=0, tzinfo=None)
(here class is datetime)

d. Demonstrate other examples of Datetime module implementing date


and time object.
Let see some other examples of datetime module -
o Strftime(): - The datetime object has a method for formatting date
objects into readable strings. The method is called strftime(), and takes
one parameter, format, to specify the format of the returned string.
SYNTAX: datetime_obj.strftime(format)
Parameters:

[Assignment on Scripting Languages (Python) Laboratory Page 8


 Format: consists of various format codes that define specific parts of
the date and time.
Returns: It returns the string representation of the date or time object.
There is different type of format we used to get output. These are –

o Isoweekday(): - Isoweekday() is a function that returns an integer that


tells the given date falls on. The integer it returns represents a day
according to the table given below.
Syntax: datetime.isoweekday ()

Return Value: an integer in range of [1, 7]

[Assignment on Scripting Languages (Python) Laboratory Page 9


Integer returned by isoweekday() function Day of the week

1 Monday

2 Tuesday

3 Wednesday

4 Thursday

5 Friday

6 Saturday

7 Sunday

[Assignment on Scripting Languages (Python) Laboratory Page 10


e. State the purpose of using timedelta object with python code.
In Python, the timedelta object is part of the datetime module and represents a
duration, which is the difference between two dates or times. It allows you to
perform arithmetic operations on dates and times. The main purpose of using a
timedelta object is to manipulate and perform calculations involving dates and
times.
Here are some common use cases for timedelta objects:
Date and Time Arithmetic: You can perform arithmetic operations such as
addition and subtraction with timedelta objects. For example, you can
calculate a future or past date/time by adding or subtracting a specific duration
from the current date/time.

Time Intervals: timedelta objects can be used to represent durations in terms


of days, hours, minutes, seconds, and microseconds. This is useful for tasks
like measuring the difference between two events.

Date and Time Comparison: You can compare dates and times using
timedelta objects to check if a certain duration has passed since a specific
event.

By utilizing timedelta objects, you can effectively work with dates and times in
Python and perform various operations related to time intervals and durations.
[Assignment on Scripting Languages (Python) Laboratory Page 11
Unit : 2 – CONTROL STRUCTURES

[Assignment on Scripting Languages (Python) Laboratory Page 12


Unit : 3 – FUNCTIONS, MODULE & PACKAGE

Week No. 10 Assignment No : 12


a. Write a script to create a menu with the following options
1. To Perform Addition 2. To Perform Subtraction
3. To Perform Multiplication 4. To Perform Division
Accepts Users Input and Performs the Operation accordingly. Use
Functions With Arguments.

10_12_b.py

ASS_X_XII_B.py

[Assignment on Scripting Languages (Python) Laboratory Page 13


b. Write a python program to find factorial of a number using Recursion.

c. Write a script to find First n Fibonacci numbers using a function.

d. Write a Python function that takes two lists and returns True if they
are equal otherwise false using function.

[Assignment on Scripting Languages (Python) Laboratory Page 14


Unit : 4 – FILE I/O, Text Processing, Regular Expression

[Assignment on Scripting Languages (Python) Laboratory Page 15


Unit : 5 – Django Frameworks
Framework
 The MVC framework,
 Django - What is Django and why should you use Django?
 Creating URL, Templates
o Send data to a template
o Display data in a template
o Display object lists in a template
o Handle chains with filters in Django
o Use URLs effectively
o Create base templates in order to extend other templates
o Insert static files in our templates

 Django Form
o Create an HTML form
o Handle the data sent by a form
o Create a Django form
o Validate and manipulate data sent from a Django form
o Create forms based on models
o Customize error messages and usage of widget

After completing this tutorial, students are expected to :

1. Understand the concept of MVT in Django applications

2. Understand the flow of Django displaying an HTML page

3. Understand the routing configuration in urls.py

4. Understand the relationship between models, views and template in Django

5. Understand the basic syntax for mapping data to HTML templates

[Assignment on Scripting Languages (Python) Laboratory Page 16


Framework :
In general, a framework is a real or conceptual structure intended to serve as a support or guide for the
building of something that expands the structure into something useful.
o Python is one of the most popular and effective programming languages that contain vast libraries and
frameworks for almost every technical domain.
o Python frameworks automate the implementation of several tasks and give developers a structure for
application development.
o Each framework comes with its own collection of modules or packages that significantly reduce
development time.
o A Python framework can either be full-stack, micro, or asynchronous. Before going into the popular
Python frameworks in detail, let's briefly introduce the various types of frameworks.
 Full-stack Framework : A full-stack framework contains all the web development requirements.
These include form generators, template layouts, form validation, and lots more.
 Micro Framework : Micro frameworks require a bit of manual work from developers. It is used for
minimalistic web application development since it lacks most of the functionality that comes along with
full-stack frameworks.
 Asynchronous Framework : Asynchronous frameworks use the asyncio (Asynchronous I/O)
library to run a number of processes concurrently. They can handle a large number of concurrent
connections.

Why Use a Framework?


There are a number of redundant operations in web development. Python frameworks allow developers to
reuse code for common HTTP operations. The projects are structured in such a way that other developers
with knowledge of that particular framework can easily use it to build and maintain web applications.
Some more advantages of using Python frameworks are listed below:
 Secure framework
 Easier implementation
 Open-source
 Good documentation
 Code reusability
 Efficient operations
 Easy integration
Library vs Framework
A library is a collection of packages that perform specific operations whereas a framework contains
the basic flow and architecture of an application. The major difference between them is the
complexity. Libraries contain a number of methods that a developer can just call whenever they write
code. With frameworks, you would need to build the rest of the other functionalities. However,

[Assignment on Scripting Languages (Python) Laboratory Page 17


frameworks offer a key advantage - flexibility. They provide the necessary tools and features that
developers can extend and build upon.
Top 5 Frameworks In Python : There are a number of Python frameworks available in the market for
web development. Depending on the functionality and key features they provide to the user, here are
the top 5 frameworks available in Python:

Web2Py : Web2Py is another popular open-source and full-stack Python framework. It is platform-
independent, which means that it can run on all the popular operating systems. Furthermore, it
simplifies the web application development process through its own web-based IDE that includes a
code editor, a debugger, and one-click deployment. Here are some more features of the Web2Py
framework:
 No prerequisites for installation 
and Data security
configuration  Error tracking mechanism
 Can read multiple protocols  Role-based access control
 Support different platforms  Backward compatibility

Flask : Flask is a micro-framework for Python. It is lightweight and easily adaptable to suit a
developer‘s needs. The Flask framework comes under the BSD license and requires the Werzeug
WSGI toolkit and Jinja2 templates. Here are some of the main features of the Flask framework:
 Fast debugger  WSGI compliance
 Jinja2 templating  Integrated support for unit testing
 Unicode-based  RESTful request dispatching
 Built-in development server  Secure cookies support
 HTTP request handling  Ability to plug any ORM

Bottle : Bottle is a micro-framework for prototyping and building simple personal applications. It
was originally meant for building APIs and is considered by developers as one of the finest Python
web frameworks. It also allows developers to work closely with the hardware to build small and
simplistic personal use apps. Here are some of the main features of the Bottle framework:

A built-in development server  Routing


 Access to form data, cookies, headers, file  Templating
uploads, cookies, headers, etc.  Abstraction layer over the WSGI
 Includes plugin support for different databases. standard

[Assignment on Scripting Languages (Python) Laboratory Page 18


CherryPy : CherryPy is an open-source Python framework that follows a minimalist approach for
building web applications. Released in 2002, it is one of the oldest Python frameworks still
popular today. Unlike other frameworks, you don't need to install the apache server to run
CherryPy. With CherryPy, you can build web applications the same way you would an object-
oriented program. The best thing about this framework is that it allows you to use any type of
technology for creating templates and data access. Here are some more features of using the
CherryPy framework:
 A flexible plugin system  Simplifies running multiple
 Built-in support for profiling, coverage, and HTTP servers at once
testing  Encoding
 Can run on different platforms  Authentication

Django : Django is a popular open-source full-stack Python framework that includes all the
necessary Python features by default. It follows the DRY principle - Don‘t Repeat Yourself.
Django uses an ORM or object-relational mapper to map objects to database tables. This helps
you use the object-oriented paradigm to manipulate data from a database. The main databases that
Django works on are Oracle, MySQL, PostgreSQL, and SQLite. It can also work on other
databases using third-party drivers. Here are some more exemplary features of the Django web
framework:

 URL routing

 Authentication

 Template engine

 Database schema migrations

 A plethora of ready-to-use libraries

 More secure as compared to other frameworks

[Assignment on Scripting Languages (Python) Laboratory Page 19


[Assignment on Scripting Languages (Python) Laboratory Page 20
1. What is Django?

o Django is a free and open-source web framework for Python that helps you build web
applications quickly and easily.

o Django, a high-level Python web framework, enables the rapid development of secure websites
you can actually maintain.

o Django is an open-source web app development framework based on Python programming


language. It is used to develop backend web applications. Its key objectives are integrating reliability,
scalability, adaptability, and simplicity into the web development process.

1. What are the key features of Django?

The key features of Django include:

o Pythonic : Django is written in Python, a popular and powerful programming language.

o MVT: Django follows the Model-View-Template (MVT) architecture pattern, which makes it
easy to develop and maintain complex web applications.

o ORM : Django includes an Object-Relational Mapper (ORM) that makes it easy to interact with
databases.

o Security : Django is designed with security in mind, and includes a number of features that help
to protect your web applications from common attacks.

o Documentation: Django comes with extensive documentation that makes it easy to learn and use.

2. What are the advantages of using Django?

The advantages of using Django include:

o Quick and easy development: Django makes it easy to build web applications quickly and
easily.

o Scalable: Django is scalable and can be used to build web applications of any size.

o Secure: Django is designed with security in mind, and includes a number of features that help to
protect your web applications from common attacks.

o Extensible: Django is extensible and can be customized to meet your specific needs.

[Assignment on Scripting Languages (Python) Laboratory Page 1


o Community: Django has a large and active community that is available to help you with any
problems you may encounter.

3. What are the disadvantages of using Django?


The disadvantages of using Django include:

o Steep learning curve: Django can have a steep learning curve, and may not be suitable for
beginners.

o Not as flexible as some other frameworks: Django is not as flexible as some other frameworks,
and may not be suitable for all projects.

o Requires Python: Django requires Python, which may not be installed on all systems.

4. What are some of the most popular websites that use Django?

o Instagram : Instagram is a photo and video sharing social networking service.

o Disqus : Disqus is a platform for comments and discussions.

o Bitbucket : Bitbucket is a code hosting service.

o Pinterest : Pinterest is a visual bookmarking service.

o Django Girls: Django Girls is a community that helps women learn Django.

5. How Does Django Work?

Any Django project consists of four main files that create the application‘s core.

o URLs.py: A URL mapper file to redirect HTTP requests to the view file based on the request URL.

o Views.py: A view file takes in HTTP requests and returns HTTP responses. The view file gets the data
from the model file and sends the response to the template‘s text file for rendering.

o Models.py: A file that defines the structure and management of the application‘s data.

o Templates.html: A file that contains the web page‘s layout.

[Assignment on Scripting Languages (Python) Laboratory Page 2


o Django is a framework that follows the
MVT (Model-View-Template) structure.
MVT is a derivative of the MVC (Model-
View-Controller) structure, but the model is
more focused on the object that defines the
entities in the database and their
configuration, the views serve as the main
logic of the application that will process
incoming requests, and the template serves
as the views that will be returned to the user.

The flow of a request being processed in Django is as follows. First, incoming requests to the Django
server will be processed through urls to be forwarded to the views defined by the developer to
process the request. If there is a process that requires the involvement of a database, then the views
will call a query to models and the database will return the result of the query to the views. After the
request has been processed, the result of the process will be mapped into the HTML that has been
defined before finally the HTML is returned to the user as a response.

6. Is Django Front End or Back End?


Django is a framework that bridges both the front end and the back end; in fact, it serves as both.
Since Django is built upon Python (which we use to deal with databases and perform the back end
functionalities), we can consider it a back end tool. However, Django also allows us to edit HTML
files and create HTML pages, which is front end functionality. So, Django is basically a tool that
allows us to develop both the front and back ends of our application in the same place.

[Assignment on Scripting Languages (Python) Laboratory Page 3


Django Architecture
Django follows the MVT or Model View Template architecture which is based on the MVC or Model
View Controller architecture. The main difference between these two is that Django itself takes care of
the controller part.
MVC stands for Model View Controller. It is used for developing the web applications, where we
break the code into various segments. Here we have 3 segments — model, view and a controller.

Model — Model is used for storing and maintaining your data. It is the backend where your database
is defined.

Views — In Django templates, views are in html. View is all about the presentation and it is not at all
aware of the backend. Whatever the user is seeing, it is referred to a view.

Controller — Controller is a business logic which will interact with the model and the view. Now that
we have understood MVC, lets learn about Django MVT pattern.

MVT stands for Model View Template. In MVT, there is a predefined template for user interface.
Let‘s take an example, say you want to write several static html forms like hello user1, hello user2 and
so on. With template, you will be having only one file that prints hello along with the variable name.
Now this variable will be substituted in that particular template using some jinja logic. That‘s the
magic of template; you don‘t need to rewrite the code again n again!
Now we might be wondering where is the controller?
In the case of MVT, Django itself takes care of the controller part, it‘s inbuilt. That is, it‘s probably the
framework itself: the machinery that sends a request to the appropriate view, according to the Django
URL configuration.

So, in the case of Django, this is what each component is doing:

 The MODEL helps to handle database. It is a data access layer, which contains the required fields and
behaviors of the data you‘re storing. There‘s hardly an application without a database. A model is a
Python class, and it does not know anything about other Django layers. Models help developers to
create, read, update, and delete objects (CRUD operations) in the original database. Also, they hold
business logic, custom methods, properties, and other things related to data manipulation.

[Assignment on Scripting Languages (Python) Laboratory Page 4


 The VIEW is used to execute the business logic and interact with a model to carry data and renders a
template. The view fetches data from a model. Then, it either gives each template access to specific
data to be displayed, or it processes data beforehand. It accepts HTTP requests, applies business logic
provided by Python classes and methods, and provides HTTP responses to the client requests.

 The TEMPLATE is a presentation layer that handles the User Interface part completely. These are
files with HTML code, which is used to render data. The contents of these files can be static or
dynamic. A template is used only to present data since there‘s no business logic in it.

 A “view” is the Python callback function for a particular URL, because that callback function describes
which data is presented.

 Furthermore, it‟s sensible to separate content from presentation — which is where templates come in.
In Django, a “view” describes which data is presented, but a view normally delegates to a template,
which describes how the data is presented.

 The „controller‟ here is Django itself which sends the request to the appropriate view in accordance
with the specified URL. This is why Django is referred to as MTV rather than MVC architecture.
The developer provides the model, the view, and the template, then maps it to a URL, and Django
does the magic, to serve it to the user.

In short, a web application has data, layout, and logic. The model will work with the data, the view
will work with the logic, and the template will work with the layout. Moving ahead in Django tutorial,
let‘s understand how things work internally.

Simple Overview of Django MVT Architecture


In the image, template is your front end which will
interact with the view and the model will be used as a
backend. Then view will access both the model and
the templates and maps it to a url. After that, Django
plays the role of controller and serves it to the user.

[Assignment on Scripting Languages (Python) Laboratory Page 5


How to install Django on Windows 7 and 8
The steps in this guide have been tested with Windows 7 and 8.
Video Link : https://www.youtube.com/watch?v=VuETrwKYLTM
Text Link : https://docs.djangoproject.com/en/1.8/howto/windows/#install-python
----------------------------------------------------------------------------------------
Django is a Python web framework, thus requiring Python to be installed on your machine.
1. Install Python
a. To install Python on your machine go to https://python.org/download/, and download a
Windows MSI installer for Python. Once downloaded, run the MSI installer.

b. After installation, open the command prompt and check the Python version by executing python --
version. If you encounter a problem, make sure you have set the PATH variable correctly. You
might need to adjust your PATH environment variable to include paths to the Python executable and
additional scripts. For example, if your Python is installed in C:\Python34\, the following paths need
to be added to PATH:
C:\Python34\;C:\Python34\Scripts;
or
C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\Scripts\;
C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\;

2. Install PIP - pip is a tool to install the python community packages


a. PIP is a package manager for Python that uses the Python Package Index to install Python
packages. PIP will later be used to install Django from PyPI. If you‘ve installed Python 3.4, pip is
included so you may skip this section.
b. Open a command prompt and execute easy_install pip. This will install pip on your system. This
command will work if you have successfully installed Setup tools.
pip --version
pip 23.0.1 from c:\users\lenovo\appdata\local\programs\python\python37-32\lib\site-
packages\pip (python 3.7)

3. Install Django
First check django is install or not by using following command ---
>>>django-admin --version

if not, then Django can be installed easily using pip. In the command prompt, execute the following

[Assignment on Scripting Languages (Python) Laboratory Page 6


command: --- >>pip install virtualenvwrapper-win

then type >>> mkvirtualenv <env_name>


>>> mkvirtualenv test
Which install virtual env wrapper.

How and why we use virtualenv and virtualenvwrapper when we develop apps using Django?

Why?
We usually work on multiple projects in a single system. Each project might have different versions
of dependencies. So, it is always advisable to isolate the environments. This way, we can install all
the dependencies of a project in one environment and easily switch between different environments
when switching different projects.

Now, check django is install or not by using following command

Then --- >>>pip install django

This will download and install Django. After the installation has completed, you can verify your
Django installation by executing another command django-admin --version in the command prompt.

[Assignment on Scripting Languages (Python) Laboratory Page 7


check django is install or not by using following command
>>>django-admin --version
3.2.18

Now, create our first project.


<test> d:\django_project>django-admin startproject project1
<test> d:\django_project>cd project1
<test> d:\django_project\project1>pip install django
<test> d:\django_project\project1>python manage.py runserver
or
<test> d:\django_project\project1>python manage.py migrate
<test> d:\django_project\project1>python manage.py runserver
Let’s Understand the Project & Web
Application Directory / File Structure :
For creating a web application, first let‘s create
a project. To create a project, just enter into a
directory where you would like to share your
code, then run the following command:
>> django-admin startproject project1

Once your project has been created, you will


find a list of files inside the project directory.

[Assignment on Scripting Languages (Python) Laboratory Page 8


Let‘s discuss each one of them.
manage.py — It is a command-line utility that lets you interact with this Django project in various
ways.
project1/ — It is the actual Python package for our project. It is used to import anything, say —
project1.urls.
init.py — Init just tells the python that this is to be treated like a python package.
settings.py — This file manages all the settings & configuration of your project.
urls.py — This is the main controller which maps it to your website.
wsgi.py — This is an entry-point for the web servers to serve the project we have created. It serves as
an entry point for WSGI (Web Server Gateway Interface) compatible web servers. The Web Server
Gateway Interface is a simple calling convention for web servers to forward requests to web
applications or frameworks written in the Python programming language.

Why is the MVT Architecture Important for Any Django Web Application?
Django is based on a Pythonic structure. Model-View-Controller (MVC) was the original
structure and is still in the most recent version. The MVC architecture enables developers to
modify an app's business logic and visual components independently without affecting the
other. But in reality, the model-view-template (MVT) is how developers typically refer to
the Django architecture. Model, View, and Template are the three layers. Each layer has a
different function and can be utilized independently.

A model is "the one authoritative source of knowledge about your data," according to the Django
documentation. The key fields and behaviours of the data you're saving are included in it. Each
model typically corresponds to a single database table. There are often four databases used by
applications: PostgreSQL, MySQL, SQLite, and Oracle, which Django officially support.

Models represent attributes and contain information about your data. A model does not know other

[Assignment on Scripting Languages (Python) Laboratory Page 9


Django layers because it is a simple Python class. An application programming interface is the only
means of communication between layers (API).

Models store data manipulation-related elements such as attributes, custom methods, and business
logic. Objects (data sets) in the original database can also be created, read, updated, and deleted with
the help of models.

The view performs tree tasks, including HTTP request acceptance, a business logic application using
Python classes and methods, and HTTP response generation for client requests. To put it another
way, the view retrieves data from a model and either grants access to specific data for each template
to be presented or prepares data for display.
Django includes a robust template engine and a rich toolkit for its own markup language. Templates
are HTML-coded files that are used to render data.
These files' contents may be static or dynamic. A
template exists only to present data; it contains no
business logic.
Creating Django Template:
Django is a powerful framework for creating web
applications in Python. Its features include database
models, routing URLs, authentication, user
management, administrative tools, and a template language. We can compose reusable HTML that
changes based on the data we pass to the template language. Django templates use tags and filters to
define a mini-language that‘s similar to Python—but isn‘t Python.

Why Django Templates

Django template is a text document or Python string marked up that uses Django template language.
Django keeps the logic and code separate from the design. It is essential to know that Django
templates do not contain the embedded code of Python into HTML.
Django templates follow the DRY (do not repeat yourself) design principle, which requires
developers to not repeat while designing a Django application. Django templates employ several
other notions, such as template inheritance, tags, variables, filters, comments, etc.

The ―project1‖ folder is just our project container, it actually contains two elements −

[Assignment on Scripting Languages (Python) Laboratory Page 10


 manage.py − this file is kind of your project local django-admin for interacting with your project via
command line (start the development server, sync db). To get a full list of command accessible via
manage.py you can use the code −
 The “project1” subfolder − this folder is the actual python package of our project. It contains four
files −
o __init__.py − Just for python, treat this folder as package.
o settings.py − As the name indicates, our project settings.
o urls.py − All links of our project and the function to call.
o wsgi.py − If we need to deploy our project over WSGI.
How to Create a Basic Project using MVT in Django?
 To initiate a project of Django on our PC, open Terminal and Enter the following command
(test) d:\django_project>django-admin startproject project1

• A New Folder with the name myproject will be created. To enter in the project using the
terminal enter command
cd <projectName> e.g. (test) d:\django_project>cd project1

• Create a new file views.py inside the project folder where settings.py, urls.py and other files are
stored and save the following code in it.

(test) d:\django_project\project1>
Code of Views:
from django.http import HttpResponse

def print_hello (request) :


return HttpResponse("<center><b>This is my first Django project. </b></center>")

• Open urls.py inside project folder (project1) and add your entry-
 import print_hello //function from views.py file.
from project1.views import print_hello

• Add an entry in url field inside url patterns –


o path('project1/', print_hello),

[Assignment on Scripting Languages (Python) Laboratory Page 11


• Start the server- Start the server by typing following command in cmd
o python manage.py runserver
• Check to the browser : http://127.0.0.1:8000/project1/

Django App
What is an app?
 An app is a module in django project which represents a part of the overall project.
Create an app folder
 After creating the project the directory structure looks like below .

[Assignment on Scripting Languages (Python) Laboratory Page 12


Django App Structure
 __init__.py - It specifies the current directory as a python package
 apps.py - It's the django app configuration file. It contains app name and other config.
 models.py - It contains the ORM models, which represents the database tables.
 migrations/ - It contains the django database migration files to update the database changes.
 admin.py - Django comes with a powerful admin module. This file used to add the app
models to admin.
 tests.py - It contains the django unit tests.

add my_app to django project


 open the project settings file my_project/settings.py and update the INSTALLED_APPS as below.

Django Template

 Django template is a text document or a Python string marked -up using the Django template
language.
 Django separates the views and templates for better readability and maintainability
 views: responsible for handling the request and generating the context for the template
 templates: templates uses the context generated by the views and creates the HTTP response
A Django template is a text file. While in the vast majority of cases this text file is an HTML file, Django
templates can also be non-HTML files. Non-HTML examples include email templates and CSV
templates.

To turn a plain text file into a Django template, the template designer adds template tags,
variables and filters.
A template tag is surrounded by {% and %}. A template tag does something. This is deliberately vague
because Django‘s tags are extremely flexible. Some example functions performed by template tags are:

 Display Logic. E.g., {% if %}...{% endif %}


 Loop Control. E.g., {% for x in y %}...{% endfor %}
 Block Declaration. E.g., {% block content %}...{% endblock %}

[Assignment on Scripting Languages (Python) Laboratory Page 13


 Content Import. E.g., {% include "header.html" %}
 Inheritance. E.g., {% extends "base.html" %}

It‘s also possible to create custom template tags to extend the DTL.

A template variable is surrounded by {{ and }}. A template variable is something. Template variables
are passed to the template at runtime in the context. We‘ll dig deeper into template contexts shortly.

Template variables don‘t just handle simple data, they work with more complex data structures too. For
example:

 Simple Variables. E.g., {{ title }}


 Object Attributes. E.g., {{ page.title }}
 Dictionary Lookups. E.g., {{ dict.key }}
 List Indexes. E.g., {{ list_items.0 }}
 Method Calls. E.g., {{ var.upper }}, {{ mydict.pop }}

With few exceptions, the methods and attributes available to the Python object are also accessible in the
template via the dot operator.

Filters modify a variable for display. You apply a filter to a variable using the | (pipe) character. There
are dozens of built-in filters; here are some examples:

 Change Case. E.g., {{ name|title }} or {{ units|lower }}


 Truncation. E.g., {{ post_content|truncatewords:50 }}
 Date Formatting. E.g., {{ order_date|date:"D M Y" }}
 List Slicing. E.g., {{ list_items|slice:":3" }}
 Default Values. E.g., {{ item_total|default:"nil" }}

Configure Template Directory

 Create a directory named “templates” at project level.


 The project structure should look like below.
 open file project1/settings.py and update
the TEMPLATES setting as below.

Use template in django view

 C
r
e
a
t
e

t
h
e template file templates/index.html in the project root directory.
 Let's use the code from Django first_view() and modify it as below.

[Assignment on Scripting Languages (Python) Laboratory Page 14


 is function provided by django which takes the request , template , context and returns the
render
HTTP response.Let's look at the template code.

HTML forms (DJANGO)

In HTML, a form is a collection of elements inside <form>...</form> that allow a visitor to do


things like enter text, select options, manipulate objects or controls, and so on, and then send that
information back to the server.

Some of these form interface elements - text input or checkboxes - are built into HTML itself. Others
are much more complex; an interface that pops up a date picker or allows you to move a slider or
manipulate controls will typically use JavaScript and CSS as well as HTML form <input> elements
to achieve these effects.

As well as its <input> elements, a form must specify two things:

 where: the URL to which the data corresponding to the user‘s input should be returned

 how: the HTTP method the data should be returned by

[Assignment on Scripting Languages (Python) Laboratory Page 15


As an example, the login form for the Django admin contains several <input> elements: one
of type="text" for the username, one of type="password" for the password, and one
of type="submit" for the ―Log in‖ button. It also contains some hidden text fields that the user
doesn‘t see, which Django uses to determine what to do next.

It also tells the browser that the form data should be sent to the URL specified in
the <form>‘s action attribute - /admin/ - and that it should be sent using the HTTP mechanism
specified by the method attribute - post.

When the <input type="submit" value="Log in"> element is triggered, the data is returned
to /admin/.

GET and POST

GET and POST are the only HTTP methods to use when dealing with forms.

Django‘s login form is returned using the POST method, in which the browser bundles up the form
data, encodes it for transmission, sends it to the server, and then receives back its response.

GET, by contrast, bundles the submitted data into a string, and uses this to compose a URL. The
URL contains the address where the data must be sent, as well as the data keys and values.

GET and POST are typically used for different purposes.

Any request that could be used to change the state of the system - for example, a request that makes
changes in the database - should use POST. GET should be used only for requests that do not affect
the state of the system.

GET would also be unsuitable for a password form, because the password would appear in the URL,
and thus, also in browser history and server logs, all in plain text. Neither would it be suitable for
large quantities of data, or for binary data, such as an image. A web application that
uses GET requests for admin forms is a security risk: it can be easy for an attacker to mimic a form‘s
request to gain access to sensitive parts of the system. POST, coupled with other protections like
Django‘s CSRF protection offers more control over access. On the other hand, GET is suitable for
things like a web search form, because the URLs that represent a GET request can easily be
bookmarked, shared, or resubmitted.

[Assignment on Scripting Languages (Python) Laboratory Page 16


An Example of Django Forms
A form is essentially a way of passing information from our front-end (HTML) to our back-end
(in this case python). There are two different methods a form can use, POST and GET. In this tutorial
we will discuss how to use django built in forms to add new To Do Lists to our application.
Creating a New Page
We are going to need to add a new page to the site that will allow us to create a new ToDoForm. We
will need to do the following:
 Create a new template (LoginForm.html, RegForm.html, myDashboard.html)
 Create a new view function inside of views.py
 Add a new link / URL (url.py)
Here we are creating our template as LoginForm.html, RegForm.html, and myDashboard.html
LoginForm.html

RegForm.html

[Assignment on Scripting Languages (Python) Laboratory Page 17


myDashBoard.html
.
h
t
m
m
y
D
a

T
h
e

n
e
Now the next step is to add a new function inside views.py that will be able to render this html for us.

Now we can add a new URL to this page from urls.py

[Assignment on Scripting Languages (Python) Laboratory Page 18


Django’s role in forms

Handling forms is a complex business. Consider Django‘s admin, where numerous items of data of
several different types may need to be prepared for display in a form, rendered as HTML, edited
using a convenient interface, returned to the server, validated and cleaned up, and then saved or
passed on for further processing. Django‘s form functionality can simplify and automate vast
portions of this work, and can also do it more securely than most programmers would be able to do in
code they wrote themselves.

Django handles three distinct parts of the work involved in forms:

 preparing and restructuring data to make it ready for rendering

 creating HTML forms for the data

 receiving and processing submitted forms and data from the client

It is possible to write code that does all of this manually, but Django can take care of it all for you.

Forms in Django

We‘ve described HTML forms briefly, but an HTML <form> is just one part of the machinery
required.

In the context of a web application, ‗form‘ might refer to that HTML <form>, or to the
Django Form that produces it, or to the structured data returned when it is submitted, or to the end-
to-end working collection of these parts.

The Django Form class

At the heart of this system of components is Django‘s Form class. In much the same way that a
Django model describes the logical structure of an object, its behavior, and the way its parts are
represented to us, a Form class describes a form and determines how it works and appears.

[Assignment on Scripting Languages (Python) Laboratory Page 19


In a similar way that a model class‘s fields map to database fields, a form class‘s fields map to
HTML form <input> elements. (A ModelForm maps a model class‘s fields to HTML
form <input> elements via a Form; this is what the Django admin is based upon.) A form‘s fields
are themselves classes; they manage form data and perform validation when a form is submitted.
A DateField and a FileField handle very different kinds of data and have to do different things with
it. A form field is represented to a user in the browser as an HTML ―widget‖ - a piece of user
interface machinery. Each field type has an appropriate default Widget class, but these can be
overridden as required.

Instantiating, processing, and rendering forms

When rendering an object in Django, we generally:

1. get hold of it in the view (fetch it from the database, for example)

2. pass it to the template context

3. expand it to HTML markup using template variables

Rendering a form in a template involves nearly the same work as rendering any other kind of object,
but there are some key differences.

In the case of a model instance that contained no data, it would rarely if ever be useful to do anything
with it in a template. On the other hand, it makes perfect sense to render an unpopulated form - that‘s
what we do when we want the user to populate it. So when we handle a model instance in a view, we
typically retrieve it from the database. When we‘re dealing with a form, we typically instantiate it in
the view.

When we instantiate a form, we can opt to leave it empty or prepopulate it, for example with:

 data from a saved model instance (as in the case of admin forms for editing)
 data that we have collated from other sources
 data received from a previous HTML form submission

The last of these cases is the most interesting, because it‘s what makes it possible for users not just to
read a website, but to send information back to it too.

Django Form Demonstration using project creation -- reg_form :


1. Create a project reg_form with the following syntax :

[Assignment on Scripting Languages (Python) Laboratory Page 20


2. A New Folder with the name myproject will be created. To enter in the project using the terminal
enter command
cd <projectName> e.g. (test) d:\django_project>cd reg_form

3. Create a ―templates‖ folder for keeping those html files for Registration, Login, Logout and
dashboard - after login where it will be redirected to stay.

4. Then create three files named as Signup.html, Login.html & Home.html and write the same code
available here.
5. Code of Home.html

6. Code of Signup.html

[Assignment on Scripting Languages (Python) Laboratory Page 21


7. Code of Login.html

8. Create a new file views.py inside the reg_form folder where settings.py, urls.py and other files
are stored and save the following code in it.
9. Code of Settings.py

[Assignment on Scripting Languages (Python) Laboratory Page 22


10. Code of urls.py

11. Code of views.py

[Assignment on Scripting Languages (Python) Laboratory Page 23


12. Create Super User for this project to Keep track of user information
>>python manage.py createsuperuser

13. Configuring the Project before running the project


>>>python manage.py makemigrations
>>>python manage.py migrate

14. Run the project use these commands


>>>python manage.py runserver
15. Project is working :

[Assignment on Scripting Languages (Python) Laboratory Page 24

You might also like