0% found this document useful (0 votes)
45 views115 pages

Python 1st Yr Training

The document is a training report submitted by Vritika Chaudhary for a one-month training at Infosys Technologies Private Limited, conducted from July 4 to July 31, 2023, as part of her B.Tech degree in Electronics and Communication Engineering. It includes an overview of Python programming, its features, and the training work undertaken, alongside acknowledgments and information about Infosys. The report also outlines the structure of the training, covering various programming fundamentals and practical applications in Python.

Uploaded by

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

Python 1st Yr Training

The document is a training report submitted by Vritika Chaudhary for a one-month training at Infosys Technologies Private Limited, conducted from July 4 to July 31, 2023, as part of her B.Tech degree in Electronics and Communication Engineering. It includes an overview of Python programming, its features, and the training work undertaken, alongside acknowledgments and information about Infosys. The report also outlines the structure of the training, covering various programming fundamentals and practical applications in Python.

Uploaded by

Vritika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

A REPORT OF ONE MONTH TRAINING

At

INFOSYS TECHONOLOGIES PRIVATE LIMITED

SUBMITTED IN PARTIAL FULFILLMENT OF THE REQUIREMENT FOR THE

AWARD OF THE DEGREE OF

BACHELOR OF TECHONOLOGY

(Electronics and Communication Engineering)

July 4, 2023 to July 31,2023

SUBMITTED BY:

Name: Vritika Chaudhary

URN: 2203775

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING

GURU NANAK DEV ENGINNERING COLLLEGE LUDHIANA

(An Autonomous College Under UGC ACT)


GURU NANAK DEV ENGINEERING COLLEGE, LUDHIANA

CANDIDATE'S DECLARATION

I “VRITIKA CHAUDHARY” hereby declare that I have undertaken one month training

“INFOSYS TECHONOLOGIES PRIVATE LIMITED” during a period from July 4,2023

to July 31,2023 in partial fulfillment of requirements for the award of degree of B.Tech

(Electronics and Communication Engineering) at GURU NANAK DEV ENGINEERING

COLLEGE, LUDHIANA. The work which is being presented in the training report submitted

to Department of Electronics and Communication Engineering at GURU NANAK DEV

ENGINEERING COLLEGE, LUDHIANA is an authentic record of training work.

Signature of the Student

The one month industrial training Viva–Voce Examination of_________ has been held on

___________ and accepted.

Signature of Internal Examiner Signature of External Examiner


ABSTRACT

The objective of a practical training is to learn something about industries practically and to

be familiar with a working style of a technical worker to adjust simply according to industrial

environment. This report deals with the equipments their relation and their general operating

principle. Python, an interpreted language which was developed by Guido van Rossum came

into implementation in 1989. The language supports both object oriented and procedure

oriented approach. Python is designed to be a highly extensible language. Python works on

the principle of "there is only one obvious way to do a task" rather than "there is more than

one way to solve a particular problem". Python is very easy to learn and implement. The

simpler syntax, uncomplicated semantics and approach with which Python has been

developed makes it very easier to learn.

A large number of python implementations and extensions have been developed since its

inception. Training Cover provides both six weeks as well as six months industrial training in

Python. Python is divided into two parts as "Core Python" and "Advance Python".

Accordingly all the basic and advanced topics are discussed in both of the modules.
ACKNOWLEDGEMENT

We are highly grateful to the Dr. Sehijpal Singh. Principal. Guru Nanak Dev Engineering

College (GNDEC), Ludhiana, for providing this opportunity to carry out the major project

work at Inventory Management Optimization Using Deep Learning.

The constant guidance and encouragement received from Dr.Narwant Singh Grewal, H.O.D..

ECE Department, GNDEC Ludhiana has been of great help in carrying out the project work

and is acknowledged with reverential thanks.

We express gratitude to other faculty members of Electronics Communication Department of

GNDEC for their intellectual support throughout the course of this work.

Finally, We are indebted to all whosoever have contributed in this report work.

NAME & SIGNATURE OF STUDENT


ABOUT THE INFOSYS

Infosys Limited is an Indian multinational information technology company that provides business

consulting, information technology and outsourcing services. The company was founded in Pune and

is headquartered in Bangalore. Infosys is the second-largest Indian IT company, after Tata

Consultancy Services, by 2020 revenue figures.

On 24 August 2021, Infosys became the fourth Indian company to reach US$100 billion in

market capitalization. It is one of the top Big Tech (India) companies.

HISTORY

Established in 1981, Infosys is a NYSE listed global consulting and IT services company

with more than 336k employees. From a capital of US$250, we have grown to become a US$

18.38 billion company with a market capitalization of approximately US$ 67 billion.

In our journey of over 40 years, we have catalyzed some of the major changes that have led

to India's emergence as the global destination for software services talent. We pioneered the

Global Delivery Model and became the first IT Company from India to be listed on

NASDAQ. Our employee stock options program created some of India's first salaried

millionaires.

Founded : 2 July 1981; 42 years ago Pune, India


Founders : N. R. Narayana Murthy, Nandan Nilekani, Kris Gopalakrishnan, S. D. Shibulal,

K. Dinesh, N. S. Raghavan, Ashok Arora

Headquarters: Bangalore, Karnataka, India

MISSION: To achieve our objectives in an environment of fairness, honesty, and courtesy

towards our clients, employees, vendors and society at large.

VISION: To be a globally respected corporation that provides best-of-breed business

solutions, leveraging technology, delivered by best-in-class people.


CONTENTS

Topic Page
No.
Certificate by Infosys

ii.-vi

Candidate’s Declaration

vii

Abstract viii

Acknowledgement

ix

About the Infosys

x-xi

List of Figures

List of Tables

CHAPTER 1 INTRODUCTION

PROGRAMMING FUNDAMENTALS USING PYTHON PART 1

1.1 Python

1.2 History of Python

1.3 Python Feature

1.4 What is Python?

1.5 The very Basics of Python

1.6 Invoking Python

1.7 Basic Principles of Python

1.7.1 Basic Core Language

1.7.2 Modules
1.7.3 Object Oriented Programming

1.7.4 Namespaces and Variable Scoping

1.7.5 Exception Handling

CHAPTER 2 TRAINING WORK UNDERTAKEN

2.1 Introduction to programming

2.1.1 Why programming and what is program?

2.1.2 The Scenario- Takeoff and landing

2.2 Introduction to algorithm and pseudo code

2.2.1 Algorithm and its representation

2.3 Basic of algorithm and pseudo code

2.3.1 Variables and operations

2.3.2 Decision Constructs

2.3.3 Iteration constructs

2.4 Variables, data types and operators in python

2.4.1 What is programming language?

2.4.2 Data types

2.4.3 Variables

2.4.4 Variables and data types

2.4.5 Operations

2.4.6 Implicit and explicit type conversion

2.5 Coding standards and Formatting output

2.5.1 Coding standards

2.6 Introduction to function

2.6.1 Function in programs


2.7 Selection control structure

2.7.1 Control structure

2.7.2 Selection control structure

2.8 Iteration control structure

2.8.1 Iteration control structure- Syntax

2.8.2 Iteration control structure-‘for’ with ‘range’

2.8.3 Iteration control structure – nested loops

2.8.4 Iteration control structure- ‘break’ and ‘continue’

2.8.5 Iteration control structure- testing loops

2.9 Eclipse plug- in

2.9.1 Introduction to Eclipse plug – in

2.9.2 Tip to handle infinite loop

2.10 Collection and list in python

2.10.1 Introduction to collection

2.10.2 List

2.11 Tuple in python

2.11.1 Tuple

2.12 String in python

2.12.1 String

2.13 Dubugging

2.13.1 Introduction to dubugging

2.13.2 Eclipse debugger

2.14 Dictionary in python

2.14.1 Dictonary

2.15 Set in python


2.15.1 Set

2.16 Libraries and Functions in python

2.16.1 Maths libraries

2.16.2 Data and functions

PROGRAMMING FUNDAMENTALS USING PYTHON PART 2

2.17 Introduction:

2.17.1 Summary of Programming fundamentals using python

2.18 Functions- arguments

2.18.1 Arguments Behavior

2.18.2 Type of Arguments

2.19 Variables and its scope

2.19.1 Types of variables

2.19.2 Variables and its scope

2.20 Using Testing

2.20.1 Code review, unit testing and logic converges

2.20.2 Logic Converges- identify test data

2.20.3 Boundary value analysis

2.21 Exception handling in python

2.21.1 Exception Handling – Different types

2.22 Recursion

2.23 Tower of Hanoi problem

2.24 Module and Packages

2.25 File handling

CHAPTER 3 RESULTS AND DISCUSSION

3.1 Python Programs


3.1.1 Program to check Prime Number in Python Program.

3.1.2 Program to check if a number is Positive, Negative or Zero.

3.1.3 Program to read a Number n and computer n+ nn+ nnn in Python.

3.1.4 Program to read Height in centimeters and then convert the Height

to Feet and inches.

3.1.5 Program to find sum of Natural Numbers.

3.1.6 Program to implement Simple Calculator in Python.

3.1.7 Program to find out how many 1 and 0 in given number.

3.1.8 Program to perform following operation with list:

(a) To get largest number from list.

(b) To search an element in a list.

3.1.9 Program to count the number of times a character appears

in given string.

3.1.10 Program to print all integers that aren’t divisible by

either 2 or 3 and lie between 1 and 50 in Python.

3.1.11 Program in python to remove an element from a list.

3.1.12 Program to Find factorial a number using recursion.

3.1.13 Program to print Multiplication Table using recursion.

3.1.14 Program to add two integers only with Exception Handling

in Python.

3.1.15 Python program to Count the Number of Words in a Text File.

3.2 Projects

3.2.1 Convert PDF to TXT using Python.

3.2.2 How to send automatic Whatsapp Messages in Python.

CHAPTER 4 CONCLUSION AND FUTURE SCOPE


4.1 Conclusion

4.2 Future scope

REFERENCE

LIST OF FIGURES

FIGURE NO. NAME OF FIGURES PAGE


NO.

1. Infosys x

1.1 Python

2.1 The air traffic control

2.2 Takeoff

2.3 Landing

2.4 Flowchart

2.5 Variables

2.6 Dimension of variables

2.7 Precedence of operator

2.8 Code

2.9 Debug

2.10 Function in program

2.11 Control Structure

2.12 While condition

2.13 For loop

2.14 Infinite loop

