0% found this document useful (0 votes)
78 views27 pages

Software Environment

Python is a high-level, general-purpose programming language that can be used for a wide variety of tasks including web and software development. It was created by Guido van Rossum in 1991 and its design philosophy emphasizes code readability. Some key uses of Python include web development, data analysis, and scientific computing.

Uploaded by

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

Software Environment

Python is a high-level, general-purpose programming language that can be used for a wide variety of tasks including web and software development. It was created by Guido van Rossum in 1991 and its design philosophy emphasizes code readability. Some key uses of Python include web development, data analysis, and scientific computing.

Uploaded by

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

What is Python?

 Python is a High level, structured, open-source programming language that


can be used for a wide variety of programming tasks.

 Python within itself is an interpreted programming language that is


automatically compiled into bytecode before execution.

 It is also a dynamically typed language that includes (but does not require
one to use) object-oriented features.

 NASA has used Python for its software systems and has adopted it as the
standard scripting language for its Integrated Planning System.

 Python is also extensively used by Google to implement many components


of its Web Crawler and Search Engine & Yahoo! for managing its
discussion groups.

History of Python
 Python was created by Guido Van Rossum.
 The design began in the late 1980s and was first released in February 1991.
Why the name Python?
No. It wasn't named after a dangerous snake. Rossum was fan of a comedy
series from late 70s. The name "Python" was adopted from the same series
"Monty Python's Flying Circus".

1
Python Version History
Implementation started - December 1989
Internal releases – 1990

Version No. Date of Released


0.9 February 20, 1991
1.0 January, 1994
2.0 October 16, 2000
3.0 December 3, 2008
3.1 June 27, 2009
3.2 February 20, 2011
3.3 September 29, 2012
3.4 March 16, 2014
3.5 September 13, 2015
3.6 December 23, 2016
3.7 June 27, 2018

2
Features of Python Programming

1. A simple language which is easier to learn

 Python has a very simple and elegant syntax.


 It's much easier to read and write Python programs compared to
other languages like: C++, Java, C#.
 Python makes programming fun and allows you to focus on the
solution rather than syntax.
 If you are a newbie, it's a great choice to start your journey with
Python.

2. Free and open-source

 You can freely use and distribute Python, even for commercial use.
 Not only you can use and distribute software’s written in it, you can
even make changes to the Python's source code.
 Python has a large community constantly improving it in each
iteration.

3
3. Portability

 You can move Python programs from one platform to another and
run it without any changes.
 It runs seamlessly on almost all platforms including Windows, Mac
OS and Linux.

4. Extensible and Embeddable

 Suppose an application requires high performance. You can easily


combine pieces of C/C++ or other languages with Python code.
 This will give your application high performance as well as scripting
capabilities which other languages may not provide out of the box.

5. A high-level, interpreted language

 Unlike C/C++, you don't have to worry about daunting tasks like
memory management, garbage collection and so on.
 Likewise, when you run Python code, it automatically converts your
code to the language your computer understands. You don't need to
worry about any lower-level operations.

6. Large standard libraries to solve common tasks

 Python has several standard libraries which makes life of a


programmer much easier since you don't have to write all the code
yourself.
 For example: Need to connect MySQL database on a Web server?
You can use MySQL dB library using import MySQL db.
 Standard libraries in Python are well tested and used by hundreds of
people. So, you can be sure that it won't break your application.

4
7. Object-oriented

 Everything in Python is an object. Object oriented programming


(OOP) helps you solve a complex problem intuitively.
 With OOP, you can divide these complex problems into smaller sets
by creating objects.

4 Reasons to Choose Python as First Language

1. Simple Elegant Syntax

 Programming in Python is fun. It's easier to understand and write


Python code. Why? The syntax feels natural. Take this source code
for an example:

a=2
b=3
sum = a + b
print(sum)

 Even if you have never programmed before, you can easily guess
that this program adds two numbers and prints it.

2. Not overly strict

 You don't need to define the type of a variable in Python. Also, it's
not necessary to add semicolon at the end of the statement.
 Python enforces you to follow good practices (like proper
indentation). These small things can make learning much easier for
beginners.

5
3. Expressiveness of the language

 Python allows you to write programs having greater functionality


