Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Introduction To Python

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 53

1

INTRODUCTION TO PYTHON
Instructor: Vincent Richards
Office: CIS Dept.
Office hrs.: MW(9:30-10:50, 5:00-6:20), TUTH (9:30-10:50, 5:00-6:20) by appt
E-mail: vincent.richards@ncu.edu.jm
Tel#: 963-7285
Website: http://lms.ncu.edu.jm
2

What is Python?
• Python is a general-purpose interpreted, interactive,
object-oriented, and high-level programming
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).
3

Why Learn Python?


• Python is a high-level, interpreted, interactive and
object-oriented scripting language. Python is
designed to be highly readable. It uses English
keywords frequently where as other languages use
punctuation, and it has fewer syntactical
constructions than other languages.
4

Why Learn Python?


• Python is a MUST for students and working
professionals to become a great Software Engineer
specially when they are working in Web
Development Domain. Some of the key
advantages of learning Python:
• Python is Interpreted − Python is processed at
runtime by the interpreter. You do not need to
compile your program before executing it. This is
similar to PERL and PHP.
5

Why Learn Python?


• Python is Interactive − You can actually sit at a
Python prompt and interact with the interpreter
directly to write your programs.
• Python is Object-Oriented − Python supports
Object-Oriented style or technique of programming
that encapsulates code within objects.
6

Why Learn Python?


• Python is a Beginner's Language − Python is a
great language for the beginner-level programmers
and supports the development of a wide range of
applications from simple text processing to WWW
browsers to games.
7

Characteristics of Python
The Following are important characteristics
of Python Programming −
•It supports functional and structured programming
methods as well as OOP.

•It can be used as a scripting language or can be


compiled to byte-code for building large applications.
8

Characteristics of Python
• It provides very high-level dynamic data types and
supports dynamic type checking.

• It supports automatic garbage collection.

• It can be easily integrated with C, C++, COM,


ActiveX, CORBA, and Java.
9

Applications of Python
As mentioned before, Python is one of the most
widely used language over the web. A few of them
are:
•Easy-to-learn − Python has few keywords, simple
structure, and a clearly defined syntax. This allows
the student to pick up the language quickly.
•Easy-to-read − Python code is more clearly defined
and visible to the eyes.
•Easy-to-maintain − Python's source code is fairly
easy-to-maintain.
10

• A broad standard library − Python's bulk of the


library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an
interactive mode which allows interactive testing and
debugging of snippets of code.
• Portable − Python can run on a wide variety of
hardware platforms and has the same interface on
all platforms.
11

• Extendable − You can add low-level modules to the


Python interpreter. These modules enable
programmers to add to or customize their tools to be
more efficient.

• Databases − Python provides interfaces to all major


commercial databases.
12

• GUI Programming − Python supports GUI


applications that can be created and ported to many
system calls, libraries and windows systems, such
as Windows MFC, Macintosh, and the X Window
system of Unix.

• Scalable − Python provides a better structure and


support for large programs than shell scripting.
13

Audience
• This Python tutorial is designed for software
programmers who need to learn Python
programming language from scratch.

• Prerequisites

• You should have a basic understanding of Computer


Programming terminologies. A basic understanding
of any of the programming languages is a plus.
14

Python - Environment Setup


• Python is available on a wide variety of platforms
including Linux, Windows and Mac OS X. Let's
understand how to set up our Python environment.
• Local Environment Setup
• Open a terminal window and type "python" to find
out if it is already installed and which version is
installed.
• Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS,
IRIX, etc.)
• Win 9x/NT/2000
15

• Macintosh (Intel, PPC, • Amiga


68K) • VMS/OpenVMS
• OS/2
• QNX
• DOS (multiple versions)
• VxWorks
• PalmOS
• Psion
• Nokia mobile phones
• Python has also been
• Windows CE ported to the Java
• Acorn/RISC OS and .NET virtual
• BeOS machines
16