2.15 Collection
2.16 List

2.17 Memory Location

2.18 List index

2.19 Eclipse debugger

2.20 Open perspective

2.21 Perspective pop-up

2.22 Example of dictionary 1

2.23 Example of dictionary 2

2.24 Example of dictionary 3

2.25 Immutable object

2.26 Mutable object

2.27 Global variables

2.28 Identify test data

2.29 Test data 1

2.30 Test data 2

2.31 Unit testing techniques

2.32 Example of Recursion

2.33 Example of recursion

2.34 Example of Tower of hanoi

2.35 Example of tower of hanoi

2.36 Models and packages


LIST OF TABLES

TABLE NO. TABLE NAME PAGE


NO.

2.1 Arithmetic operators

2.2 Relational operators

2.3 Relation expression

2.4 Logical operators 1

2.5 Logical operators 2

2.6 Logical operators 3

2.7 Programming language

2.8 Types of programming 1

2.9 Types of programming 1

2.10 Data with variable

2.11 Reserved word in python

2.12 Operators in python

2.13 Common false value

2.14 Conversion table

2.15 Loop table

2.16 Control structure

2.17 For loop

2.18 Tuple
2.19 Randon read and write

2.20 Tuple length

2.21 String Index table

2.22 Dictionary table

2.23 Inbuilt function

2.24 Set

2.25 Maths libraries

2.26 Data and function

2.27 Types of exception handling

2.28 File handling


CHAPTER 1
INTRODUCTION

1.1 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.

 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.

 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.

 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.

Fig 1.1

1.2 HISTORY OF PYTHON


Python was developed by Guido van Rossum in the late eighties and early nineties at the

National Research Institute for Mathematics and Computer Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,

Small Talk, and Unix shell and other scripting languages

Python is copyrighted. Like Perl, Python source code is now available under the GNU

General Public License (GPL).

Python is now maintained by a core development team at the institute, although Guido van

Rossum still holds a vital role in directing its progress.

1.3 PYTHON FEATURES

Python's features include:

 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.

 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.

 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.


 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

Python has a big list of good features:

 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.

 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.

1.4 WHAT IS PYTHON?

Python is a high-level scripting language which can be used for a wide variety of text

processing, system administration and internet-related tasks. Unlike many similar languages,

it’s core language is very small and easy to master, while allowing the addition of modules to

perform a virtually limitless variety of tasks.

Python is a true object-oriented language, and is available on a wide variety of platforms.

There’s even a python interpreter written entirely in Java, further enhancing python’s position

as an excellent solution for internet-based problems. Python was developed in the early

1990’s by Guido van Rossum, then at CWI in Amsterdam, and currently at CNRI in Virginia.

In some ways, python grew out of a project to design a computer language which would be

easy for beginners to learn, yet would be powerful enough for even advanced users. This

heritage is reflected in python’s small, clean syntax and the thoroughness of the

implementation of ideas like object-oriented programming, without eliminating the ability to


program in a more traditional style. So python is an excellent choice as a first programming

language without sacrificing the power and advanced capabilities that users will eventually

need.

Although pictures of snakes often appear on python books and websites, the name is derived

from Guido van Rossum’s favorite TV show, “Monty Python’s Flying Circus”. For this

reason, lots of online and print documentation for the language has a light and humorous

touch. Interestingly, many experienced programmers report that python has brought back a

lot of the fun they used to have programming, so van Rossum’s inspiration may be well

expressed in the language itself.

1.5 THE VERY BASICS OF PYTHON

There are a few features of python which are different than other programming languages,

and which should be mentioned early on so that subsequent examples don’t seem confusing.

Further information on all of these features will be provided later, when the topics are

covered in depth. Python statements do not need to end with a special character – the python

interpreter knows that you are done with an individual statement by the presence of a

newline, which will be generated when you press the “Return” key of your keyboard. If a

statement spans more than one line, the safest course of action is to use a backslash (\) at the

end of the line to let python know that you are going to continue the statement on the next

line; you can continue using backslashes on additional continuation lines. (There are

situations where the backslashes are not needed which will be discussed later.)

Python provides you with a certain level of freedom when composing a program, but there

are some rules which must always be obeyed. One of these rules, which some people find

very surprising, is that python uses indentation (that is, the amount of white space before the

statement itself) to indicate the presence of loops, instead of using delimiters like curly braces

({}) or keywords (like “begin” and “end”) as in many other languages. The amount of
indentation you use is not important, but it must be consistent within a given depth of a loop,

and statements which are not indented must begin in the first column. Most python

programmers prefer to use an editor like emacs, which automatically provides consistent

indentation; you will probably find it easier to maintain your programs if you use consistent

indentation in every loop, at all depths, and an intelligent editor is very useful in achieving

this.

1.6 INVOKING PYTHON

There are three ways to invoke python, each with its’ own uses. The first way is to type

“python” at the shell command prompt. This brings up the python interpreter with a message

similar to this one:

Python 2.2.1 (#2, Aug 27 2002, 09:01:47)

[GCC 2.95.4 20011002 (Debian prerelease)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

The three greater-than signs (>>>) represent python’s prompt; you type your commands after

the prompt, and hit return for python to execute them. If you’ve typed an executable

statement, python will execute it immediately and display the results of the statement on the

screen. For example, if I use python’s print statement to print the famous “Hello, world”

greeting, I’ll immediately see a response:

>>> print ’hello,world’

hello,world

The print statement automatically adds a newline at the end of the printed string. This is true

regardless of how python is invoked. (You can suppress the newline by following the string

to be printed with a comma.)


When using the python interpreter this way, it executes statements immediately, and, unless

the value of an expression is assigned to a variable, python will display the value of that

expression as soon as it’s typed. This makes python a very handy calculator:

>>> cost = 27.00


>>> taxrate = .075
>>> cost * taxrate
2.025
>>> 16 + 25 + 92 * 3
317
When you use python interactively and wish to use a loop, you must, as always, indent the

body of the loop consistently when you type your statements. Python can’t execute your

statements until the completion of the loop, and as a reminder, it changes its prompt from

greater-than signs to periods. Here’s a trivial loop that prints each letter of a word on a

separate line — notice the change in the prompt, and that python doesn’t respond until you

enter a completely blank line.

>>> word = ’python’


>>> for i in word:
... print i
...
p
y
t
h
o
n
The need for a completely blank line is peculiar to the interactive use of python. In other
settings, simply returning to the previous level of indentation informs python that you’re
closing the loop.
You can terminate an interactive session by entering the end-of-file character appropriate to

your system (control-Z for Windows, control-D for Unix), or by entering

import sys
sys.exit()

or
raise SystemExit

at the python prompt.

For longer programs, you can compose your python code in the editor of your choice, and

execute the program by either typing “python”, followed by the name of the file containing

your program, or by clicking on the file’s icon, if you’ve associated the suffix of your python

file with the python interpreter. The file extension most commonly used for python files is

“.py”. Under UNIX systems, a standard technique for running programs written in languages

like python is to include a specially formed comment as the first line of the file, informing the

shell where to find the interpreter for your program. Suppose that python is installed as

/usr/local/bin/python on your system. (The UNIX command “which python” should tell you

where python is installed if it’s not in /usr/local/bin.) Then the first line of your python

program, starting in column 1, should look like this:

#!/usr/local/bin/python

After creating a file, say myprogram.py, which contains the special comment as its first line,

you would make the file executable (through the UNIX command “chmod +x

myprogram.py”), and then you could execute your program by simply typing

“myprogram.py” at the UNIX prompt.

When you’re running python interactively, you can instruct python to execute files containing

python programs with the execfile function. Suppose that you are using python interactively,

and wish to run the program you’ve stored in the file myprog.py. You could enter the

following statement:

execfile("myprog.py")

The file name, since it is not an internal python symbol (like a variable name or keyword),

must be surrounded by quotes.

1.7 BASICS PRINCIPLES OF PYTHON


Python has many features that usually are found only in languages which are much more

complex to learn and use. These features were designed into python from its very first

beginnings, rather than being accumulated into an end result, as is the case with many other

scripting languages. If you’re new to programming, even the basic descriptions which follow

may seem intimidating. But don’t worry – all of these ideas will be made clearer in the

chapters which follow. The idea of presenting these concepts now is to make you aware of

how python works, and the general philosophy behind python programming. If some of the

concepts that are introduced here seem abstract or overly complex, just try to get a general

feel for the idea, and the details will be fleshed out later

1.7.1 BASIC CORE LANGUAGE

Python is designed so that there really isn’t that much to learn in the basic language. For

example, there is only one basic structure for conditional programming (if/else/elif), two

looping commands (while and for), and a consistent method of handling errors (try/except)

which apply to all python programs. This doesn’t mean that the language is not flexible and

powerful, however. It simply means that you’re not confronted with an overwhelming choice

of options at every turn, which can make programming a much simpler task.

1.7.2 MODULES

Python relies on modules, that is, self-contained programs which define a variety of functions

and data types, that you can call in order to do tasks beyond the scope of the basic core

language by using the import command. For example, the core distribution of python

contains modules for processing files, accessing your computer’s operating system and the

internet, writing CGI scripts (which handle communicating with pages displayed in web

browsers), string handling and many other tasks. Optional modules, available on the Python

web site (http://www.python.org), can be used to create graphical user interfaces,

communicate with data bases, process image files, and so on. This structure makes it easy to
get started with python, learning specific skills only as you need them, as well as making

python run more efficiently by not always including every capability in every program.

1.7.3 OBJECT ORIENTED PROGRAMMING

Python is a true object-oriented language. The term “object oriented” has become quite a

popular buzzword; such high profile languages as C++ and Java are both object oriented by

design. Many other languages add some object-oriented capabilities, but were not designed to

be object oriented from the ground up as python was. Why is this feature important? Object

oriented program allows you to focus on the data you’re interested in, whether it’s employee

information, the results of a scientific experiment or survey, setlists for your favorite band,

the contents of your CD collection, information entered by an internet user into a search form

or shopping cart, and to develop methods to deal efficiently with your data. A basic concept

of object oriented programming is encapsulation, the ability to define an object that contains

your data and all the information a program needs to operate on that data. In this way, when

you call a function (known as a method in object-oriented lingo), you don’t need to specify a

lot of details about your data, because your data object “knows” all about itself. In addition,

objects can inherit from other objects, so if you or someone else has designed an object that’s

very close to one you’re interested in, you only have to construct those methods which differ

from the existing object, allowing you to save a lot of work.

Another nice feature of object oriented programs is operator overloading. What this means is

that the same operator can have different meanings when used with different types of data.

For example, in python, when you’re dealing with numbers, the plus sign (+) has its usual

obvious meaning of addition. But when you’re dealing with strings, the plus sign means to

join the two strings together. In addition to being able to use overloading for built-in types

(like numbers and strings), python also allows you to define what operators mean for the data

types you create yourself.


Perhaps the nicest feature of object-oriented programming in python is that you can use as

much or as little of it as you want. Until you get comfortable with the ideas behind object-

oriented programming, you can write more traditional programs in python without any

problems.

1.7.4 NAMESPACES AND VARIABLE SCOPING

When you type the name of a variable inside a script or interactive python session, python

needs to figure out exactly what variable you’re using. To prevent variables you create from

overwriting or interfering with variables in python itself or in the modules you use, python

uses the concept of multiple namespaces. Basically, this means that the same variable name

can be used in different parts of a program without fear of destroying the value of a variable

you’re not concerned with.

To keep its bookkeeping in order, python enforces what is known as the LGB rule. First, the

local namespace is searched, and then the global namespace, then the namespace of python

built-in functions and variables. A local namespace is automatically created whenever you

write a function, or a module containing any of functions, class definitions, or methods. The

global namespace consists primarily of the variables you create as part of the “toplevel”

program, like a script or an interactive session. Finally, the built-in namespace consists of the

objects which are part of python’s core. You can see the contents of any of the namespaces

by using the dir command:

>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’]
>>> dir(__builtins__)
[’ArithmeticError’, ’AssertionError’, ’AttributeError’, ’EOFError’, ’Ellipsis’,
’Exception’, ’FloatingPointError’, ’IOError’, ’ImportError’, ’IndexError’,
’KeyError’, ’KeyboardInterrupt’, ’LookupError’, ’MemoryError’, ’NameError’,
’None’, ’OverflowError’, ’RuntimeError’, ’StandardError’, ’SyntaxError’,
’SystemError’, ’SystemExit’, ’TypeError’, ’ValueError’, ’ZeroDivisionError’, ’_’,
’__debug__’, ’__doc__’, ’__import__’, ’__name__’, ’abs’, ’apply’, ’callable’, ’chr’,
’cmp’, ’coerce’, ’compile’, ’complex’, ’delattr’, ’dir’, ’divmod’, ’eval’, ’execfile’, ’filter’,
’float’, ’getattr’, ’globals’, ’hasattr’, ’hash’, ’hex’, ’id’, ’input’, ’int’, ’intern’,
’isinstance’, ’issubclass’, ’len’, ’list’, ’locals’, ’long’, ’map’, ’max’, ’min’, ’oct’, ’open’,
’ord’, ’pow’, ’range’, ’raw_input’, ’reduce’, ’reload’, ’repr’, ’round’, ’setattr’, ’slice’,
’str’, ’tuple’, ’type’, ’vars’, ’xrange’]

The _ _builtins_ _ namespace contains all the functions, variables and exceptions which are

part of python’s core.

To give controlled access to other namespaces, python uses the import statement. There are

three ways to use this statement. In its simplest form, you import the name of a module; this

allows you to specify the various objects defined in that module by using a two level name,

with the module’s name and the object’s name separated by a period. For example, the string

module (Section 8.4) provides many functions useful for dealing with character strings.

Suppose we want to use the split function of the string module to break up a sentence into a

list containing separate words. We could use the following sequence of statements:

>>> import string

>>> string.split(’Welcome to the Ministry of Silly Walks’)

[’Welcome’, ’to’, ’the’, ’Ministry’, ’of’, ’Silly’, ’Walks’]

If we had tried to refer to this function as simply “split”, python would not be able to find it.

That’s because we have only imported the string module into the local namespace, not all of

the objects defined in the module. (See below for details of how to do that.)

The second form of the import statement is more specific; it specifies the individual objects

from a module whose names we want imported into the local namespace. For example, if we

only needed the two functions split and join for use in a program, we could import just those

two names directly into the local namespace, allowing us to dispense with the string. prefix:

>>> from string import split,join

>>> split(’Welcome to the Ministry of Silly Walks’)

[’Welcome’, ’to’, ’the’, ’Ministry’, ’of’, ’Silly’, ’Walks’]

This technique reduces the amount of typing we need to do, and is an efficient way to bring

just a few outside objects into the local environment.


Finally, some modules are designed so that you’re expected to have toplevel access to all of

the functions in the module without having to use the module name as a prefix. In cases like

this you can use a statement like:

>>> from string import *

Now all of the objects defined in the string module are available directly in the top-level

environment, with no need for a prefix. You should use this technique with caution, because

certain commonly used names from the module may override the names of your variables. In

addition, it introduces lots of names into the local namespace, which could adversely affect

python’s efficiency.

1.7.5 EXCEPTION HANDLING

Regardless how carefully you write your programs, when you start using them in a variety of

situations, errors are bound to occur. Python provides a consistent method of handling errors,

a topic often referred to as exception handling. When you’re performing an operation that

might result in an error, you can surround it with a try loop, and provide an except clause to

tell python what to do when a particular error arises. While this is a fairly advanced concept,

usually found in more complex languages, you can start using it in even your earliest python

programs.

As a simple example, consider dividing two numbers. If the divisor is zero, most programs

(python included) will stop running, leaving the user back at a system shell prompt, or with

nothing at all. Here’s a little python program that illustrates this concept; assume we’ve saved

it to a file called div.py:

#!/usr/local/bin/python

x=7y=0

print x/y

print "Now we’re done!"


When we run this program, we don’t get to the line which prints the message, because the

division by zero is a “fatal” error:

% div.py Traceback (innermost last):

File "div.py", line 5, in ?

print x/y

ZeroDivisionError: integer division or modulo

While the message may look a little complicated, the main point to notice is that the last line

of the message tells us the name of the exception that occurred. This allows us to construct an

except clause to handle the problem:

x=7
y=0

try:
print x/y
except Zero Division Error:
print "Oops - I can’t divide by zero, sorry!"

print "Now we’re done!"


Now when we run the program, it behaves a little more nicely:

% div.py

Oops - I can’t divide by zero, sorry!

Now we’re done!

Since each exception in python has a name, it’s very easy to modify your program to handle

errors whenever they’re discovered. And of course, if you can think ahead, you can construct

try/except clauses to catch errors before they happen.


CHAPTER 2
TRAINING WORK UNDERTAKEN

PROGRAMMING FUNDAMENTALS USING PYTHON PART 1

2.1 INTRODUCTION TO PROGRAMMING

2.1.1 WHY PROGRAMMING AND WHAT IS A PROGRAM?

In the airport there are many flights landing and taking off. Unlike road traffic, the flights

don't have direct information of other flights around them. The Air Traffic Control (ATC) at

the ground gives instructions to each flight on what it should do.

Fig. 2.1

Similarly, instructions are provided to computer to accomplish specific tasks. Such

instructions are known as program and the act of creating a program is known as

programming.

2.1.2THE SCENARIO – TAKEOFF AND LANDING


Various scenarios are used in an airport to discuss the concepts related to programming. Let

us take a look at few of the processes that happen during takeoff and landing.

TAKEOFF:

Fig. 2.2

LANDING:

Fig. 2.3

2.2 INTRODUCTION TO ALGORITHM & PSEUDO CODE

2.2.1 ALGORITHM AND ITS REPRESENTATION

Number of flights landed 1. Add the number of flights Number of flights


Number of flights took off landed to the initial number currently in the
Initial number of flights of flights in the airport airport
2. Subtract the number of
flights that took off
Input
process
output

Process is basically a sequence of computations to be performed using some Logic. This is

also known as an Algorithm. Different logic gives rise to different algorithms.


Algorithm should be represented from the mental thoughts into a form which others can

understand. There are primarily two ways of representing an algorithm:

 Flow chart: Diagrammatic way of representing the algorithm.

 Pseudo-code: Representing the algorithm between a program and normal English.

For example, here is a pseudo-code and a flowchart.

Pseudo-code:

input No_Of_Takeoffs, No_Of_Landings

Initial_No_Of_Flights=100

Current_No_Of_Flights=Initial_No_Of_Flights+No_Of_Landings-No_Of_Takeoffs

display "Current number of flights", Current_No_Of_Flights

Flowchart:

Fig: 2.4

Pseudo-code cannot be executed by a computer. It is representation of an algorithm for

programmer to understand.

2.3 BASICS OF ALGORITHM AND PSEUDO CODE

2.3.1 VARIABLES AND OPERATORS

input No_Of_Takeoffs, No_Of_Landings


Initial_No_Of_Flights=100
Current_No_Of_Flights=Initial_No_Of_Flights+No_Of_Landings-No_Of_Takeoffs
display "Current number of flights", Current_No_Of_Flights

To assign a value to the variable, we can use the = symbol. It is also called the assignment
operator. It’s called an operator because it operator on the data.
No_Of_Takeoffs, No_Of_Landings, Initial_No_Of_Flights ,Current_No_Of_Flights are

variables used in this pseudo – code.

Variables are like containers for data (i.e. they hold that data) and the value of the variable

can vary in the pseudo code.

Like assignment operator, there are other operators which can be used to perform various

operations. Arithmetic operators: used for performing arithmetic operations.

Table: 2.1
Relational operators: Also known as comparison operators, are used to compare values.

Result of a relational expression is always either true or false.

Table: 2.2
Logical operators are used to combine one or more relational expressions
Table: 2.3
If A and B are two relational expressions, say A = (Num1>2000), B= (Num2>100), the result

of combining A and B using logical operator is based on the result of A and B as shown

below:

Table: 2.4 Table: 2.5 Table: 2.6

2.3.2 DECISION CONSTRUCTS

In a pseudo-code, typically the instructions are performed one by one or line by line. But

there may be situations when all the statements in a pseudo-code are not performed. Parts of

the pseudo-code which change the flow of instructions or change the flow of control are

called as control structures.

SELETCION
Selection/ decision control structure
Types of control structure are used when we want to consider alternatives.

ITERATION
Iteration control structures are used when
we need to perform repetitive instructions.
ATC takes lot of decisions as part of its air traffic control operations.

For example, if a flight is approaching the runway, ATC should check if the runway is free. If

the runway is not free, then the flight should not land immediately. It should circle in the air

and wait for further instructions from the ATC.

Such decision-making process can be conveniently represented in a pseudo-code using an if

statement.

Sometimes, ATC may have more than one alternative for a given situation. For example, if

the runway is free, the flight can land. But if the flight has less fuel, then it should be allowed

an emergency landing. Otherwise, it should circle in the air.

if (Runway=="free") then

display "Land"

else if (Fuel_Status=="low") then

display "Emergency landing"

else

display "Circle in the air"

end-if

2.3.3 ITERATION CONSTRUCTS


Immigration check needs to be done for all the passengers in the flight. Suppose the flight had only 5

passengers, the pseudo-code can be written as follows:

display "Flight has landed"


display "Proceed for Immigration Check"
Passenger_Count=1
display "Immigration check done for passenger,", Passenger_Count
Passenger_Count=Passenger_Count+1
display "Immigration check done for passenger,", Passenger_Count
Passenger_Count=Passenger_Count+1
display "Immigration check done for passenger,", Passenger_Count
Passenger_Count=Passenger_Count+1
display "Immigration check done for passenger,", Passenger_Count
Passenger_Count=Passenger_Count+1
display "Immigration check done for passenger,", Passenger_Count

Sometimes, you may want to execute some statements specific (known) number of times as

in the case of immigration check. In such cases you can use a for loop as shown below.

No_Of_Passengers=5
for(Passenger_Count=1,Passenger_Count<=No_Of_Passengers,Passenger_Count=Passe
nger_Count+1)
display "Immigration
check done for passenger,",
Passenger_Count
end-for

When you want to repeatedly execute a statement as long as a condition is met, you can use

the iteration statement called as while loop.

display "The flight has landed"


display "Immigration check done"
display " Collect the baggage from the conveyor belt"
Baggage_Count=150
while(Baggage_Count>0) do
input No_Of_Baggage_Picked
Baggage_Count=Baggage_Count-No_Of_Baggage_Picked
end-while

Go through the below two pseudo-code and guess the output.


PSEUDO CODE 1:
Counter=5
while(Counter>=5) do
display Counter
Counter = Counter + 1
end-while
PSEUDO CODE 2:
input Limit
for(Counter=5, Counter<=Limit, Counter=Counter-1)
display Counter
end-for

(Assume that the input value provide to variable limit is 5.)

Be cautious of infinite loops. The logic written in loops should ensure that the loop will

terminate in finite number of iterations.

2.4 VARIABLES, DATATYPES AND OPERATORS IN PYTHON

2.4.1 WHAT IS PROGRAMMING LANGUAGE?

Pseudo-code helped us to represent the algorithms and learn few basics of programming. But

to instruct the computer we need to write a program in a programming language. There are

many languages available in which we can write our programs.

Different languages are created for different purposes. This involves trade-offs. For example

a large flight can carry many passengers, but also consumes lot of fuel. Similarly different

languages have different advantages.

We will be learning programming using Python in this course.

Table: 2.7

2.4.2 DATATYPES

We know that a program works on data or values. Some examples of values are 1, 1.0 and

"Hello".
For a program to use a data, it must be stored in a memory location. The values are stored in

binary form in computer memory.

How do we know how many bits are required to represent a value or how much space it

needs in memory?

This is determined by the data type of the value and the programming language. e.g. number,

string etc. Thus every value will have a type.

Data Type determines the operations that can be performed on a value. For e.g. we can

perform operations like addition, multiplication, division, subtraction etc. on numerical data

types. We can concatenate, convert case, extract substring etc. on string data types.

print(1 + 2)

print("Hello + "World")

print(True and False)

print(4.0 / 2.0)

The above program uses 8 values of different data types.

A program may have data belonging to different types. Common data types used in

programming are:

Table: 2.8
Python programming language supports the following data types:
Table: 2.9

2.4.3 VARIABLES

Fig 2.5

If everything is a value, then what is a variable?

A variable is a name that is assigned to a value. It is done so that we can refer to that value at

some later point in the program.

Let us see the usage of values and variables in a program.

 During input, we receive values and assign

them to variables.

 During processing, we perform operations on values and variables to generate more

values. These computed values are also assigned to variables.

 During output, we display the computed values in variables to the end users.
Let's have a look at the python program to display the number of landings and number of

takeoffs in an airport:

Note: In Python, print() can be used to display output in the console

2.4.4 VARIABLES AND DATATYPE

Let's see how can we associate a data type with a variable.

Table: 2.10
Languages like Python are dynamically typed whereas C,Go etc are statically typed.

Dynamic Typing is a technique in some languages where depending on how a value is used,

the data type of the variable is dynamically and automatically assigned. Consider the below

code in Python,

num=65 #Line 1

num="A" #Line 2

In Line 1, variable num is considered to be of type int and in Line 2, its type is reassigned to

String.

Static Typing is used in some languages where the data type has to be declared before a

variable is used. Consider the below code in Go,

var num int=65; //Line 1

num="A"; //Line 2

var name string = "A"; //Line3

Here, Line 1 is a valid statement which declares a variable num of type int. But Line 2 is

invalid as we cannot assign a string value to variable num which is already declared to be of

type int. Line 3 is a valid statement where name is declared and used as a string.
Any name can be given to a variable however, we cannot use some of the built-in keywords

of the language. These keywords are known as reserved words. Some of the reserved words

in Python are:

Table: 2.11
If you put a small product in a big box, you may end up wasting space. Similarly if you put a

big product in a small box you may end up damaging the product.

Just like product is placed in a box, data occupies memory. Some data need more memory

whereas some other data require less memory based on the data type.

In Python language, automatically creates just the right memory needed - neither less nor

more.

We have seen that a variable will have a name, value, type and it will occupy memory. Apart

from these, it has two more dimensions scope and lifetime. Thus we can say that any variable

will have the following six dimensions.

Fig: 2.6

2.4.5 OPERATORS

As we discussed in pseudo-code, operators help to perform an operation.


Some of the most common operators used in Python are listed below.

Table: 2.12

Note: In Python, // indicates integer division.

Example: 11//2=5

The result of a relational or logical expression is always a boolean (true or false). Apart from

the boolean values, other values can also be used to represent a true or false value.

For example, in python, value zero is considered to be equivalent to false.

The common false values in Python are given below. Any other value is considered to be

true.

Table: 2.13

What do you think is the output of 5+4*9% (3+1)/6-1? How do you think the result of this

expression is computed?

It is done based on the precedence of the operators. Precedence of an operator can be

identified based on the rule - BODMAS. Brackets followed by Orders (Powers, Roots),

followed by modulo, Division and Multiplication, followed by Addition and Subtraction.

1. Brackets have the highest precedence followed by orders.

2. Modulo, Division and Multiplication have the same precedence. Hence if all appear in an

expression, they are evaluated from Left to Right.


3. Addition and Subtraction have the same precedence. Hence if both appear in an

expression, they are evaluated from Left to Right.

Fig. 2.7

Though its not compulsory to have brackets to denote the precedence of operators in an

expression, it is always preferred to have brackets as it makes the expression readable and

brings in a lot more clarity.

Fig. 2.8

2.4.6 IMPLICIT AND EXPLICIT TYPE CONVERSION

Take a look at the below code:

Why do you think the result is 2.0 ?

num=1 +1.0

The result is 2.0!

Here we were actually expecting the output as 2 but Python automatically converted 1 into a

float and added with 1.0. This is known as implicit conversion.


Implicit conversions are dangerous as one may encounter unexpected result.

Take a look at the below code:

num=1 + int(1.0)

The result will be 2!

If we want the output as 2, then we have to explicitly convert the float 1.0 into integer 1. This

is known as explicit conversion. Explicit conversion involves mentioning the data type within

brackets explicitly.

Programming languages define their own rule for implicit and explicit conversions and these

rules will change from language to language.

We noticed that implicit conversions are dangerous as one may encounter unexpected result.

Similarly, one has to be careful in explicit conversions as well. For example,

1. Converting a floating point value to integer would result in loss of decimal point values.

2. A larger data type if converted to smaller data type will result in loss of data as the number

will be truncated.

Table: 2.14

2.5 CODING STANDARDS AND FORMATTING OUTPUT

2.5.1 CODING STANDARDS

Here are two programs implementing the same functionality.

CODE 1: CODE 2:
a=356 '''This is a program to find the
b=245 current number of flights in an airport'''
c=89 landings_count=356
d=a+c-b takeoffs_count=245
print(d) initial_flights=89
current_flights = initial_flights + landings_count

takeoffs_count
#Displaying the current number of flights
print("Current number of
flights:",current_flights)

Though we can give any name to a variable other than reserved words, Google has come up

with style guides for most of the programming languages. These style guides help to bring in

uniformity and enhance readability of programs written by programmers across the world.

As per Google style guide, variable names in Python should be written as var_name.

The pattern followed in Python is known as snake_case.

Apart from this, it is important to place comments wherever possible to explain code and use

meaningful variable names. Comment is an explanation provided in the code which makes it

easier to understand for a person who is going through the code. These are all part of coding

standards which is a set of guidelines that can be used to enhance the readability and clarity

of the program. It also makes it easier to debug and maintain the program.

Coding standards are the set of guidelines that can be used to enhance the readability and

clarity of the program and make it easy to debug and maintain the program.

Fig: 2.9

2.6 INTRODUCTION TO FUNCTION

2.6.1 FUNCTION IN PROGRAMS

A function is a block of code that performs a particular task. In python, functions are

declared using the keyword def.


Fig: 2.10

2.7 SELECTION CONTROL STRUCTURE

2.7.1 CONTROL STRUCTURE

Recall the different control structures using which the programmer specifies the order of

execution of statements. The commonly used control structures in programming are:

Fig: 2.11

2.7.2 SELECTION CONTROL STRUCTURE

During check-in process in an airport, the luggage weight of each passenger is checked and in

case of over-weight, they are asked to pay for extra luggage. Below Python program

represents the check-in process. Go through it and guess the output. Assume luggage weight

is always positive

ticket_status="Confirmed"
luggage_weight=32
weight_limit=30 #Weight limit for the airline
extra_luggage_charge=0
if(ticket_status=="Confirmed"):
if(luggage_weight>0 and luggage_weight<=weight_limit):
print("Check-in cleared")
elif(luggage_weight<=(weight_limit+10)):
extra_luggage_charge=300*(luggage_weight-weight_limit)
else:
extra_luggage_charge=500*(luggage_weight-weight_limit)
if(extra_luggage_charge>0):
print("Extra luggage charge is Rs.", extra_luggage_charge)
print("Please make the payment to clear check-in")
else:
print("Sorry, ticket is not confirmed")

The program you have seen uses various decision control statements for implementing the

logic. Let’s explore it one by one using scenarios related to check-in process.One of the first

steps during check-in process is checking the passport status. Consider the below program

written for that.

1. passenger_name="Chan"
2. passport_status="valid"
3. if(passport_status=="valid"):
4. print("Airport security cleared")
5. else:

6. print("Invalid passport")

The conditional statement used in this program is known as if-else statement.

The next step in check-in process is checking the luggage weight.

1. luggage_weight=30
2. weight_limit=30 #Weight limit for the airline
3. extra_luggage_charge=0
4. if(luggage_weight>0 and luggage_weight<=weight_limit):
5. print("Check-in cleared")
6. elif(luggage_weight<=(weight_limit+10)):
7. extra_luggage_charge=300*(luggage_weight-weight_limit)
8. else:
9. extra_luggage_charge=500*(luggage_weight-weight_limit)
10.
11. if(extra_luggage_charge>0):
12. print("Extra luggage charge is Rs.", extra_luggage_charge)
13. print("Please make the payment to clear check-in")

The conditional statement in this program is known as the else if ladder . The conditions are

evaluated from top of the ladder downwards. As soon as a true condition is encountered, the

statement associated with it is executed. The remaining condition checks in the ladder will be

skipped.

Let’s combine the luggage check-in process with ticket validation. Ticket validation happens

first followed by luggage check-in.

1. ticket_status="Confirmed"
2. luggage_weight=32
3. weight_limit=30 #Weight limit for the airline
4. extra_luggage_charge=0
5. if(ticket_status=="Confirmed"):
6. if(luggage_weight>0 and luggage_weight<=weight_limit):
7. print("Check-in cleared")
8. elif(luggage_weight<=(weight_limit+10)):
9. extra_luggage_charge=300*(luggage_weight-weight_limit)
10. else:
11. extra_luggage_charge=500*(luggage_weight-weight_limit)
12. if(extra_luggage_charge>0):
13. print("Extra luggage charge is Rs.", extra_luggage_charge)
14. print("Please make the payment to clear check-in")
15. else:

16. print("Sorry, ticket is not confirmed")

The conditional statement written in this program is known as nested if statement. In this

case, an if statement is written within another if statement. Similarly, any decision logic can

also be written within an else statement.

2.8 ITERATION CONTROL STRUCTURE


2.8.1 ITERATION CONTROL STRUCTURES – SYNTAX

When we want to repeatedly execute a statement as long as a condition is met, we can use the

iteration statement called as while loop.

Go through the below python code and guess the output. Assume that the number of baggage

picked by the passengers will always be less than or equal to baggage_count. For this code,

consider baggage picked in each iteration are 54, 20, 24, 0, 1, 0, 1.

1. baggage_count=100
2. no_of_baggage_picked=0
3. while(baggage_count>0):
4. no_of_baggage_picked = (int)(input ("Number of
baggage:"))
5. baggage_count = baggage_count -
no_of_baggage_picked

6. print("No. of baggage remaining:",baggage_count)

Note: Use Eclipse to execute the code having input statement

fig: 2.12

Suppose a flight has landed with 5 passengers and immigration check needs to be done for all

of them. Have a look at the below code:

1. print("Flight has landed")


2. print("Proceed for immigration check")
3. passenger_count=1
4. print("Immigration check done for passenger,",
passenger_count)
5. passenger_count+=1
6. print("Immigration check done for passenger,",
passenger_count)
7. passenger_count+=1
8. print("Immigration check done for passenger,",
passenger_count)
9. passenger_count+=1
10. print("Immigration check done for passenger,",
passenger_count)
11. passenger_count+=1
12. print("Immigration check done for passenger,",
passenger_count)

When we want to execute some statements specific (known) number of times as in the case of

immigration check, we can use a for loop as shown below:

1. print("Flight has landed")


2. print("Proceed for immigration check")
3. for passenger_count in 1,2,3,4,5:
4. print("Immigration check done for passenger,",
passenger_count)

In Python, for loop allows the loop to run over a specific sequence of values. In other words,

for every value in the sequence, the loop runs once.

Fig.2.13

2.8.2 ITERATION CONTROL STRUCTURES – ‘for’ with ‘range’


Consider the below code.

What if we want the loop to run from 1 to 100? Should we modify the below code to create a

sequence of values from 1 to 100 ?

1. for number in 1,2,3,4,5:


2. print("The current number is ",number)

We can create a sequence of values in Python using range(x,y,step). It creates a sequence

from x to y-1 with a difference of step between each value.

1. start=1
2. end=10
3. step=2
4. for number in range (start, end, step):

5. print("The current number is ", number)

 start - Starting number of the sequence

 end - Generate number up to end, but not including this number

 step - Difference between each number in the sequence

It is not mandatory to give step. The default value of step is 1.

2.8.3 ITERATION CONTROL STRUCTURES – NESTED LOOPS

Here, we need to use nested loop (loop inside another loop) as we need to maintain the count

of passengers and the count of baggage of each passenger.


Assume that there are 5 passengers and each of them have 2 baggage. The below code will

make sure that all baggage of each passenger have undergone the security check.

1. number_of_passengers=5
2. number_of_baggage=2
3. security_check=True
4. for passenger_count in range(1,
number_of_passengers+1):
5. for baggage_count in range(1,number_of_baggage+1):
6. if(security_check==True):
7. print("Security check of passenger:",
passenger_count, "-- baggage:", baggage_count,"baggage
cleared")
8. else:
9. print("Security check of passenger:",
passenger_count, "-- baggage:", baggage_count,"baggage
not cleared")

2.8.4 ITERATION CONTROL STRUCTURES – ‘BREAK’AND


CONTINUE’

Table: 2.15
Go through the below code and guess the output. Assume A – Adult passenger, C- Child, FC

– Flight Captain, FA – Flight Attendant, SP – Suspicious passenger.

1. for passenger in "A","A", "FC", "C", "FA", "SP", "A", "A":


2. if(passenger=="FC" or passenger=="FA"):
3. print("No check required")
4. continue
5.
6. if(passenger=="SP"):
7. print("Declare emergency in the airport")
8. break
9.
10. if(passenger=="A" or passenger=="C"):
11. print("Proceed with normal security check")
12.
13.
14. print("Check the person")
15. print("Check for cabin baggage")

When we want to stop a loop or break away from it we can use break statement.

1. for passenger in "A","A", "FC", "C", "FA", "SP", "A",


"A":
2. if(passenger=="FC" or passenger=="FA"):
3. print("No check required")
4. continue
5.
6. if(passenger=="SP"):
7. print("Declare emergency in the airport")
8. break
9.
10. if(passenger=="A" or passenger=="C"):
11. print("Proceed with normal security check")
12.
13. print("Check the person")
14. print("Check for cabin baggage")
When we want to skip the remaining portion of loop statements and continue with the next

iteration, we can use continue statement.

1. for passenger in "A","A", "FC", "C", "FA", "SP", "A",


"A":
2. if(passenger=="FC" or passenger=="FA"):
3. print("No check required")
4. continue
5.
6. if(passenger=="SP"):
7. print("Declare emergency in the airport")
8. break
9.
10. if(passenger=="A" or passenger=="C"):
11. print("Proceed with normal security check")
12.
13. print("Check the person")
14. print("Check for cabin baggage")

2.8.5 ITERATION CONTROL STRUCTURES – TESTING LOOPS

In this code, we observe that loop condition will always evaluate to true. Hence the loop will

never terminate. Such loops are known as infinite loops.

Always ensure that loop will terminate in finite number of iterations.

Copy the below code, execute it in Playground and observe the results:

1. counter = 5
2. while (counter >= 5):
3. print(counter)
4. counter = counter + 1
5.

A simple loop like this can be tested with test data to


 skip the entire loop.

 make 1 pass through the loop.

 make n, n+1,n-1 passes through the loop,

 where n is the maximum number of passes possible through the loop

Also, always watch out for infinite loop.

The test data as per this method for the below code are:

1. counter = 1
2. while(counter <= 3):
3. print(counter)
4. counter += 1

Table: 2.16
In case of for loops in Python, as initialization and change of value are automatically taken

care, while testing we just need to test it with

1. an empty sequence

2. a non-empty sequence

1. num_list = [1,2]
2. for num in num_list:
3. print(num, end = " ")

Table: 2.17

If there is any logic inside the for loop, additionally test it using the technique applicable for

it.

2.9 ECLIPSE PLUG – IN

2.9.1 INTRODUCTION TO ECLIPSE PLUG – IN

Eclipse is a modern IDE. IDE stands of Integrated Development Environment, where all the

necessary tools for developing your code are integrated into one piece.

You will be using Eclipse to solve your assignments and to take your assessments.

For your assignments you will have the option to verify the correctness of your code and

submit your code by using appropriate buttons in Eclipse, as will be discussed now.

You can verify your code any number of times, but you can submit only once.
2.9.2 TIP TO HANDLE INFINITE LOOP

1. baggage_count=100

2. no_of_baggage_picked=0

3. while(baggage_count>0):

4. no_of_baggage_picked = 10

5. print("No. of baggage remaining:",baggage_count)

In this code, we observe that loop condition will always evaluate to true. Hence the loop will

never terminate. Such loops are known as infinite loops. Always ensure that loop will

terminate in finite number of iterations. Here is a tip to handle infinite loops in Eclipse IDE.

If your code is entering into infinite loop during execution, you can terminate the execution

process by clicking the terminate button in the Console tab of Eclipse IDE. Check the code

for infinite loop and correct it before doing the verification using the verify button.
Fig: 2.14

2.10 COLLECTION AND LIST IN PYTHON

2.10.1 INTRODUCTION TO COLLECTION

Fig: 2.15

We can store the ticket numbers by creating one variable for each passenger.

ticket_no_1 = 78808
ticket_no_2 = 26302
ticket_no_n = 48310

However it may not be a good idea. We need a way to store these ticket numbers independent

of the number of tickets. For this we can use collections, where data can be stored together.

There are many collection data types which are supported by programming languages.

2.10.2 LIST:

Let’s start by exploring one of the most common collection data type – list. It can be used to

store a group of elements together in a sequence. Suppose we want to store the ticket

numbers allocated to each passenger traveling in a flight. Instead of using separate variable

for each ticket number, we can use a list as shown below.


Fig: 2.16

In case of having different variables for each ticket number, variables will be stored in

separate memory locations. Whereas in case of list, the elements will be stored in contiguous

memory locations.

Fig: 2.17
Each element in the list has a position in the list known as an index.

The list index starts from zero. It’s like having seat numbers starting from 0!

Fig: 2.18

 Suppose seat number 2 is allocated to the passenger with ticket number 93634, the

passenger can directly go to seat number 2 without having to go through other seats.

Similarly, index positions actually help us to directly access a value from the list.

list_name[index] can be used to directly access the list element at the mentioned

index position.

 Suppose we have to allocate a different passenger to seat number 3, we can do it as

ticket_list[3]=13504. Thus, in addition to using the index to access an element

directly, we can also use it to directly modify an element in the list.

 Just like how we cannot allocate 101 st seat to a passenger in a 100 seat plane, we

cannot access values beyond the total number of elements in the list. For example:

print(ticket_list[5]) will result in index out of bound error.

2.11 TUPLE IN PYTHON

2.11.1 TUPLE
How can we store it such that no one can modify the elements? Of course, we can use a list

but anybody can modify an element in the list. This is where we can use another collection

data type known as tuple.

Like list, tuple can also store a sequence of elements but the value of the elements cannot be

changed. (i.e. tuples are IMMUTABLE). Elements can be homogeneous or heterogeneous

but they are READ-ONLY.

Operation Example Description

() are optional, a set of values

separated by comma is also considered

to be a tuple.

sample_tuple="A","B","C"
lunch_menu=("Welcome
Although () are optional, it is a good
Creating a Drink","VegStarter","Non-Veg
practice to have them for readability of
tuple Starter","Veg Main Course","Non-Veg
code.
Main Course","Dessert")

If we need to create a tuple with a

single element, then we need to

include a comma as shown below:

sample_tuple=("A",)

This will result in an error as tuple is


Random
lunch_menu[0]="" immutable. Hence random write is not
Write
possible in tuple.

Table: 2.18
All the remaining operations are similar to lists.

Let’s learn the tuple operations in comparison with lists.

Random read and write

Operation Tuple List

Random read print(sample_tuple[2]) print(sample_tuple[2])

sample_tuple[0] = “I“ sample_list[0] = “I"

Random write
This will result in an error as tuple is immutable. This works as list is

Hence random write is not possible in tuple. mutable.

x, y, z = sample_tuple

Unpacking of
a, b, c = 1, 2, 3 x, y, z = sample_list
elements

This is also valid as 1,2,3 is a tuple.

Table: 2.19

Finding the length

Tuple List

len(sample_tuple) len(sample_list)

Table: 2.20

2.12 STRING IN PYTHON

2.12.1 STRING
In a program, not all values will be numerical. We will also have alphabetical or alpha

numerical values. Such values are called strings. Example: “Hello World”, pancard number -

“AABGT6715H” , name – “Arjun”, ticket number – “BA1045” Each value in a string is

called a character. Just like list elements, we can access the characters in a string based on

its index position.

String "AABGT6715H"

Character A A B G T 6 7 1 5 H

Index 0 1 2 3 4 5 6 7 8 9

Table: 2.21

In Python, string is a data type and anything enclosed in a single quote or double quote is

considered to be a string. All the remaining operations are similar to lists. But like tuple,

strings are also IMMUTABLE.

2.13 DUBUGGING

2.13.1. INTRODUCTION TO DEBUGGING

Here is a program which has written to perform the baggage check of all the passengers of a

particular flight. Each passenger can carry a minimum of 1 kg and a maximum of 30kg.

count=0

i=1

for baggage_weight in 29, 30, 31, 32, 28:

if(baggage_weight>=1 or baggage_weight<=30):

print("Passenger",i,": Proceed for baggage check.")


else:

count+=1

print("Passenger",i,": Maximum baggage weight allowed is 30kg.")

i+=1

print("No. of passengers who cleared baggage check:", count)

But the code is having some logical errors/bugs.

Actual Output: Expected Output:

Passenger 1 : Proceed for baggage check. Passenger 1 : Proceed for baggage check.
Passenger 2 : Proceed for baggage check. Passenger 1 : Proceed for baggage check.
Passenger 3 : Maximum baggage weight
Passenger 3 : Proceed for baggage check.
allowed is 30kg.
Passenger 3 : Maximum baggage weight
Passenger 4 : Proceed for baggage check.
allowed is 30kg.
Passenger 5 : Proceed for baggage check. Passenger 5 : Proceed for baggage check.
No. of passengers who cleared baggage No. of passengers who cleared baggage
check: 0 check: 3

How can we help Chan to fix the errors?

When there are logical errors/bugs in a program, we can either manually debug the

program the way that we have been doing so far or we can take the help of a debugging

tool provided by the IDE we are using. As we are using Eclipse IDE, we can use the

debugger in the Eclipse tool to help us in debugging. Let’s try debugging with a different

program which finds all even numbers in a given range.

#PF-Tryout

'''This program is expected to display all the even numbers

between 1 and n (both inclusive)'''

i=1

n=10
while(i<=n):

if(i%2==0):

print(i)

i+=1

else:

continue

i+=1

2.13.2 ECLIPSE DEBUGGER

Below given are the steps to use the debugger in the Eclipse IDE. This is the starting screen

when you open eclipse. You can close this welcome tab to proceed further.

Fig: 2.19

Click on the 'open perspective' button on the top right corner of the screen
Fig: 2.20

Choose Programming Assignment from the open perspective pop-up

Fig:2.21

2.14 DICTIONARY IN PYTHON

2.4.1 DICTIONARY

Suppose these are the 5 countries to which flights operate from an airport.
Fig: 2.22

We want to know the country to which maximum flights have departed on a day.

How can we do this? We can maintain a count for each country. As and when a flight departs

from the airport, count for the country to which it has departed can be increased by one. At

the end of the day, we just need to pick the country with the maximum count from this.

Fig: 2.23

Independently they do not make sense. We need to store them as key-value pairs. In

programming, this can be done using a collection known as dictionary which allows to store

key-value pairs where each key is unique. One of the advantage of using dictionary is that it

allows very fast search for value based on key.


Fig:2.24

Dictionaries can be used to store an unordered collection of key-value pairs. The key should

be unique and can be of any immutable data type. Like lists, dictionaries are mutable. Let’s

now understand how a dictionary is implemented in Python.

crew_details=

{ "Pilot":"Kumar",
First element in every pair is the key and the
Creating a dictionary "Co-pilot":"Raghav",
second element is the value.
"Head-Strewardess":"Malini",

"Stewardess":"Mala" }

Accessing the value This will return the corresponding value for
crew_details["Pilot"]
using key the specified key

for key,value in
Iterating through the items function gives both key and value,
crew_details.items():
dictionary which can be used in a for loop.
print(key,":",value)

Table: 2.22

Dictionary in Python also have many inbuilt functions.

Function Output Explanation

Returns the value for given key. If the


crew_details.get("Pilot") Kumar
given key is not found, returns None

crew_details.update({"Flight No output, Updates the dictionary with the given

Attendant":"Jane", "Co- dictionary will key-value pairs. If a key-value pair is

pilot":"Henry"}) be updated already existing, it will be overwritten,

otherwise it will be added to the


Function Output Explanation

dictionary

Table: 2.23

2.15 SET IN PYTHON


2.15.1 SET

A set is an unordered group of values with no duplicate entries. Set can be created by using

the keyword set or by using curly braces {}. set function is used to eliminate duplicate values

in a list.

Removes the duplicates from the


Creating a flight_set={500,520,600,345,520,634,600,
given group of values to create
set 500,200,200}
the set

passengers_list=["George", "Annie",
Eliminating set function - removes the
"Jack", "Annie", "Henry", "Helen",
duplicates duplicates from the list and
"Maria", "George", "Jack", "Remo"]
from a list returns a set
unique_passengers=set(passengers_list)

Common

elements Creates a new set which has

between setA&setB common elements from setA and

setA and setB

setB

Elements
Creates a new set which has only
that are only setA - setB
unique elements of setA
in setA

Merges setA | setB Creates a new set which has all


elements of

setA and the elements of setA and setB

setB

Table: 2.24

2.16 LIBRARIES AND FUNCTIONS IN PYTHON

2.16.1 MATHS LIBRARIES

math is another useful module in Python. Once you have imported the math module, you

can use some of the below functions:

Function Explanation

math.ceil(x) Smallest integer greater than or equal to x

math.floor(x) Largest integer smaller than or equal to x

math.factorial(x) Factorial of x

math.fabs(x) Gives absolute value of x

Table: 2.25

2.16.2 DATA AND FUNCTIONS

Python has inbuilt modules called time and datetime. They are very helpful in finding details

of time.

Function Explanation

time.gmtime() Returns the current GM time

time.localtime() Returns the current time based on the current locality


Converts t to a string as specified by the format argument

and returns it.

time.strftime(t,format) Where t is the time returned by time.gmtime() or

time.localtime(). It is optional, default value is current time

as returned by time.localtime()

datetime.datetime.strptime Converts a date string in the specified format to a datetime

(date_string, format) value and returns it

datetime.date.today() Returns the current local date

Table: 2.26
PROGRAMMING FUNDAMENTALS USING PYTHON PART 2

2.17 INTRODUCTION:

2.17.1 SUMMERY OF PROGRAMMING FUNDAMENTALS USING


PYTHON

This course "Programming Fundamentals using Python - Part 2" is in continuation with

"Programming Fundamentals using Python - Part 1".

In "Programming Fundamentals using Python - Part 1" course the following topics have

been covered:

1. Why do we need programming and what is programming all about.

2. Algorithms & pseudo-codes which help us in building the logic for a given problem

statement

3. The basic aspects of Python i.e variables, operators and control structures.

4. Lastly, collections which is one of the critical aspects in any language. List, tuple, set and

dictionary collection types have been considered for discussion under collections.
This course "Programming Fundamentals using Python - Part 2" introduces concepts

which would help us in developing a robust code, organizing the application code more

efficiently and recursive approach for specific scenarios.

2.18 FUNCTIONS - ARGUMENTS

2.18.1 ARGUMENTS BEHAVIOR

In programming, there are two ways in which arguments can be passed to functions: pass by

and pass by reference. Some languages use pass by value by default while others use pass

by reference. Some languages support both and allow you to choose.

Everything in Python is considered to be an object and can be categorized as either ‘Mutable’

or ‘Immutable’. In Python, arguments are passed by reference.

Fig: 2.25
Fig: 2.26

2.18.2 TYPES OF ARGUMENTS

Programming languages allow controlling the ordering and default values of arguments.

In python we will observe the following:

Code 1: Positional def func(arg1, arg2):


return result
res=func(val1, va12)
Default way of specifying arguments. In this, the order, count and type of actual arguments
should exactly match that of the formal arguments. Else, it will result in error.
Code 2: Keyword def func(arg1, arg2):
return result
res=func(arg2=va12, arg1-val1)
Allows flexibility in the order of passing the actual arguments by mentioning the argument
name.
Code 3: Default
def func(arg1, arg2=default_value):
return result
res func (val1)
Allows to specify default value for an argument in the function signature. It is used only
when no value is passed for that argument else it works normally. In Python, default
arguments should be last in the order.
Code 4: Variable argument count
def func(arg1, arg2, *arg3)
return result
res-func(val1, val2, val3, val4, va15)
Allows a function to have variable number of arguments. In Python, any argument name
starting with is considered to be a varying length argument. It should be last in the order. It
works by copying all values beyond that position into a tuple.

2.19 VARIABLES AND ITS SCOPE


2.19.1 TYPES OF VARIABLES

There are two types of variables which we can use in a program - local variables and global

variables.

Local variables are the ones which are created inside a function. They are created when the

owning function starts execution and remains in memory till owning function finishes

execution. They can be accessed only inside that function.

Global variables are the ones which are created outside the functions. They are created when

the program execution starts and remains in memory till the program terminates. They can be

read anywhere in the program - within a function or outside.

Fig: 2.27

2.19.2 VARIABLES AND ITS SCOPE

In cases where a global variable needs to be modified inside a function, like in function

update_baggage_limit(), Python allows you to do that using the global keyword.

wt limit=30
def baggage_check (baggage_wt):

extra_baggage_charge=0

if not (baggage_wt>=0 and baggage_wt<=wt_limit): extra_baggage-baggage_wt-


wt_limitextra_baggage_charge=extra_baggage*100 return extra_baggage_charge

wt limit

def update_baggage_limit(new_wt_limit):

specified using

global wt limit

global keyword

wt_limit=new_wt_limit

print("This airline now allows baggage Limit till", wt_Limit, "kgs")

print("This airline allows baggage Limit till", wt_limit, "kgs") print("Pay the extra
baggage charge of", baggage check (35), "rupees") update_baggage_limit(45)
print("Pay the extra baggage charge of", baggage check (35), "rupees")

2.20 UNIT TESTING

2.20.1 CODE REVIEW, UNIT TESTING AND LOGIC CONVERGES

We have written couple of programs by now. How do you know that your programs are

correct? One way is to ask your peer or an expert to go through the code and identify if there

are any mistakes. This way of reviewing your code for correctness is known as Code

Review. Though there are guidelines for code review, it is possible that the person who is

reviewing may miss some things.

2.20.2 LOGIC CONVERGES – IDENTIFY TEST DATA


fig: 2.28

There are three decisions in this program We have to identify airline values which will take

the control through the true and false paths of each decision, it is sufficient to cover the entire

logic and uncover any error. Enter two values of airline which will ensure that the logic

written in decision 1 is covered. Similarly for decision 2 and 3, identify the values of airline

and respective output which will cover the logic for both. Can we use the same “Invalid

airline” value to cover the false path of all the three decisions? Then we’ll need just four set

of test data to test the entire logic with decision 1, 2 and 3 put together. This is one of the

testing techniques which can be used to cover the logic.

2.20.3 BOUNDARY VALUE ANALYSIS

What if the programmer has written the condition like: luggage_wt>= 1 and luggage_wt< 30?

Will it work as per the requirement for luggage weight of 30kg?


Whenever ranges (say >0 and <=30, >=30, >=1 and <=30 etc.) are being written in

conditions, we need to exhaustively test as most of the programmers make errors while

writing these conditions. Hence it may not be sufficient to check with just two values that

take control to the true and false paths alone.

In that case we should test the boundaries by considering values

- on the boundary,

- one above the boundary and

- one below the boundary

This technique of identifying test data on the boundaries is known as boundary value

analysis. The correct logic for the check-in process of Air India is as given below The test

data values we should use for luggage_wt as per boundary value analysis are:

Fig: 2.29
Fig: 2.30

The testing that we have been doing so far is known as unit testing.

Here, unit is the smallest testable part of a program or application, in our case a function. It is

done to check whether a unit is performing its intended task or not and it is the responsibility

of the programmer to test the piece of code that he/she has written. Below are few of the unit

testing techniques that can be used by the programmer to test the program.

fig.2.31

Among these, we have learnt boundary value analysis and path/logic coverage.

2.21 EXCEPTION HANDLING IN PYTHON

2.21.1 EXCEPTION HANDLING – DIFFERENT TYPES

Python has many kinds of errors predefined as part of the language. Here are some of the

common types. Exception

Built-in
When it will be raised Example
Exception
num_list=[]

ZeroDivisionError When a value is divided by zero total=10

avg=total/len(num_list)

When we try to do an operation total=10


TypeError
with incompatible data types total+="20"

When we try to access a variable


NameError avg=total/10 where total is not defined
which is not defined

When we try to access an index num_list=[1,2,3,4]


IndexError
value which is out of range value=num_list[4]

#string is a valid data type for int() but


When we use a valid data type
the value “A” is invalid, as "A" can't be
for an argument of a built-in
ValueError converted into int.
function but passes an invalid
value="A"
value for it
num=int(value)

Table: 2.27

Python also allows us to handle different errors that can occur separately. That means you can

have a different action or message for every unique error that occurs. Here is the same

expenditure calculation code with additional average expenditure calculation.

def calculate_expenditure(list_of_expenditure):
total=0
try:
for expenditure in list_of_expenditure:
total+=expenditure
print("Total:",total)
avg=total/num_values
print("Average:",avg)
except ZeroDivisionError:
print("Divide by Zero error")
except TypeError:
print("Wrong data type")
except:
print("Some error occured")
list_of_values=[100,200,300,"400",500]
num_values=0
calculate_expenditure(list_of_values)
NOTE:

1. Default except block is the one without any type mentioned.

2. If an error occurs and the matching except block is found, then that is executed.

3. If an error occurs and the matching except block is not found, it executes the default

except block.

4. If an error occurs and the matching except block is not found and if the default except

block is also not found, the code crashes.

5. The default except block, if present should be the last except block, otherwise it will

result in a runtime error.

2.22 RECURSION

Human tower is created by men standing on shoulders of the men standing at the lower level.

It can have any number of levels. Each level will have 2 men less than the previous level.
However, there will always be one person at the top of the tower, that means there will

always be odd number of men standing at the bottom most/base level.

Fig: 2.32

Suppose we want to find the total weight of a human tower which has 5 people standing at

the bottom level. Assume that each person weighs 50 kg and there will always be odd number

of men at the base level. We can solve this problem recursively. Have a look.

def human tower (no_of_people):

if(no of people == 1): return 1*(50)

else:

Recursive function call

return no of people (50) + human tower (no of people - 2)

print "Total weight of human tower: ", human_tower (5)


Fig:2.33

In recursion, two things are important – termination condition and recursive call. Recursive

call invokes itself with a smaller argument and termination condition helps to terminate the

recursive calls.

def human_tower (no_of_people):

if(no_of_people ==1): Termination condition or

return 1*(50)

base condition

Recursive function call

else:

return no of people (50) human_tower (no_of_people 2)

print "Total weight of human tower: ", human_tower(5)

2.23 TOWER OF HANOI PROBLEM

Tower of Hanoi is another problem which can be used to learn recursion. This problem was

discovered by the French mathematician Edouard Lucas in 1883.

Rules
 Move only one disk at a time. Rings must be in decreasing size

 No move should result in a larger disk on top of a smaller disk

 For temporarily holding a disk, the third tower can be used

Fig:2.34

Let’s understand how the solution can be defined recursively for transferring 3 rings from

tower A to tower B.

Step-1: Two rings moved from tower A to tower C

 solution is arrived for 2 rings using A as source tower, C as destination tower and B as

temp tower

Step-2: A ring is transferred from tower A to tower B

Step-3: Two rings moved from tower C to tower B

 solution is arrived for 2 rings using C as source tower, B as destination tower and A as

temp tower
fig: 2.35

2.24 MODULE AND PACKAGES

Code organization is done through modules and packages!

 A module is nothing but a normal python file with a .py extension.

 A package is just a normal folder which contains an empty file who’s name is

__init__.py. Since package is a folder it can store many python modules/files in it.

Fig: 2.36

Let's assume that the ManageFlights.py inside Flights package has the below code:

airline="Smart Airlines"

def add(no_of_flights):

print(no_of_flights," flights added to the fleet")


If we need to access the function add(), inside the Manage Flights module in some other

module, then we can import the Manage Flights module and use it. Import can be done in two

ways: Method 1:

from Flights import ManageFlights #from packagename import modulename

ManageFlights.add(10)

Method 2:

import Flights.ManageFlights #import packagename.modulename

Flights.ManageFlights.add(10)

Consider a scenario where 2 modules have the same name but in different package and both

of them have the same function ‘add’.

Flights->Manage.py->add()

Employees->Manage.py->add()

To avoid naming conflicts during import we can use one of the below techniques:

I.

import Flights.Manage

import Employees.Manage

Flights.Manage.add()

Employees.Manage.add()

II.
from Flights import Manage as FManage

from Employees import Manage as EManage

FManage.add()

EManage.add()

III.

from Flights.Manage import add as add1

from Employees.Manage import add as add2

add1()

add2()

2.25. FILE HANDLING

Python allows to create files, read from files, write content to file and append content to

existing content through inbuilt functions!


Table: 2.28

The number of files that can be simultaneously opened by a program is limited. So it is very

important to close all the files, once the operations are completed.

flight_file=open("flight.txt","w")

flight_file.write("Hello")

flight_file.close()

Note: You can execute all the codes related to file handling in Eclipse Plug-in and observe

the output
Sometimes, we may encounter exceptions when dealing with files. In this example, we are

trying to write to a file which is opened in read-only mode. This will result in an exception. In

such a case, let’s see how we can use try except block to catch this exception.

try:

flight_file=open("flight.txt","r")

text=flight_file.read()

print(text)

flight_file.write(",Good Morning")

flight_file.close()

except:

print("Error occurred")

if flight_file.closed:

print("File is closed")

else:

print("File is open")

When we want to write a code that will run in all situations, we can put it in a finally block.

Since closing a file is necessary we can do it in the finally block instead of in the try block.

try:

flight_file=open("flight.txt","r")

text=flight_file.read()

print(text)

flight_file.write(",Good Morning")

except:

print("Error occurred")
finally:

print("File is being closed")

flight_file.close()

if flight_file.closed:

print("File is closed")

else:

print("File is open")

Firstly, copy "Code 1" to TryOut.py in Eclipse Plug-in. Execute and observe the results.

Now, copy "Code 2" to execute and observe the results.

Code 1:

try:

hello_file=open("flight.txt","w")

text="Hello everyone! Welcome"

hello_file.write(text)

except:

print("Error occurred, not able to write to file")

finally:

hello_file.close()

try:

hello_file=open("flights.txt","r")

text_from_file=hello_file.read()

print(text_from_file)

except:

print("Error Occurred, not able to read from file")


finally:

hello_file.close()

Code 2:

try:

hello_file=open("flight.txt","w")

text="Hello everyone! Welcome"

hello_file.write(text)

except:

print("Error occurred, not able to write to file")

finally:

hello_file.close()

try:

hello_file=open("flight.txt","r")

text_from_file=hello_file.read()

print(text_from_file)

except:

print("Error Occurred, not able to read from file")

finally:

hello_file.close()
CHAPTER 3
RESULTS AND DISCUSSION

3.1 PYTHON PROGRAMS

3.1.1 Program to check Prime Number in Python Program.


n= int(input("Enter the number: "))

if (n > 1):

for i in range(2, n):

if n % i == 0:

print(n, "is not a prime number")

break

else:

print(n, "is a prime number")

else:

print(n, "is not a prime number")

OUTPUT:

Enter the number:

17 17 is a prime

number
3.1.2 Program to check if a number is Positive, Negative or Zero.

n = int(input("Enter the number:

")) if n < 0:

print("Number is negative")

elif n == 0:

print("Number is zero")

elif n > 0:

print("Number is positive")

OUTPUT:

Enter the

number: 5

Number is

positive
3.1.3 Program to read a Number n and computer n+ nn+ nnn in Python.

n = input("Enter the number: ")

result = int(n) + int(n + n) + int(n + n + n)

print("result =", result)

OUTPUT:

Enter the number:

5 result = 615
3.1.4 Program to read Height in centimeters and then convert the Height to
Feet and inches.

cm = int(input("Enter the height in centimeters:

")) inches = 0.394 * cm

feet = 0.0328084 * cm

print("The length in inches is", round(inches, 2))

print("The length in feet is", round(feet, 2))

OUTPUT:

Enter the height in centimeters:

170 The length in inches is 66.93

The length in feet is 5.58


3.1.5 Program to find sum of Natural Numbers.

n = int(input("Enter the number: "))

sum = 0

for i in range(n + 1):

sum += i

print(f"Sum of {n} natural numbers: {sum}")

OUTPUT:

Enter the number: 5

Sum of 5 natural numbers: 15


3.1.6 Program to implement Simple Calculator in Python.

a= int(input("Enter the first number: "))

b = int(input("Enter the second number: "))

print("Choose any operation from add, subtract, multiply,

divide") op = input("Enter the operation: ")

match op:

case "add":

print("Result:", a + b)

case "subtract":

print("Result:", a - b)

case "multiply":

print("Result:", a * b)

case "divide":

print("Result:", a / b)

case _:

print("Invalid operation")
OUTPUT:

Enter the first number: 5

Enter the second number: 3

Choose any operation from add, subtract, multiply,

divide Enter the operation: add

Result: 8

3.1.7 Program to find out how many 1 and 0 in given number.

n = input("Enter the number: ")

one = n.count("1")

zero = n.count("0")

print(f"Number of zero in {n}: {zero}")

print(f"Number of one in {n}: {one}")

OUTPUT:

Enter the number: 100101


Number of zero in 100101: 3

Number of one in 100101: 3

3.1.8 Program to perform following operation with list:


(a) To get largest number from list.
(b) To search an element in a list.

n = int(input("Enter the element to search: "))

num_list = [5, 2, 10, 2, 8, 6]

print("Largest number of list:",

max(num_list)) if n in num_list:

print(n, "is in the list")

else:

print(n, "is not in the list")


OUTPUT:

Enter the element to search:

8 Largest number of list: 10

8 is in list

3.1.9 Program to count the number of times a character appears in given


string.

my_string = input("Enter the string: ")

char = input("Enter the character: ")

count = my_string.count(char)

print(f"{char} occurs {count} times in {my_string}")

OUTPUT:

Enter the string : Hello World


Enter the character: l

l occurs 3 times in Hello World

3.1.10 Program to print all integers that aren’t divisible by either 2 or 3


and lie between 1 and 50 in Python.

for i in range(1, 51):

if not (i % 2 == 0 or i % 3 == 0):

print(i, end=" ")

OUTPUT:
1 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49

3.1.11 Program in python to remove an element from a list.

my_list = [4, 3, 1, 23, 7, 10, 14]

my_list.remove(23)

print(my_list)
OUTPUT:
[4, 3, 1, 7, 10, 14]

3.1.12 Program to Find factorial a number using recursion

def factorial(n):

if n == 0:

return 1

if n == 1:
return 1

else:

return n * factorial(n - 1)

n = int(input("Enter the number: "))

print(f"Factorial of {n} is: {factorial(n)}")

OUTPUT:

Enter the number: 5

Factorial of 5 is: 120

3.1.13 Program to print Multiplication Table using recursion.

def table(n, i):

if i <= 10:

print(f"{n} * {i} = {n * i}")

table(n, i + 1)
n = int(input("Enter the number: "))

i = 1 # Start from 1 for multiplication table

table(n, i)

OUTPUT:

Enter the number: 5


5*1=5

5 * 2 = 10

5 * 3 = 15

5 * 4 = 20

5 * 5 = 25

5 * 6 = 30

5 * 7 = 35

5 * 8 = 40

5 * 9 = 45

5 * 10 = 50

3.1.14 Program to add two integers only with Exception Handling in


Python

try:

a = int(input("Enter the first value: "))

b = int(input("Enter the second value: "))


sum = a + b

print(f"Addition of {a} and {b} is {sum}")

except ValueError:

print("Input integer only")

except TypeError:

print("Type of both input should be same")

except Exception:

print("Other Error")

OUTPUT:

Enter the first value: 5

Enter the second value: abc

Input integer only

3.1.15 Python program to Count the Number of Words in a Text File.

fname=input(“Enter file name: ”)

num_words=0
with open(fname, ‘r’) as f:

for line in f:

words=line.split()

num_words+=len(words)

print(“Number of words:”)

print(num_words)

Suppose you have a text file named "sample.txt" with the following

content: This is a sample text file.

It contains multiple lines.

Each line has several words

OUTPUT:

Enter file name:

sample.txt Number of

words:

15

3.2 PROJECTS

3.2.1 Convert PDF to TXT using Python

import PyPDF2
def pdf_to_txt(pdf_path, txt_path):

try:

with open(pdf_path, 'rb') as pdf_file:

pdf_reader = PyPDF2.PdfReader(pdf_file)

text = ''

for page_num in range(len(pdf_reader.pages)):

page = pdf_reader.pages[page_num]

text += page.extract_text()

with open(txt_path, 'w', encoding='utf-8') as txt_file:

txt_file.write(text)

print("PDF to TXT conversion successful.")

# Provide the input PDF file path and output TXT file path

pdf_file_path = 'input.pdf' # Change this to the actual PDF file path

txt_file_path = 'output.txt' # Change this to the desired TXT file path

pdf_to_txt(pdf_file_path, txt_file_path)

3.2.2 How to send automatic Whatsapp Messages in Python.

import pywhatkit
phone_number = "+1234567890" # Replace with the recipient's phone

number message = "Hello from Python!" # The message you want to send

hour = 14 # Hour (24-hour format)

minute = 30 # Minute

pywhatkit.sendwhatmsg(phone_number, message, hour, minute)

print("Message sent successfully.")

CHAPTER4
CONCLUSIONS AND FUTURE SCOPE
4.1 CONCLUSION

Practical knowledge means the visualization of the knowledge, which we read in our books.
For this, we perform experiments and get observations. Practical knowledge is very important
in every field. One must be familiar with the problems related to that field so that he may
solve them and become a successful person. After achieving the proper goal in life, an
engineer has to enter in professional life. According to this life, he has to serve an industry,
may be public or private sector or self-own. For the efficient work in the field, he must be
well aware of the practical knowledge as well as theoretical knowledge. Due to all above
reasons and to bridge the gap between theory and practical, our Engineering curriculum
provides a practical training of 30 days. During this period a student work in the industry and
get well all type of experience and knowledge about the working of companies and hardware
and software tools. I have under gone my 30 days summer training after 1 st year at
infosys.pvt.ltd. This report is based on the knowledge, which I acquired during my 30 days
of summer training.

4.2 FUTURE SCOPE

Python is a high-level, interpreted programming language that has become increasingly


popular for web development, data analysis, artificial intelligence, and other fields. There are
many Python courses available in Pune, India, which offer training for beginners and
advanced learners. They are typically offered by reputed training institutes, universities, and
online platforms. Python courses in Pune usually include hands-on exercises, projects, and
assignments to help students gain practical experience and apply what they have learned.
Many courses also offer certification upon completion, which can be valuable for students
looking to demonstrate their skills to potential employers. Some popular Python courses in
Pune include those offered by Codekul, LearnWell Technocraft, Seed Infotech, Edureka, and
Simplilearn. These courses can vary in duration, price, and teaching style, so it's important
for students to research their options and choose the one that best fits their needs and goals.
REFERENCE

https://youtu.be/vLqTf2b6GZw?si=fF0ZOkjFNpQagbWM

https://infyspringboard.onwingspan.com/web/en/app/toc/
lex_auth_0125409616243425281061_shared/overview

https://infyspringboard.onwingspan.com/web/en/app/toc/
lex_auth_012734003600908288382_shared/overview

You might also like