with fewer lines of code. Here's a link to the source code of Tic-tac-
toe game with a graphical interface and a smart computer opponent
in less than 500 lines of code. This is just an example. You will be
amazed how much you can do with Python once you learn the
basics.

4. Great Community and Support

 Python has a large supporting community. There are numerous


active forums online which can be handy if you are stuck. Some of
them are:

 Google Forum for Python

 Python Questions - Stack Overflow

Python vs PHP
From the development point of view, PHP is a web-oriented language.
Choosing between Python or PHP for web applications pay attention to these
characteristics:

6
Python vs Java

7
Python vs C#

Difference between Ruby and Python

In terms of the first language, Ruby and Python are the most popular ones.
Ruby is extremely popular technology for building websites. Among the most
famous are Twitter (the early version), Basecamp, Github, Airbnb, Slideshare and
Groupon.

8
Installing and Running Python in Windows
1. Go to Download Python page on the official site and click Download
Python 3.7 (You may see different version name).

2. When the download is completed, double-click the file and follow the
instructions to install it.

When Python is installed, a program called IDLE is also installed along


with it. It provides graphical user interface to work with Python.
3. Open IDLE, copy the following code below and press enter.

4. print("Hello, World!")

5. To create a file in IDLE, go to File > New Window (Shortcut: Ctrl+N).

9
6. Write Python code (you can copy the code below for now) and save
(Shortcut: Ctrl+S) with .py file extension like: hello.py or your-first-
program.py

print("Hello, World!")
7. Go to Run > Run module (Shortcut: F5) and you can see the output.
Congratulations, you've successfully run your first Python program.

PYTHON HAS TWO BASIC MODES:

Interactive mode: is a command line shell which gives immediate output for
each statement, while running previously statements in active memory.
This mode is also referred as REPL (Read Evaluate Print Loop)

We can start an interactive session from Command Prompt Directly.

10
Normal mode: is where the scripted python file (.py) run in the Python
interpreter.

PYTHON PROGRAM TO ADD TWO NUMBERS


# This program adds two numbers
num1 = 1.5
num2 = 6.3
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

ADD TWO NUMBERS PROVIDED BY THE USER


# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# Add two numbers


sum = float(num1) + float(num2)

11
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

We use the built-in function input() to take the input.


input() returns a string, so we convert it into number using the float() function.

Python Quick start

Python is an interpreted programming language, this means that as a developer


you write Python (.py) files in a text editor and then put those files into the
python interpreter to be executed.

The way to run a python file is like this on the command line:

C:\Users\Your Name>python helloworld.py

Where "helloworld.py" is the name of your python file.

Let's write our first Python file, called helloworld.py, which can be done in any
text editor.

helloworld.py

print("Hello, World!")

Simple as that. Save your file. Open your command line, navigate to the directory
where you saved your file, and run:

C:\Users\Your Name>python helloworld.py

The output should read:

12
Hello, World!

Congratulations, you have written and executed your first Python program.

The Python Command Line

To test a short amount of code in python sometimes it is quickest and easiest not
to write the code in a file. This is made possible because Python can be run as a
command line itself.

Type the following on the Windows, Mac or Linux command line:

C:\Users\Your Name>python

From there you can write any python, including our hello world example from
earlier in the tutorial:

C:\Users\YourName>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] onwin 32 Type "help", "copyright", "credits" or "license" for more
information.

>>> print("Hello, World!")

Which will write "Hello, World!" in the command line:

Whenever you are done in the python command line, you can simply type the
following to quit the python command line interface:

exit()

13
Python - GUI Programming (Tkinter)

Python provides various options for developing graphical user interfaces (GUIs).
Most important are listed below.

 Tkinter − Tkinter is the Python interface to the Tk GUI toolkit installed


with Python.
 wxPython − This is an open-source Python interface for wxWindows
 JPython − JPython is a Python port for Java which gives Python scripts
seamless access to Java class libraries on the local machine

Tkinter Programming

Tkinter is the standard GUI library for Python.

Python when combined with Tkinter provides a fast and easy way to create GUI
applications.

Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.

Creating a GUI application using Tkinter, we need to do is perform the following


