17
Python Programming - Learn & Practice Additional Resources can be downloaded from: www.questlearning.in/bookpython1.html

Book Preview - Learn and Practice

Embed Size (px)

Citation preview

Page 1: Book Preview - Learn and Practice

Python Programming - Learn & Practice

Additional Resources can be downloaded from: www.questlearning.in/bookpython1.html

Page 2: Book Preview - Learn and Practice

New to Python? If you are indeed a beginner programmer,

this book is for you!

Python is an Internet and systems programming language that is soaring in

popularity in today's fast-paced software development environment, and no

wonder: it's simple (yet robust), object-oriented (yet can be used as a

procedural language), extensible, scalable and features an easy to learn syntax

that is clear and concise. The book covers the core Python programming and

teaches the concept using sample programs. Book covers lot of programming

examples to practice and learn. Learn the core features of Python as well as

advanced topics such as regular expressions, multithreaded programming,

Web/Internet and network development, GUI development with Tk(inter) and

more.

Happy Coding in Python

Series: The Statistical Programming Language Series

Author: Swapnil Saurav

Price: ₹ 350

ISBN: 978-81-931739-6-1

Additional Resources can be downloaded from:

http://questlearning.in/bookpython1.html

Email ID: [email protected] (send us any feedback/comments)

Online shop: www.ekapress.org

Page 3: Book Preview - Learn and Practice

About the Author

Swapnil Saurav

Swapnil Saurav has more than 13 years of work

experience in IT industry with focus on Supply Chain

Analytics. He is an ambitious, creative and highly

motivated individual, who has a passion for the

Supply Chain with focus on Retail and Manufacturing industries and an

uncompromising commitment to quality and outstanding customer service. He

has been invited to be the key note speaker at various industry forums and has a

passion for teaching & developing leaders for tomorrow. His expertise lies in

figuring out ways to do what others say can't be done. He holds MBA from S.P.

Jain Institute of Management & Research, M.S. (BITS, Pilani) and B.E.

(Visvesvaraya Technological University).

Website: www.swapnil.asia

Linked In profile: https://in.linkedin.com/in/swapnilsaurav

Page 4: Book Preview - Learn and Practice

Foreword

Dr Akhilesh KumarStarting it roots in ABC, Python has come a long

way. Python is becoming more and more popular

among programmers and non-programmers

because it is absolute fun and highly productive. I

got a chance to read this book "Python

Programming - Learn & Practice" by Swapnil Saurav. In my views, the best way to

learn a new programming language is to practice, and Swapnil has done a

wonderful job by providing many examples on each topic. Thus, I would

recommend this book to new programmers, who can learn as they go along.

Python is a computer programming language that lets you work more quickly

than other programming languages. Experienced programmers in any other

language can pick up Python very quickly, and beginners find the clean syntax and

indentation structure easy to learn. This book will help the beginners to pick up

the concepts quickly and also the programming experts to get introduced to

Python.

-- - Assistant Professor, Dept. of Industrial and Systems Engineering Indian Institute of Technology, Kharagpur

Page 5: Book Preview - Learn and Practice

Python Programming: Learn and Practice

1 | P a g e

TABLE OF CONTENTS

UNIT 1: GETTING STARTED WITH PYTHON PROGRAMMING ..................... 4

Getting Started .............................................................................................................. 4

Features of Python ........................................................................................................ 4

Getting Started with Python Programming ................................................................... 9

UNIT 2: BASIC PROGRAMMING WITH PYTHON .......................................... 14

Adding comments to your programs .......................................................................... 14

Constants in Python .................................................................................................... 14

Print Statement ........................................................................................................... 15

ESCAPE Sequences ...................................................................................................... 16

Variables in python ..................................................................................................... 16

Unit 3: ADVANCED PROGRAMMING CONCEPTS ........................................ 18

Operators & Expressions ............................................................................................. 18

Control Flow ................................................................................................................ 20

Functions ..................................................................................................................... 23

Recursive Functions ..................................................................................................... 27

Modules ....................................................................................................................... 29

Packages ...................................................................................................................... 31

Decorators ................................................................................................................... 32

