Lab Manual On Scripting Languages - CST 2nd - 2023-24
Lab Manual On Scripting Languages - CST 2nd - 2023-24
Topic Covered:
PROGRAM: DIPLOMA
1. Introduction, Variables SEMSTER : 3rd
and Data Types
YEAR : 2nd
2. Control Structures
3. Functions,
Modules and
Packages
5. Frameworks
Prepared by:
Mr. Raj Kumar Datta (Lecturer)
Department of Computer Science & Technology
K G Engineering Institute,
Bishnupur, Bankura, West Bengal - 722122
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.
Now Run this exe file and install the Python, just click next and go ahead, till
the setup installation is finished
Assignment 1b:
Write down the instructions of setting up the path and running a script in
Interactive and Script mode in python.
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
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:
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 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.
Like mentioned before, this error primarily occurs because there are space or
tab errors in our code. Since Python uses procedural language, we may
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.
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
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.
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.
Increasing readability
Explaining the code to others
Understanding the code easily after a long-term
Including resources
Re-using the existing code
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:
Begin the docstring with a capital letter, and end it with a period. This is a
basic example of what it looks like:
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.
join():-
capitalize():-
count():-
index():-
upper():-
lower():-
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.
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.
<-----Valid parameter
<-----Nonvalid parameter
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
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 –
Note – Passing an argument other than integer will raise a Type Error and
passing arguments outside the range will raise Value Error.
now() Returns current local date and time with its parameter
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)
Operator Description
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
Function Description
Name
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)
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
7 Sunday
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
10_12_b.py
ASS_X_XII_B.py
d. Write a Python function that takes two lists and returns True if they
are equal otherwise false using function.
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
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:
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
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 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.
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.
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 Django Girls: Django Girls is a community that helps women learn Django.
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.
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.
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.
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.
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.
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\;
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
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.
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.
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
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.
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 −
• 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
• 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
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 .
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:
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:
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:
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.
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.
where: the URL to which the data corresponding to the user‘s input should be returned
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 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.
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.
RegForm.html
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.
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.
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.
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.
1. get hold of it in the view (fetch it from the database, for example)
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.
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
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