Python 1st Yr Training
Python 1st Yr Training
At
BACHELOR OF TECHONOLOGY
SUBMITTED BY:
URN: 2203775
CANDIDATE'S DECLARATION
I “VRITIKA CHAUDHARY” hereby declare that I have undertaken one month training
to July 31,2023 in partial fulfillment of requirements for the award of degree of B.Tech
COLLEGE, LUDHIANA. The work which is being presented in the training report submitted
The one month industrial training Viva–Voce Examination of_________ has been held on
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
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
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
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
GNDEC for their intellectual support throughout the course of this work.
Finally, We are indebted to all whosoever have contributed in this report work.
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
On 24 August 2021, Infosys became the fourth Indian company to reach US$100 billion in
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$
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.
Topic Page
No.
Certificate by Infosys
ii.-vi
Candidate’s Declaration
vii
Abstract viii
Acknowledgement
ix
x-xi
List of Figures
List of Tables
CHAPTER 1 INTRODUCTION
1.1 Python
1.7.2 Modules
1.7.3 Object Oriented Programming
2.4.3 Variables
2.4.5 Operations
2.10.2 List
2.11.1 Tuple
2.12.1 String
2.13 Dubugging
2.14.1 Dictonary
2.17 Introduction:
2.22 Recursion
3.1.4 Program to read Height in centimeters and then convert the Height
in given string.
in Python.
3.2 Projects
REFERENCE
LIST OF FIGURES
1. Infosys x
1.1 Python
2.2 Takeoff
2.3 Landing
2.4 Flowchart
2.5 Variables
2.8 Code
2.9 Debug
2.15 Collection
2.16 List
2.18 Tuple
2.19 Randon read and write
2.24 Set
1.1 PYTHON
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.
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
Fig 1.1
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,
Python is copyrighted. Like Perl, Python source code is now available under the GNU
Python is now maintained by a core development team at the institute, although Guido van
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
Easy-to-read: Python code is more clearly defined and visible to the eyes.
A broad standard library: Python's bulk of the library is very portable and cross-
Interactive Mode: Python has support for an interactive mode which allows
Portable: Python can run on a wide variety of hardware platforms and has the same
Extendable: You can add low-level modules to the Python interpreter. These modules
to many system calls, libraries and windows systems, such as Windows MFC,
Scalable: Python provides a better structure and support for large programs than shell
scripting
large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
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
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
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
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.
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
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”
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
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:
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
import sys
sys.exit()
or
raise SystemExit
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
#!/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
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),
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
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
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.
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
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
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.
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
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
>>> 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
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:
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:
This technique reduces the amount of typing we need to do, and is an efficient way to bring
the functions in the module without having to use the module name as a prefix. In cases like
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.
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
#!/usr/local/bin/python
x=7y=0
print x/y
print x/y
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
x=7
y=0
try:
print x/y
except Zero Division Error:
print "Oops - I can’t divide by zero, sorry!"
% div.py
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
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
Fig. 2.1
instructions are known as program and the act of creating a program is known as
programming.
us take a look at few of the processes that happen during takeoff and landing.
TAKEOFF:
Fig. 2.2
LANDING:
Fig. 2.3
Pseudo-code:
Initial_No_Of_Flights=100
Current_No_Of_Flights=Initial_No_Of_Flights+No_Of_Landings-No_Of_Takeoffs
Flowchart:
Fig: 2.4
programmer to understand.
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 are like containers for data (i.e. they hold that data) and the value of the variable
Like assignment operator, there are other operators which can be used to perform various
Table: 2.1
Relational operators: Also known as comparison operators, are used to compare values.
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:
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
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
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
if (Runway=="free") then
display "Land"
else
end-if
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
Be cautious of infinite loops. The logic written in loops should ensure that the loop will
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
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
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
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,
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(4.0 / 2.0)
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
A variable is a name that is assigned to a value. It is done so that we can refer to that value at
them 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:
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
num="A"; //Line 2
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
Fig: 2.6
2.4.5 OPERATORS
Table: 2.12
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.
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?
identified based on the rule - BODMAS. Brackets followed by Orders (Powers, Roots),
2. Modulo, Division and Multiplication have the same precedence. Hence if all appear in an
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
Fig. 2.8
num=1 +1.0
Here we were actually expecting the output as 2 but Python automatically converted 1 into a
num=1 + int(1.0)
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
We noticed that implicit conversions are dangerous as one may encounter unexpected result.
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
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.
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
A function is a block of code that performs a particular task. In python, functions are
Recall the different control structures using which the programmer specifies the order of
Fig: 2.11
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
1. passenger_name="Chan"
2. passport_status="valid"
3. if(passport_status=="valid"):
4. print("Airport security cleared")
5. else:
6. print("Invalid passport")
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
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:
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
When we want to repeatedly execute a statement as long as a condition is met, we can use the
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,
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
fig: 2.12
Suppose a flight has landed with 5 passengers and immigration check needs to be done for all
When we want to execute some statements specific (known) number of times as in the case of
In Python, for loop allows the loop to run over a specific sequence of values. In other words,
Fig.2.13
What if we want the loop to run from 1 to 100? Should we modify the below code to create a
1. start=1
2. end=10
3. step=2
4. for number in range (start, end, step):
Here, we need to use nested loop (loop inside another loop) as we need to maintain the count
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")
Table: 2.15
Go through the below code and guess the output. Assume A – Adult passenger, C- Child, FC
When we want to stop a loop or break away from it we can use break statement.
In this code, we observe that loop condition will always evaluate to true. Hence the loop will
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.
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
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.
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
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
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
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.
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:
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
Like list, tuple can also store a sequence of elements but the value of the elements cannot be
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")
sample_tuple=("A",)
Table: 2.18
All the remaining operations are similar to lists.
Random write
This will result in an error as tuple is immutable. This works as list is
x, y, z = sample_tuple
Unpacking of
a, b, c = 1, 2, 3 x, y, z = sample_list
elements
Table: 2.19
Tuple List
len(sample_tuple) len(sample_list)
Table: 2.20
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 -
called a character. Just like list elements, we can access the characters in a string based on
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,
2.13 DUBUGGING
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
if(baggage_weight>=1 or baggage_weight<=30):
count+=1
i+=1
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
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
#PF-Tryout
i=1
n=10
while(i<=n):
if(i%2==0):
print(i)
i+=1
else:
continue
i+=1
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
Fig:2.21
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
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
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
Table: 2.23
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.
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
setB
Elements
Creates a new set which has only
that are only setA - setB
unique elements of setA
in setA
setB
Table: 2.24
math is another useful module in Python. Once you have imported the math module, you
Function Explanation
math.factorial(x) Factorial of x
Table: 2.25
Python has inbuilt modules called time and datetime. They are very helpful in finding details
of time.
Function Explanation
as returned by time.localtime()
Table: 2.26
PROGRAMMING FUNDAMENTALS USING PYTHON PART 2
2.17 INTRODUCTION:
This course "Programming Fundamentals using Python - Part 2" is in continuation with
In "Programming Fundamentals using Python - Part 1" course the following topics have
been covered:
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
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
Fig: 2.25
Fig: 2.26
Programming languages allow controlling the ordering and default values of arguments.
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
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
Fig: 2.27
In cases where a global variable needs to be modified inside a function, like in function
wt limit=30
def baggage_check (baggage_wt):
extra_baggage_charge=0
wt limit
def update_baggage_limit(new_wt_limit):
specified using
global wt limit
global keyword
wt_limit=new_wt_limit
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")
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
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
What if the programmer has written the condition like: luggage_wt>= 1 and luggage_wt< 30?
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
- on 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.
Python has many kinds of errors predefined as part of the language. Here are some of the
Built-in
When it will be raised Example
Exception
num_list=[]
avg=total/len(num_list)
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
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:
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
5. The default except block, if present should be the last except block, otherwise it will
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
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.
else:
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.
return 1*(50)
base condition
else:
Tower of Hanoi is another problem which can be used to learn recursion. This problem was
Rules
Move only one disk at a time. Rings must be in decreasing size
Fig:2.34
Let’s understand how the solution can be defined recursively for transferring 3 rings from
tower A to tower B.
solution is arrived for 2 rings using A as source tower, C as destination tower and B as
temp tower
solution is arrived for 2 rings using C as source tower, B as destination tower and A as
temp tower
fig: 2.35
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):
module, then we can import the Manage Flights module and use it. Import can be done in two
ways: Method 1:
ManageFlights.add(10)
Method 2:
Flights.ManageFlights.add(10)
Consider a scenario where 2 modules have the same name but in different package and both
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
FManage.add()
EManage.add()
III.
add1()
add2()
Python allows to create files, read from files, write content to file and append content to
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:
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.
Code 1:
try:
hello_file=open("flight.txt","w")
hello_file.write(text)
except:
finally:
hello_file.close()
try:
hello_file=open("flights.txt","r")
text_from_file=hello_file.read()
print(text_from_file)
except:
hello_file.close()
Code 2:
try:
hello_file=open("flight.txt","w")
hello_file.write(text)
except:
finally:
hello_file.close()
try:
hello_file=open("flight.txt","r")
text_from_file=hello_file.read()
print(text_from_file)
except:
finally:
hello_file.close()
CHAPTER 3
RESULTS AND DISCUSSION
if (n > 1):
if n % i == 0:
break
else:
else:
OUTPUT:
17 17 is a prime
number
3.1.2 Program to check if a number is Positive, Negative or Zero.
")) 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.
OUTPUT:
5 result = 615
3.1.4 Program to read Height in centimeters and then convert the Height to
Feet and inches.
feet = 0.0328084 * cm
OUTPUT:
sum = 0
sum += i
OUTPUT:
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:
Result: 8
one = n.count("1")
zero = n.count("0")
OUTPUT:
max(num_list)) if n in num_list:
else:
8 is in list
count = my_string.count(char)
OUTPUT:
if not (i % 2 == 0 or i % 3 == 0):
OUTPUT:
1 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49
my_list.remove(23)
print(my_list)
OUTPUT:
[4, 3, 1, 7, 10, 14]
def factorial(n):
if n == 0:
return 1
if n == 1:
return 1
else:
return n * factorial(n - 1)
OUTPUT:
if i <= 10:
table(n, i + 1)
n = int(input("Enter the number: "))
table(n, i)
OUTPUT:
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
try:
except ValueError:
except TypeError:
except Exception:
print("Other Error")
OUTPUT:
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
OUTPUT:
sample.txt Number of
words:
15
3.2 PROJECTS
import PyPDF2
def pdf_to_txt(pdf_path, txt_path):
try:
pdf_reader = PyPDF2.PdfReader(pdf_file)
text = ''
page = pdf_reader.pages[page_num]
text += page.extract_text()
txt_file.write(text)
# Provide the input PDF file path and output TXT file path
pdf_to_txt(pdf_file_path, txt_file_path)
import pywhatkit
phone_number = "+1234567890" # Replace with the recipient's phone
number message = "Hello from Python!" # The message you want to send
minute = 30 # Minute
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.
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