WORKING WITH DATE AND TIME ............................................................................... 37

UNIT 4: OBJECT ORIENTED PROGRAMMING IN PYTHON ......................... 40

Class & objects in Python ............................................................................................ 40

Inheritance & polymorphism ...................................................................................... 44

Abstract Classes ........................................................................................................... 48

More about Strings ...................................................................................................... 51

UNIT 5: DATA STRUCTURES .......................................................................... 53

LIST .............................................................................................................................. 53

TUPLE........................................................................................................................... 54

DICTIONARY ................................................................................................................. 55

SEQUENCE ................................................................................................................... 56

SET ............................................................................................................................... 57

Page 6: Book Preview - Learn and Practice

Python Programming: Learn and Practice

2 | P a g e

REFERENCES ................................................................................................................ 57

UNIT 6: INPUT AND OUTPUT .......................................................................... 59

User Input .................................................................................................................... 59

Files.............................................................................................................................. 59

Pickle ........................................................................................................................... 61

UNIT 7: EXCEPTIONS & ASSERTIONS .......................................................... 62

Exception Handling ...................................................................................................... 62

Assertions .................................................................................................................... 64

UNIT 8: REGULAR EXPRESSIONS ................................................................. 66

The Match() Function .................................................................................................. 66

The Search() Function ................................................................................................. 66

UNIT 9: CGI PROGRAMMING .......................................................................... 68

GET and POST Methods............................................................................................... 69

Passing Checkbox Data to CGI Program ...................................................................... 70

Cookies ........................................................................................................................ 71

UNIT 10: DATABASE ACCESS ....................................................................... 72

Database Connection .................................................................................................. 72

Creating Database Table ............................................................................................. 73

Insert Operation .......................................................................................................... 73

Read Operation ........................................................................................................... 74

Update & Delete Operations ....................................................................................... 75

UNIT 11: NETWORK PROGRAMMING ........................................................... 76

Socket Programming ................................................................................................... 76

Sending Emails............................................................................................................. 77

UNIT 12: MULTI THREADING PROGRAMMING ............................................ 79

The Threading module ................................................................................................ 80

Synchronizing Threads ................................................................................................ 81

Multithreaded Priority Queue ..................................................................................... 82

UNIT 13: XML PROCESSING ........................................................................... 83

XML Parser Architectures and APIs ............................................................................. 83

Parsing XML with SAX APIs .......................................................................................... 84

Parsing XML with DOM APIs ........................................................................................ 86

Page 7: Book Preview - Learn and Practice

Python Programming: Learn and Practice

3 | P a g e

UNIT 14: GUI PROGRAMMING ........................................................................ 88

Tkinter Programming .................................................................................................. 88

UNIT 15: DATA VISUALIZATION IN PYTHON ................................................ 97

UNIT 16: PRACTICE PROGRAMS IN PYTHON ............................................ 103

Basic Python Exercises............................................................................................... 103

Data Types Programs................................................................................................. 105

Conditional statements and loops Programs ............................................................ 109

Functions Programs ................................................................................................... 113

Search and Sorting Programs .................................................................................... 113

Recursion Programs .................................................................................................. 116

Date Time Programs .................................................................................................. 119

Class Programs .......................................................................................................... 119

File Input Output Programs ....................................................................................... 120

Regular Expression Programs .................................................................................... 121

Page 8: Book Preview - Learn and Practice

Python Programming: Learn and Practice

4 | P a g e

UNIT 1: GETTING STARTED WITH PYTHON PROGRAMMING

GETTING STARTED

This book serves as a guide or tutorial to the Python programming language. It is mainly targeted at newbies. It is useful for experienced programmers as well. Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

Python is an example of a FLOSS (Free/Libré and Open Source Software). In simple terms, you can freely distribute copies of this software, read its source code, make changes to it, and use pieces of it in new free programs. FLOSS is based on the concept of a community which shares knowledge. This is one of the reasons why Python is so good - it has been created and is constantly improved by a community who just want to see a better Python.

FEATURES OF PYTHON