Getting Python
• The most up-to-date and current source code,
binaries, documentation, news, etc., is available on
the official website of Python 
https://www.python.org/
• You can download Python documentation from 
https://www.python.org/doc/. The documentation is
available in HTML, PDF, and PostScript formats.
17

Installing Python
• Python distribution is available for a wide variety of
platforms. You need to download only the binary
code applicable for your platform and install Python.
• If the binary code for your platform is not available,
you need a C compiler to compile the source code
manually. Compiling the source code offers more
flexibility in terms of choice of features that you
require in your installation.
18

Unix and Linux Installation


Here are the simple steps to install Python on Unix/Linux machine.
• Open a Web browser and go • Editing the Modules/Setup file if
to  you want to customize some
https://www.python.org/downl options.
oads/ • run ./configure script
. • make
• Follow the link to download
• make install
zipped source code
available for Unix/Linux.
• Download and extract files.

This installs Python at standard location /usr/local/bin and its libraries


at /usr/local/lib/pythonXX where XX is the version of Python.
19

Windows Installation
• Here are the steps to install Python on Windows
machine.
• Open a Web browser and go to 
https://www.python.org/downloads/.
• Follow the link for the Windows installer python-
XYZ.msi file where XYZ is the version you need to
install.
20

Windows Installation
• To use this installer python-XYZ.msi, the Windows
system must support Microsoft Installer 2.0. Save
the installer file to your local machine and then run it
to find out if your machine supports MSI.
• Run the downloaded file. This brings up the Python
install wizard, which is really easy to use. Just
accept the default settings, wait until the install is
finished, and you are done.
21

Macintosh Installation
• Recent Macs come with Python installed, but it may
be several years out of date. See 
http://www.python.org/download/mac/ for
instructions on getting the current version along with
extra tools to support development on the Mac. For
older Mac OS's before Mac OS X 10.3 (released in
2003), MacPython is available.
• Jack Jansen maintains it and you can have full
access to the entire documentation at his website − 
http://www.cwi.nl/~jack/macpython.html. You can
find complete installation details for Mac OS
installation.
22

Setting up PATH
• Programs and other executable files can be in many
directories, so operating systems provide a search
path that lists the directories that the OS searches
for executables.
• The path is stored in an environment variable, which
is a named string maintained by the operating
system. This variable contains information available
to the command shell and other programs.
23

Setting up PATH
• The path variable is named as PATH in Unix or Path
in Windows (Unix is case sensitive; Windows is not).
• In Mac OS, the installer handles the path details. To
invoke the Python interpreter from any particular
directory, you must add the Python directory to your
path.
24

Setting path at Unix/Linux


To add the Python directory to the path for a particular
session in Unix −
• In the csh shell − type setenv PATH
"$PATH:/usr/local/bin/python" and press Enter.
• In the bash shell (Linux) − type export
PATH="$PATH:/usr/local/bin/python" and press Enter.
• In the sh or ksh shell − type
PATH="$PATH:/usr/local/bin/python" and press Enter.
• Note − /usr/local/bin/python is the path of the Python
directory
• here https://www.tutorialspoint.com/python/python_environment.htm
25

Setting path at Windows


To add the Python directory to the path for a particular
session in Windows −
•At the command prompt − type path %path%;C:\Python and
press Enter.
•Note − C:\Python is the path of the Python directory
•here https://www.tutorialspoint.com/python/python_environment.htm
26

Setting path at Windows


On Windows 7
• Select “Computer” from the Start menu
• Choose “System Properties” from the menu
• Click “Advanced system settings” (it’s on the left) then click
the “Advanced” tab
• Click on “Environment Variables”, under “System Variables”,
find “Path”, and click on it.
• Click “Edit…”, and add the text on the following line to the
end of the Path in the box “Variable value”. Note that there
should be no spaces anywhere at all:
• ;C:\Python27
• then click “OK” and you’re done.
Ref: https://gist.github.com/roblanf/6929493
27