steps

 Import the tkinter module.


 Create the GUI application main window.
 Add one or more widgets to the GUI application.
 Enter the main event loop to take action against each event triggered by the
user.

14
Tkinter Widgets

tkinter provides various controls, such as buttons, labels and text boxes used in a
GUI application. These controls are commonly called widgets.

widgets in Tkinter.

Sr.No. Operator & Description


1 Button
The Button widget is used to perform some action when clicked.
2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals, polygons
and rectangles, in your application.
3 Checkbutton
The Checkbutton widget is used to display a number of options as
checkboxes. The user can select multiple options at a time.
4 Entry
The Entry widget is used to display a single-line text field for accepting
values from a user.
5 Frame
The Frame widget is used as a container widget to organize other
widgets.
6 Label
The Label widget is used to provide a single-line caption for other
widgets. It can also contain images.
7 Listbox
The Listbox widget is used to provide a list of options to a user.
8 Menubutton

15
The Menubutton widget is used to display menus in your application.
9 Menu
The Menu widget is used to provide various commands to a user. These
commands are contained inside Menubutton.
10 Message
The Message widget is used to display multiline text fields for accepting
values from a user.
11 Radiobutton
The Radiobutton widget is used to display several options as radio
buttons. The user can select only one option at a time.
12 Scale
The Scale widget is used to provide a slider widget.
13 Scrollbar
The Scrollbar widget is used to add scrolling capability to various
widgets, such as list boxes.
14 Text
The Text widget is used to display text in multiple lines.
15 Toplevel
The Toplevel widget is used to provide a separate window container.
16 Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry widget,
which can be used to select from a fixed number of values.
17 PanedWindow
A PanedWindow is a container widget that may contain any number of
panes, arranged horizontally or vertically.
18 LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act
as a spacer or container for complex window layouts.
19 MessageBox

16
This module is used to display message boxes in your applications.

Let us study these widgets in detail −

Standard attributes

Let us look at how some of their common attributes. such as sizes, colors and
fonts are specified.

 Dimensions
 Colors
 Fonts
 Anchors
 Relief styles
 Bitmaps
 Cursors

Geometry Management

All Tkinter widgets have access to specific geometry management methods,


which have the purpose of organizing widgets throughout the parent widget area.

Tkinter contains the following geometry manager classes: pack, grid, and place.

 The pack() Method − organizes widgets in blocks before placing them in


the parent widget.
 The grid() Method − organizes widgets in a table-like structure in the
parent widget.
 The place() Method − organizes widgets by placing them in a specific
position in the parent widget.

17
Why Django?

Django is a Web framework written in Python.

A Web framework is a software that supports the development of dynamic Web


sites, applications, and services.

It provides a set of tools and functionalities that solves many common problems
associated with Web development, such as security features, database access,
sessions, template processing, URL routing, internationalization, localization,
and much more.

Using a Web framework, such as Django, enables us to develop secure and


reliable Web applications very quickly in a standardized way.
The development of Django is supported by the Django Software Foundation,
and it’s sponsored by companies like JetBrains and Instagram.
Who’s Using Django?
It’s good to know who is using Django out there, so to have an idea what you can
do with it. Among the biggest Web sites using Django we
have: Instagram, Disqus, Mozilla, Bitbucket, Last.fm, National Geographic.

Installation
The first thing we need to do is install some programs on our machine so to be
able to start playing with Django. The basic setup consists of installing

 Python

 Virtualenv

 Django

Using virtual environments is not mandatory, but it’s highly recommended.

18
Installing Virtualenv
we are going to use pip, a tool to manage and install Python packages, to
install virtualenv.

In the Command Prompt, execute the command below:

pip install virtualenv

From now on, everything we install, including Django itself, will be installed
inside a Virtual Environment.

mkdir myproject
cd myproject

This folder is the higher level directory that will store all the files and things
related to our Django project, including its virtual environment.

let’s start by creating our very first virtual environment and installing Django.

Inside the myproj folder:

virtualenv myvenv

Our virtual environment is created.


Now before we start using it, we need to activate:

myvenv\Scripts\activate

You will know it worked if you see (venv) in front of the command line, like
this:

19
to deactivate the venv run the command below:

venv\Scripts\deactivate.bat

But let’s keep it activated for the next steps.

Installing Django
Now that we have the venv activated, run the following command to install
Django:

pip install django

20
Starting a New Project
To start a new Django project, run the command below:

django-admin startproject myproject

The command-line utility django-admin is automatically installed with Django.

After we run the command above, it will generate the base folder structure for a
Django project.

Our initial project structure is composed of five files:

o manage.py: a shortcut to use the django-admin command-line utility. It’s


used to run management commands related to our project.

We will use it to run the development server, run tests, create migrations
and much more.

21
o __init__.py: this empty file tells Python that this folder is a Python
package.
o settings.py: this file contains all the project’s configuration.
o urls.py: this file is responsible for mapping the routes and paths in our
project.

For example, if you want to show something in the URL /about/, you
have to map it here first.

o wsgi.py: this file is a simple gateway interface used for deployment.

You don’t have to bother about it. Just let it be for now.

Django comes with a simple web server installed.

It’s very convenient during the development, so we don’t have to install anything
else to run the project locally.

We can test it by executing the command:

python manage.py runserver

For now, you can ignore the migration errors; we will get to that later.

Now open the following URL in a Web browser: http://127.0.0.1:8000 and you
should see the following page:

22
Hit CTRL + BREAK to stop the development server.

Django Apps
In the Django philosophy we have two important concepts:

o app: is a Web application that does something.

An app usually is composed of a set of models (database tables), views,


templates, tests.

o project: is a collection of configurations and apps.

One project can be composed of multiple apps, or a single app.

It’s important to note that you can’t run a Django app without a project. Simple
websites like a blog can be written entirely inside a single app, which could be
named blog or weblog for example.

23
let’s create a simple Web Forum or Discussion Board. To create our first app, go
to the directory where the manage.py file is and executes the following
command:

django-admin startapp boards


Notice that we used the command startapp this time.

So, let’s first explore what each file does:

o migrations/: here Django store some files to keep track of the changes you
create in the models.py file, so to keep the database and
the models.py synchronized.
o admin.py: this is a configuration file for a built-in Django app
called Django Admin.
o apps.py: this is a configuration file of the app itself.
o models.py: here is where we define the entities of our Web application.
The models are translated automatically by Django into database tables.
o tests.py: this file is used to write unit tests for the app.
o views.py: this is the file where we handle the request/response cycle of our
Web application.

24
Now that we created our first app, let’s configure our project to use it.

To do that, open the settings.py and try to find the INSTALLED_APPS variable:

settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

As you can see, Django already come with 6 built-in apps installed. They offer
common functionalities that most Web applications need, like authentication,
sessions, static files management (images, javascripts, css, etc.) and so on.

Hello, World!
Let’s write our first view. We will explore it in great detail in the next tutorial.
But for now, let’s just experiment how it looks like to create a new page with
Django.

Open the views.py file inside the boards app, and add the following code:

views.py

from django.http import HttpResponse

25
def home(request):
return HttpResponse('Hello, World!')
Views are Python functions that receive an HttpRequest object and returns
an HttpResponse object. Receive a request as a parameter and returns
a response as a result. That’s the flow you have to keep in mind!

So, here we defined a simple view called home which simply returns a message
saying Hello, World!.

Now we have to tell Django when to serve this view. It’s done inside
the urls.py file:

urls.py

from django.conf.urls import url


from django.contrib import admin

from boards import views

urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^admin/', admin.site.urls),
]
If you compare the snippet above with your urls.py file, you will notice I added
the following new line: url(r'^$', views.home, name='home') and
imported the views module from our app boards using from boards
import views.

As I mentioned before, we will explore those concepts in great detail later on.

26
But for now, Django works with regex to match the requested URL. For
our home view, I’m using the ^$ regex, which will match an empty path, which
is the homepage (this url: http://127.0.0.1:8000). If I wanted to match the
URL http://127.0.0.1:8000/homepage/, my url would be:

url(r'^homepage/$', views.home, name='home').

Let’s see what happen:

python manage.py runserver

In a Web browser, open the http://127.0.0.1:8000 URL:

27

You might also like