Simple: Python is a simple and minimalistic language. This pseudo-code nature of Python is one of its greatest strengths. It allows you to concentrate on the solution to the problem rather than the language itself.

Easy to Learn: Python has an extraordinarily simple syntax.

Free and Open Source: Python is an example of a FLOSS (Free/Libré and Open Source Software).

High-level Language: You dont have to worry about machine understands the syntaxes. Portable: Due to its open-source nature, Python has been ported to (i.e. changed to make it work on) many platforms. All your Python programs can work on any of these platforms without requiring any changes at all if you are careful enough to avoid any system-dependent features. You can use Python on GNU/Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and PocketPC!

Interpreted: A program written in a compiled language like C or C[]+ is converted from the source language i.e. C or C+ into a language that is spoken by your computer (binary code i.e. 0s and 1s) using a compiler with various flags and options. When you run the program, the linker/loader software copies the program from hard disk to memory and starts running it. Python, on the other hand, does not need compilation to binary. You just run the program directly from the source code. Internally, Python converts the source code into an intermediate form called bytecodes and then translates this into the native language of your computer and then runs it. All this, actually, makes using Python much easier since you don’t have to worry about compiling the program, making sure that the proper libraries are linked

Page 9: Book Preview - Learn and Practice

Python Programming: Learn and Practice

5 | P a g e

and loaded, etc. This also makes your Python programs much more portable, since you can just copy your Python program onto another computer and it just works!

Object Oriented: Python supports procedure-oriented programming as well as object-oriented programming. Python has a very powerful but simplistic way of doing OOP, especially when compared to big languages like C++ or Java.

Embeddable: You can embed Python within your C/C\++ programs to give scripting capabilities for your program’s users.

Extensive Libraries: The Python Standard Library is huge indeed. It can help you do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, FTP, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interfaces), and other system-dependent stuff. Remember, all this is always available wherever Python is installed. This is called the Batteries Included philosophy of Python.

Python 2 versus Python 3 Python comes in two flavors - Python 2.X and Python 3.X. Many beginning Python users are wondering with which version of Python they should start. I would suggest you to just go with the version your favorite tutorial was written in, and check out the differences later on. But if you are new to Python, my suggestion is to go with Python 3.X because that will be supported for future programing and Python 2.X development has been stopped.

Note: In this book, we will use Python 3 as our programming language.

Installing on Windows Visit https://www.python.org/downloads/ and download the latest version. The installation is just like any other Windows-based software. By default, it will create a folder in C drive as shown in the figure on right.

Double click on the python.exe file to launch python at Windows command line which would appear as below:

We have used Windows version for the examples given in this book. Once you have started Python, you should see >>> where you can start typing stuff. This is called the Python interpreter prompt.

Page 10: Book Preview - Learn and Practice

Python Programming: Learn and Practice

6 | P a g e

Installation on Mac OS X For Mac OS X users, Python must be installed already. To verify, open the terminal by pressing Command+Space keys (to open Spotlight search), type Terminal and press enter key. Now, run python and ensure there are no errors.

Installation on GNU/Linux For GNU/Linux users, Python must be installed already. To verify, open the terminal by opening the Terminal application or by pressing Alt+F2 and entering gnome-terminal. If that doesn’t work, please refer the documentation of your particular GNU/Linux distribution.

How to Quit the Interpreter Prompt If you are using a GNU/Linux or OS X shell, you can exit the interpreter prompt by pressing ctrl+d or entering exit(). If you are using the Windows command prompt, press ctrl+z followed by the enter key.

Python Editor We have seen how to run Python command prompt but it is a bad choice because it does not do syntax highlighting and also importantly it does not support indentation of the text which is very important in our case as we will see later. Good editors will automatically do this for us. I use PyCharm (from PyCharm Educational Edition) which is a free editor for writing Python programs. Download and Install PyCharm from JetBrains.com website. When you open PyCharm, click on Create New Project and then select Pure Python. Change Untitle to a filename. Please refer PyCharm tutorial for detailed: https://www.jetbrains.com/help/pycharm/2016.3/quick-start-guide.html

1. Click the Create button.2. Right-click on the helloworld in the sidebar and select New → Python File:3. You will be asked to type the name, type hello.4. You can now see a file opened for you