Running Python
There are three different ways to start Python −
• Interactive Interpreter
• You can start Python from Unix, DOS, or any other system
that provides you a command-line interpreter or shell window.
• Enter python the command line.
• Start coding right away in the interactive interpreter.
• $python # Unix/Linux
or
• python% # Unix/Linux
or
• C:> python # Windows/DOS
28

Script from the Command-line


• $python script.py # Unix/Linux
or
• python% script.py # Unix/Linux
or
• C: >python script.py # Windows/DOS

Note − Be sure the file permission mode allows execution.


29

Integrated Development Environment


• You can run Python from a Graphical User Interface (GUI)
environment as well, if you have a GUI application on your
system that supports Python.
• Unix − IDLE is the very first Unix IDE for Python.
• Windows − PythonWin is the first Windows interface for
Python and is an IDE with a GUI.
• Macintosh − The Macintosh version of Python along with the
IDLE IDE is available from the main website, downloadable
as either MacBinary or BinHex'd files.
30

Integrated Development Environment


• You can run Python from a Graphical User Interface (GUI)
environment as well, if you have a GUI application on your
system that supports Python.
• Unix − IDLE is the very first Unix IDE for Python.
• Windows − PythonWin is the first Windows interface for
Python and is an IDE with a GUI.
• Macintosh − The Macintosh version of Python along with the
IDLE IDE is available from the main website, downloadable
as either MacBinary or BinHex'd files.
31

Integrated Development Environment


• Make sure the Python environment is properly set up and
working perfectly fine.
• Note − All the examples given in subsequent chapters are
executed with Python 2.4.3 version available on CentOS
flavor of Linux.
• There are Python Programming environments online, so that
you can execute your programs online also.
32

First Python Program


• Make sure the Python environment is properly set up and
working perfectly fine.
• Note − All the examples given in subsequent chapters are
executed with Python 2.4.3 version available on CentOS
flavor of Linux.
• There are Python Programming environments online, so that
you can execute your programs online also.
33

First Python Program


• Make sure the Python environment is properly set up and
working perfectly fine.
• Note − All the examples given in subsequent chapters are
executed with Python 2.4.3 version available on CentOS
flavor of Linux.
• There are Python Programming environments online, so that
you can execute your programs online also.
34

• Execute programs in different modes of programming.


• Interactive Mode Programming
• Invoking the interpreter without passing a script file as a
parameter brings up the following prompt −
• $ python Python 2.4.3 (#1, Nov 11 2010, 13:34:43) [GCC
4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2 Type "help",
"copyright", "credits" or "license" for more information. >>>
• Type the following text at the Python prompt and press the
Enter −
>>> print "Hello, Python!“
• If you are running new version of Python, then you would
need to use print statement with parenthesis as in print
("Hello, Python!");. However in Python version 2.4.3, this
produces the following result −
Hello, Python!
35

Script Mode Programming


• Invoking the interpreter with a script parameter begins
execution of the script and continues until the script is
finished. When the script is finished, the interpreter is no
longer active.
• Let us write a simple Python program in a script. Python files
have extension .py. Type the following source code in a
test.py file −
• print "Hello, Python!“
• Assuming that you have Python interpreter set in PATH
variable.
36

Script Mode Programming


• Now, try to run this program as follows −
• $ python test.pyThis produces the following result −
Hello, Python!
Let us try another way to execute a Python script. Here is the
modified test.py file −
#!/usr/bin/python
print "Hello, Python!“
• We assume that you have Python interpreter available in
/usr/bin directory. Now, try to run this program as follows −
$ chmod +x test.py # This is to make file executable
$./test.pyThis produces the following result −
• Hello, Python!
37

Python Identifiers
• A Python identifier is a name used to identify a variable,
function, class, module or other object. An identifier starts
with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
• Python does not allow punctuation characters such as @, $,
and % within identifiers. Python is a case sensitive
programming language.
Thus, Manpower and manpower are two different identifiers
in Python.
38

Python Identifiers
Here are naming conventions for Python identifiers −
• Class names start with an uppercase letter. All other
identifiers start with a lowercase letter.
• Starting an identifier with a single leading underscore
indicates that the identifier is private.
• Starting an identifier with two leading underscores indicates a
strongly private identifier.
• If the identifier also ends with two trailing underscores, the
identifier is a language-defined special name.
39

Reserved Words
The following list shows the Python keywords. These are
reserved words and you cannot use them as constant or
variable or any other identifier names. All the Python
keywords contain lowercase letters only.
40

Reserved Words
41

Lines and Indentation


• Python provides no braces to indicate blocks of code for
class and function definitions or flow control. Blocks of code
are denoted by line indentation, which is rigidly enforced.
• The number of spaces in the indentation is variable, but all
statements within the block must be indented the same
amount.
42

For example −
if True:
print "True"
else:
print "False"
However, the following block generates an error −
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Therefore, in Python all the continuous lines indented with
same number of spaces would form a block.
43

Lines and Indentation


• Multi-Line Statements
Statements in Python typically end with a new line. Python
does, however, allow the use of the line continuation
character (\) to denote that the line should continue. For
example −
total = item_one + \
item_two + \
item_three
44

Quotation in Python
• Python accepts single ('), double (") and triple (''' or """)
quotes to denote string literals, as long as the same type of
quote starts and ends the string.
• The triple quotes are used to span the string across multiple
lines. For example, all the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
45

Comments in Python
• A hash sign (#) that is not inside a string literal begins a
comment. All characters after the # and up to the end of the
physical line are part of the comment and the Python
interpreter ignores them.
• #!/usr/bin/python

• # First comment
• print "Hello, Python!" # second comment
46

Comments in Python
• A hash sign (#) that is not inside a string literal begins a
comment. All characters after the # and up to the end of the
physical line are part of the comment and the Python
interpreter ignores them.
• #!/usr/bin/python

• # First comment
• print "Hello, Python!" # second comment

This produces the following result −


Hello, Python!
47

Comments in Python
• You can type a comment on the same line after a statement
or expression −

• name = "Madisetti" # This is again comment


• You can comment multiple lines as follows −

• # This is a comment.
• # This is a comment, too.
• # This is a comment, too.
• # I said that already.
48

Comments in Python
• You can type a comment on the same line after a statement
or expression −
• Following triple-quoted string is also ignored by Python
interpreter and can be used as a multiline comments:
'''
This is a multiline
comment.
'''
49

Using Blank Lines


• A line containing only whitespace, possibly with a comment,
is known as a blank line and Python totally ignores it.
• In an interactive interpreter session, you must enter an empty
physical line to terminate a multiline statement.
50

Waiting for the User


• The following line of the program displays the prompt, the
statement saying “Press the enter key to exit”, and waits for
the user to take action −
• #!/usr/bin/python
• raw_input("\n\nPress the enter key to exit.")

• Here, "\n\n" is used to create two new lines before displaying


the actual line.
• Once the user presses the key, the program ends. This is a
nice trick to keep a console window open until the user is
done with an application.
51

Multiple Statements on a Single Line


• The semicolon ( ; ) allows multiple statements on the single
• line given that neither statement starts a new code block.
• Here is a sample snip using the semicolon −

• import sys; x = 'foo'; sys.stdout.write(x + '\n')


52

Multiple Statement Groups as Suites


• A group of individual statements, which make a single code
block are called suites in Python. Compound or complex
statements, such as if, while, def, and class require a header
line and a suite.
• Header lines begin the statement (with the keyword) and
terminate with a colon ( : ) and are followed by one or more
lines which make up the suite. For example −
• if expression :
• suite
• elif expression :
• suite
• else :
• suite
53

Command Line Arguments


• $ python -h
• usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
• Options and arguments (and corresponding environment
variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]
You can also program your script in such a way that it should
accept various options. 

You might also like