Page 11: Book Preview - Learn and Practice

Python Programming: Learn and Practice

7 | P a g e

Page 12: Book Preview - Learn and Practice

Python Programming: Learn and Practice

8 | P a g e

Let’s create our first Python Program

1. Using PyCharm editor

Output:

2. Using a source file (Windows Command Line)

a. Create a folder where you want to save all your Python programs (I have created a folder at: c:\MyPythonPrograms)

b. Create a file by name hello.py at this folder. Open with Notepad and type your program as show below:

c. Navigate to where your python file is, using the commands 'cd' (change directory) and

'dir' (to show files in the directory, to verify your head). For our example something like,

> cd C:\MyPythonPrograms try: > python hello.py If you get this message:

Page 13: Book Preview - Learn and Practice

Python Programming: Learn and Practice

9 | P a g e

then python (the interpreter program that can translate Python into 'computer instructions') isn't on your path (see Putting Python in Your Path below). Then try calling it like this (assuming Python2.7, installed in the usual location):

> C:\Python35\python.exe hello.py (Advanced users: instead of hello.py, you could write out first.py's full path of

C:\MyPythonPrograms\hello.py)

Putting Python In Your Path (Windows OS) In order to run programs, your operating system looks in various places, and tries to

match the name of the program / command you typed with some programs along the way.

In windows: control panel > system > advanced > |Environmental Variables| > system variables ->

Path

this needs to include: C:\Python35; (or equivalent). If you put it at the front, it will be the first place looked. You can also add it at the end, which is possibly saner. Then restart your prompt, and try typing 'python'. If it all worked, you should get a ">>>" prompt.

3. Running the Python program on Command prompt

You can also run your program at the command prompt:

The >>> is Python's way of telling you that you are in interactive mode. In interactive mode

what you type is immediately run. Try typing 1+1 in. Python will respond with 2. Interactive

mode allows you to test out and see what Python will do. If you ever feel you need to play

with new Python statements, go into interactive mode and try them out.

Getting Help

If you need quick information about any function or statement in Python, then you can use

the built-in help functionality. This is very useful especially when using the interpreter

prompt. For example, run help('len') - this displays the help for the len function which is used

to count number of items.

GETTING STARTED WITH PYTHON PROGRAMMING

Page 14: Book Preview - Learn and Practice

Python Programming: Learn and Practice

10 | P a g e

As we go through this tutorial, I will attempt to teach you how to program. There

really is only one way to learn to program. You must read code and write code (as

computer programs are often called). I'm going to show you lots of code. You

should type in code that I show you to see what happens. Play around with it and

make changes. The worst that can happen is that it won't work. SO Dont Be Afraid

to Code !!! ##Python is easy to learn

print ("Hello, World!")

>>> Hello, World!

Creating and Running Programs

Go into IDLE if you are not already. In the menu at the top, select File then New Window. In

the new window that appears, type the following :

print ("Hello, World!")

Now save the program: select File from the menu, then Save. Save it as "hello.py" (you can

save it in any folder you want). Now that it is saved it can be run. Next run the program by

going to Run then Run Module.

It is very useful to stick to some rules regarding the file names of Python programs. Otherwise

some things might go wrong unexpectedly. These don't matter as much for programs, but you

can have weird problems if you don't follow them for module names (modules will be

discussed later).

4. Always save the program with the extension .py. Do not put another dot somewhere

else in the file name.

5. Only use standard characters for file names: letters, numbers, dash (-) and

underscore (_).

6. White space ("") should not be used at all (use e.g. underscores instead).

7. Do not use anything other than a letter (particularly no numbers!) at the beginning of

a file name.

8. Do not use "non-english" characters (such as ä, ö, ü, å or ß) in your file names—or,

even better, do not use them at all when programming.

Python documentation

First of all, Python is very well documented. There might even be copies of these documents

on your computer, which came with your Python installation: The official Python Tutorial8 by

Guido van Rossum is often a good starting point for general questions.

For questions about standard modules (you will learn what this is later), the Python

Library Reference9 is the place to look.

If you really want to get to know something about the details of the language, the

Python Reference Manual10 is comprehensive but quite complex for beginners.

Page 15: Book Preview - Learn and Practice

Python Programming: Learn and Practice

11 | P a g e

Now here is a more complicated program :

print ("Jack and Jill went up a hill", end="")

print ("to fetch a pail of water;")

print ("Jack fell down, and broke his crown,", end="")

print ("and Jill came tumbling after.")

Output :

Jack and Jill went up a hillto fetch a pail of water;

Jack fell down, and broke his crown,and Jill came tumbling after.

Terminology

Now is probably a good time to give you a bit of an explanation of what is happening - and a

little bit of programming terminology. What we were doing above was using a command

called print. The print command is followed by one or more arguments. So in this example

print "Hello, World!"

there is one argument, which is "Hello, World!". Note that this argument is a group of

characters enclosed in double quotes ("). This is commonly referred to as a string of

characters, or string, for short. Another example of a string is "Jack and Jill went up a hill".

A command and its arguments are collectively referred to as a statement, so print "Hello,

World!" is an example of a statement.

Expressions

Here is another program :

print ("2 + 2 is", 2 + 2)

print ("3 * 4 is", 3 * 4)

print ("100 - 1 is", 100 - 1)

print ("(33 + 2) / 5 + 11.5 is", (33 + 2) / 5 + 11.5)

Output :

2 + 2 is 4

3 * 4 is 12

100 - 1 is 99

(33 + 2) / 5 + 11.5 is 18.5

So with the first line of the program

print "2 + 2 is", 2 + 2

The first argument is the string "2 + 2 is" and the second argument is the mathematical

expression 2 + 2, which is commonly referred to as an expression.

What is important to note is that a string is printed as is (the string is what is within the

double quotes but doesn't include the double quotes themselves. So the string is printed

Page 16: Book Preview - Learn and Practice

Python Programming: Learn and Practice

12 | P a g e

without the enclosing double quotes.) But an expression is evaluated, (in other words,

converted) to its actual value.

Python has six basic operations for numbers :

Try below program and check the output : print ("14 / 3 = ", 14 / 3)

print ("14 % 3 = ", 14 % 3)

print ()

print ("14.0 / 3.0 =", 14.0 / 3.0)

print ("14.0 % 3.0 =", 14.0 % 3.0)

print ()

print ("14.0 / 3 =", 14.0 / 3)

print ("14.0 % 3 =", 14.0 % 3)

print ()

print ("14 / 3.0 =", 14 / 3.0)

print ("14 % 3.0 =", 14 % 3.0)

print ()

TALKING TO HUMANS (COMMENTS)

Often in programming you are doing something complicated and may not in the future

remember what you did. When this happens, the program should probably be commented. A

comment is a note to you and other programmers explaining what is happening. For example

: # This is a comment

print("Comment example")

# This is another comment

More examples # This is not quite true outside of USA

# and is based on my dim memories of my younger years

print ("First Grade")

print ("1 + 1 =", 1 + 1)

print ("2 + 4 =", 2 + 4)

print ("5 - 2 =", 5 - 2)

print()

print ("Third Grade")

print ("243 - 23 =", 243 - 23)

print ("12 * 4 =", 12 * 4)

Page 17: Book Preview - Learn and Practice

Python Programming: Learn and Practice

13 | P a g e

print ("12 / 3 =", 12 / 3)

print ("13 / 3 =", 13 / 3, "R", 13 % 3)

print()

print ("Junior High")

print ("123.56 - 62.12 =", 123.56 - 62.12)

print ("(4 + 3) * 2 =", (4 + 3) * 2)

print ("4 + 3 * 2 =", 4 + 3 * 2)

print ("3 ** 2 =", 3 ** 2)

print()

Practice

1. Write a program that prints your full name and your birthday as separate strings.

2. Write a program that shows the use of all 6 math functions.

User Input a=input("What's your name: ")

print("My name is "+a)

This is an example of input. The program reaches a certain point and then waits for the user

to input some data that the program can use later.

Now that we are comfortable with Python programming, lets get deeper into Python

programming.