Practical Training Aruu

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

A

Report of Practical training taken


On
“PYTHON PROGRAMMING LANGUAGE”

Completed at Msme technology center

bhiwadi, Alwar
Submitted in partial fulfillment for the award of
the

Diploma
In
Computer Science &

Engineering

Of

Board of technical education (Raj), Jodhpur

SUBMITTEDBY:
GUIDEDBY:
MR. B.R. MALI DAKSH LIMBA
(LECTURER)
ADAMYA RAJPUROHIT
DR. MURLIDHAR VERMA
KAILASH DAS
(LECTURER)
HARSHIT NATH

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING.


GOVERNMENT POLYTECHNIC COLLEGE, JODHPUR
2023-24
PREFACE

Not only theoretical knowledge but also practical knowledge is essential for a

technical student and thus the project work is beneficial for him to learn

more and more about practical works.

An excellent practical work and knowledge makes an engineer successful in

qualities are very important every field and these for an Engineer, in my

opinion and it is also old come of my project work also.

This report gives good knowledge about practical training work. I will never

say that it is complete in itself out. I have tried to do my best in preparing this

report. I think this report will be taken as reference by coming students.

The report consists of details about “PYTHON PROGRAMMING”. This report

is prepared by an student of Computer Science & Engineering.


COMPANY PROFILE

MSME Technology Center, Bhiwadi

(Established by Department of Technical Education, Govt. of Rajasthan)

Centre for Electronic Governance is an autonomous body of Government of


Rajasthan under the Department of Technical Education.
The MSME Technology Centre, Bhiwadi, is a premier institution in India dedicated to
supporting Micro, Small, and Medium Enterprises (MSMEs) in enhancing their
technological capabilities and competitiveness. Established under the Ministry of
MSME, Government of India, this centre plays an important role in the industrial
growth and development of the region.

The institute offers long term, medium term and short term courses in
CAD/CAM/CAE/CNC Machining and Tool & Die Technology. The centre offers
Diploma courses namely, Advanced Diploma in Tool & Die Making, Diploma in
Logistics Technology and Diploma in Mechatronics. These programs aim to equip
the industry with a skilled workforce adept in cutting-edge technologies.
The centre is equipped with state-of-the-art infrastructure and facilities, including
modern workshops, laboratories, and technology demonstration units. These
facilities
cater to various sectors such as manufacturing, electronics, and information
technology. Moreover, the centre specializes in the design and manufacturing of
high-quality Press Tools, Die Casting Dies, Moulds, Jigs, Fixtures, and Gauges,
customized to meet the specific requirements of clients while adhering to stringent
international standards.
Acknowledgement

The training report on PYTHON PROGRAMMING is an outcome of guidance,


moral support & devotion bestowed on me through my work. For this let me
acknowledge & express our performance sense of gratitude & thanks to
everybody who have been source of inspiration during the training period.
First & foremost, I offer my sincere phrases of thanks with innate humility to
Dr. AJAY MATHUR (H.O.D) computer science, Govt. Polytechnic College,
Jodhpur & guide my project for providing help whenever needed.
The consistence guidance & support provided by MR. Anshu Kumar Sehgal
(Principal) of Govt. Polytechnic College and Mr. B.R. Mali (Lecturer),
Dr.Murlidhar Verma (Lecturer) So we are very thankful to
acknowledge for key
role played by him in providing me with his precious ideas, suggestion & help
that enabled in shaping project work.
If I can say in words I must at the outset tender my intimate or receipt of
affectionate care to Govt. Polytechnic College, Jodhpur for providing such
stimulating atmosphere & work environment.

( Daksh Limba )
Declaration

I hereby certify that the work which is being presented in the report entitled
“PYTHON PROGRAMMING LANGUAGE” in fulfillment of the requirement for
completion of 6 Week industrial training in department of Computer Science
Engineering of “Board of Technical Education Jodhpur (Rajasthan)” is an authentic
record of my own work carried out during industrial training.

( Daksh Limba )
ABSTRACT

This report contains the Python programming language basics. Python


is a general-purpose programming language that can be used to teach
programming concepts. Participants will learn Python and greatly
benefit from performing hands-on exercises. The participants will
write the lines of code by following the instructor and/or the provided
handouts. The instructor and his assistant(s) will help the individuals
with their questions and problems. The instructor will use a Windows
machine to cover the topics. The participants are expected to bring
their own laptops. The instructor and his assistant(s) will be available
to help the participants with the installation of the needed software for
the workshop prior to the start of the workshop. The topics include,
among other things, displaying messages, working with variables,
using operators, performing computations, making decisions, creating
loops, and working with lists.
Certificate
Training Report
Contents
Chapter-1 Introduction To Python.....................................................................01
Python....................................................................................................................01
History of python...................................................................................................01
Features of python................................................................................................01
Limitations of python............................................................................................02
Applications of python..........................................................................................03
Some Python editors............................................................................................03
Companies using python......................................................................................03
Chapter -2 Variables and types.........................................................................04
Variable.................................................................................................................04
Rules of declaring variable name.........................................................................04
Lets see the program,(declaring variable)...........................................................05
Data Types............................................................................................................05
Keywords..............................................................................................................06
Operators..............................................................................................................06
CHAPTER-3 STRINGS.........................................................................................11
Definition...............................................................................................................11
String slicing..........................................................................................................12
String functions.....................................................................................................13
Escape sequence character.................................................................................14
CHAPTER- 4 Conditional Statements...............................................................15
INTRODUCTION...................................................................................................15
Type of conditional statements...........................................................................15
Simple if statement............................................................................................. 15
4.2.2 if....else statement......................................................................................17
4.2.3. if....elif.....else statement...........................................................................18
4.2.4. Nested-if statement...................................................................................20
Chapter- 5 List and Tuples.................................................................................22
What are Lists?......................................................................................................22
Declaring a List of Numbers...................................................................................22
Accessing Elements Within a List..........................................................................22
Declaring a List of Mixed Data Types.....................................................................23
Lists Within Lists.....................................................................................................24
Accessing Lists Within Lists...................................................................................24
Changing Values in a list........................................................................................25
Variable Storage Locations....................................................................................26
Copying a List.........................................................................................................26
List methods...........................................................................................................27
Tuples.....................................................................................................................27
Tuple indexing and slicing......................................................................................29
Basic Tuple operations...........................................................................................31
Tuple in built functions...........................................................................................32
Where use tuple?....................................................................................................32
Chapter – 6 Loops in Python................................................................................33
INTRODUCTION.....................................................................................................33
Looping in python...................................................................................................33
While Loop..............................................................................................................34
For Loop..................................................................................................................35
Chapter – 7 Functions in python................;.........................................................37
Definition.................................................................................................................37
Types of functions...................................................................................................37
Advantage of Function sin Python..........................................................................37
Creating a Function.................................................................................................38
There turn statement..............................................................................................39
Arguments in function.............................................................................................40
Call by reference in Python.....................................................................................41
Python Built-in Functions.......................................................................................41
Chapter – 8 My project...........................................................................................47
8.1 All About the project.........................................................................................47

8
Table of Contents.................................................................................................... 47
Python..................................................................................................................... 47
Import Libraries...................................................................................................... 48
Result...................................................................................................................... 50
References.............................................................................................................. 51

9
Chapter-1 IntroductionTo
Python

Python
Python is a general purpose high level programming language. It is simple and easy
to understand language which feels like reading simple English. This pseudo code
nature of python makes it easy to learn and understandable by beginners.
Python is an interpreted, object-oriented, high-level programming language with
dynamic semantics. Its high-level built in data structures, combined with dynamic
typing and dynamic binding, make it very attractive for Rapid Application
Development, as well as for use as a scripting or glue language to connect existing
components together. Python's simple, easy to learn syntax emphasizes readability
and therefore reduces the cost of program maintenance.
History ofpython
Developed by GUIDO VAN ROSSUM at National Research Institute for
mathematics and computer science ,Netherlands.
Namedafter a TVshowcalled―MontyPython‘sFlyingCircus‖andnot
after python thesnake.
VAN ROSSUM is principal author. Benevolent dictator forlife(bdfl).
Python 1.0 released on January1994.
Python 2.0 released on October 16, 2000 with many major new
features garbage collector and support forUnicode.
Python 3.0 released on December 3,2008.
Features ofpython
Easy to code Python is a high-level programming language. Python is very
easy to learn the in python language and anybody can learn python basics
in
a few hours or days. It is also a developer-friendlylanguage.
Free and Open Source Python language is freely available at the official
website and you can download it from the given download link below
click on the Download Python keyword.
Object-Oriented Language One of the key features of python is Object-
Oriented programming. Python supports object-oriented language and
concepts of classes, objects encapsulation,etc.
GUI Programming Support Graphical User interfaces can be made using
10
module such as PyQt5, PyQt4, w x Python, or Tk in python

High-Level Language When we write programs in python, we do not


need
to remember the system architecture, nor do we need to manage the
memory.

Extensible feature We can write us some Python code into C or C++


language and also we can compile that code in C/C++language.

Python is Portable language For example, if we have python code for


windows and if we want to run this code on other platforms such as
Linux, Unix, and Mac then we do not need to change it, we can run this
code on any platform.

Python is Integrated language because we can easily integrate python with


other languages like c, c++,etc.

Interpreted Language because Python code is executed line by line


at a time. like other languages C, C++, Java, etc. there is no need to
compile python code this makes it easier to debug our code. The
source code of python is converted into an immediate form
calledbytecode.

Large Standard Library which provides a rich set of module and functions
so you do not have to write your own code for every single thing. There
are many libraries present in python for such as regular expressions,
unit-testing, web browsers,etc.
Dynamically Typed Language That means the type (for example- int,
double, long, etc.) for a variable is decided at run time not in advance
because of this feature we don‘t need to specify the type ofvariable.

Limitations of python

Speed: Python is an interpreted language and is slow as compared to C/C++


or Java. Unlike C or C++ it‘s not closer to hardware because Python is a
high-level language. As we all know that compilation and execution help to
work normally, but in thiscase,

11
Applications ofpython
 Web Development. Python can be used to make web-applications at a rapid
rate....
 Game Development....
 Machine Learning and Artificial Intelligence....
 Data Science and Data Visualization....
 Desktop GUI....
 Web Scraping Applications. ...
 Business Applications....
 CADApplications.
 Audio and VideoApplications
 Embedded Applications.Etc

Some Pythoneditors
 PyCharm

 Pydev
 Wing
 IDLE
 Vim
 Python tools for Visual Studio ( PTVS)
 Eric Python

1.7Companies using

pythonPython is usedby

 Intel
 IBM
 NASA,
 Pixar
 Netflix

12
CHAPTER -2 VARIABLES AND DATA TYPES

Variable
A variable is a name given to a memory location in a program. One of the most
powerful features of a programming language is the ability to manipulate variables.
A variable is a name that refers to a value.
A Python variable is a reserved memory location to store values. In other words, a
variable in a python program gives data to the computer for processing.
For example : a = 30
b=―govind‖

Rules of declaring variablename

1. Variablenameshouldstartwithletter(a-zA-Z)orunderscore(_).
a. Valid:age,_age,Age
b. Invalid:1age

2. Invariablename,nospecialcharactersallowedotherthanunderscore(_).
a. Valid:age_,_age
b. Invalid:age_*

3. Variablesarecasesensitive.
a. age and Age are different, since variable names are casesensitive.

4. Variable name can have numbers but not at thebeginning.


a. Example:Age1

5. Variable name should not be a Python keyword. Keywords are also called as
reserved words.

Example
pass, break, continue.. etc are reserved for special meaning in Python. So, we
should not declare keyword as a variable name.

13
Lets see the program,( declaring variable)

Program and its output:

DataTypes

Every value in Python has a data type. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of
these classes.
Primarily there is following data type in python:-

1. Numeric: It consist of three type that are describedlows


asfol

Python- data type

numeric dictionary boolean set Seq ue n


ce type

integer Co mple x flo at string list tuple

14
i. Integers: In Python, integers are zero, positive or negative whole
numbers without a fractional part and having unlimited precision, e.g. 0,
100, -10. The followings are valid integer literals in Python.
ii. Floating point numbers: In Python, floating point numbers(float)are positive and
negative real numbers with a fractional part denoted by the
decimal symbol . or the scientific notation E or e, e.g. 1234.56, 3.142, -
1.55,0.23..
iii. Complex number: A complex number is created from real numbers.
Python complex number can be created either using direct assignment
statement or by using complex ()function.
Complex numbers which are mostly used where we are using two real
numbers. For instance, an electric circuit which is defined by voltage(V)
and current(C) are used in geometry, scientific calculations and calculus.
2.Dictionary: Dictionary in Python is an unordered collection of data values, used
to store data values like a map, which, unlike other Data Types that hold only a
single value as an element, Dictionary holds key: value pair. Key-value is provided
in the dictionary to make it more optimized.
3. Booleans: Booleans represent one of two values: True or False.
Set: A Set is an unordered collection data type that is iterable, mutable and has no
duplicate elements. Python‘s set class represents the mathematical notion of a set.
4. Sequence type: it consists of mainly three types that are described as follows
i. Strings: In Python, string is an immutable sequence datatype. It is the
sequence of Unicode characters wrapped inside single, double, or triple
quotes. A string literal can be assigned to a variable.
ii. List: Lists are used to store multiple items in a single variable .
iii. Tuples: Python tuples area data structure that stores an ordered sequence of
values. Tuples are immutable. This means you cannot change the values in a
tuple.

*None: Python Boolean type is one of the built-in data types provided by Python,
which represents one of the two values i.e. True or False.
#python is a fantastic language that automatically identifies the type of data for us

15
Keywords:
The reserved words that convey a special meaning to the compiler / interpreter.
Each keyword has a special meaning and a specific operation. These keywords
can't be used as a variable.
We cannot use a keyword as a variable name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.In Python,
.keywords are case sensitive

There are 33 keywords in Python :


and:Alogicaloperator lambda:Tocreateananonymousfunction

as:Tocreateanalias is:Totestiftwovariablesareequal

assert:Fordebugging in:Tocheckifavalueispresentinalist,tuple,etc.

break:Tobreakoutofaloop import:Toimportamodule

class:Todefineaclass if:Tomakeaconditionalstatement

continue:Tocontinuetothenextiterationofaloop from:Toimportspecificpartsofamodule

def:Todefineafunction from:Toimportspecificpartsofamodule

del:Todeleteanobject for:Tocreateaforloop

elif:Usedinconditionalstatements,sameaselseif finally:Ablockofcodethatwillbeexecutednomatterifthereis
exception
else: Usedinconditionalstatements false: Booleanvalue,resultofcomparisonoperations

none:Representsanullvalue yield:Toendafunction,returnsagenerator

nonlocal:Todeclareanon-localvariable with:Usedtosimplifyexceptionhandling

not:Alogicaloperator while:Tocreateawhileloop

or:Alogicaloperator try:Tomakeatry...exceptstatement

pass: Anullstatement,astatementthatwilldonothing raise: Toraiseanexception

return:Toexitafunctionandreturnavalue true:Booleanvalue,resultofcomparisonoperations

except: Usedwithexceptions,whattodowhenanexceptionoccurs

Operators
Definition: Operators are special symbols that represent computations like
addition and multiplication. The values the operator is applied to are called
operands. For example : 2+3 =5(here 2 and 3 are operands ,+ and = are operator
here .)
Types of operators in python:

16
1. Arithmeticoperators
2. Assignmentoperators
3. Comparisonoperators
4. Logicaloperators
5. Identityoperators
6. Membershipoperators
7. Bitwiseoperators

1. Arithmeticoperator:
These operators are used with numeric values to perform commonmathematical
operationslike addition,subtraction,multiplication,dividationetc.

Operator Name Example


- Subtraction x-y
+ Addition x+y
* Multiplication x*y
/ Division Modulus x/y
% Exponentiation x%y
** Floor division x**y
// x//y

2.Assignmentoperators:
Assignment Operators in Python are used for assigning the value of the right
operand to the left operand. Various assignment operators used in Python are (+=,
– = , *=, /= , etc.).

Operator Example Same As


= X=5 X=5
+= x+=3 x=x+3
-= x-=3 x=x-3
*= x*=3 x=x*3
/= x/=3 x=x/3
%= x%=3 x=x%3
//= x //= 3 x=x//3
**= x **= 3 x=x**3

17
&= x&=3 x=x&3
|= x|=3 x=x|3
^= x^=3 x=x^3
>>= x >>= 3 x=x>>3
<<= x <<= 3 x=x<<3

3. Comparisonoperators:
When we want to compare a value with another value. To do that, we use
comparison operators.
Python has six comparison operators, which are as follows:
Lessthan(<) Notequalto(!=)
Lessthanorequalto(<=) Equal(==)
Greaterthan(>) Greatherthanorequalto(>=)

These comparison operators compare two values and return a boolean value, either
True or False. And you can use these comparison operators to compare both
numbers and strings.
Examples of all six comparison operator :

18
4. Logical operator:
logical operators perform logical operation base on given
condition

Operator Description Example


and True if both are true >>>x=5;y=6
>>> x > 1 and y <10
True
>>>x=5;y=6
or True if at least one is true
>>>x>6ory<10
True

>>>x=5
not Returns True if an
expression evalutes to >>> not x > 1
false and vice-versa False

5. Identity operators:
This operator are used to compare weather two objects are same or not.
Or
Identity operator in python is used to compare the memory location of two
objects. The two identity operators used in Python are (is, is not).
is :Returns true if both variables are the same object
example: x is y
>>> x =5
>>> y =5
>>> x is y
>>> true

is not: Returns true if both variables are not the sameobject


Example:x is not y

19
>>> x = 10
>>> y =15
>>> x is not y
>>> true

6. Membershipoperators:
These operators test for membership in a sequence such as lists, strings or tuples.
There are two membership operators that are used in Python. (in, not in). It gives
the result based on the variable present in specified sequence or string.
Example: For example here we check whether the value of x=4 and value of y=8is
available in list or not, by using in and not inoperators.

Output :

7. Bitwiseoperators:

20
CHAPTER- 3
STRINGS

Definition
String is a data type in python. String is a sequence of character enclosed in
quotes. You can also access the characters one at a time with the bracketoperator.
―String is the technical name for text. To define a block of code as a string, you
need to include it in either double quotes (") or single quotes ('). It doesn’t matter
which you use so as long as you are consistent
.‖
There are some characters you need to be particularly careful with when inputting
them into strings. These include: " ' \
That is because these symbols have special meanings in Python and it can get
confusing if you use them in a string.
If you want to use one of these symbols you need to precede it with a backslash
symbol and then Python will know to ignore the symbol and will treat it as normal
text that is to be displayed.
Strings and Numbers as Variables If you define a variable as a string, even if it
only contains numbers, you cannot later use that string as part of a calculation. If
you want to use a variable that has been defined as a string in a calculation, you
will have to convert the string to a number before it can beused.

Example:

21
Stringslicing:
A string slicing in python can be sliced for getting a part of the string.
Consider the following string:

The index in a string starts from 0 to (length -1) in python. In order slice a string,
we use the following syntax.

Negative Indices: it can also be used as shown in the figure above -1 corresponds
to the (length-1) index, -2 to (length -2).
Slicing with skip value
we can provide a skip value as a part of our slice like this:
word = ―amazing‖
word [1:6:2]
‗mzn‘
Other advanced slicingtechniques:
word=―amazing‖
word[:7] word[0:7] ‗amazing‘
word[0:] word[0:7] ‗amazing‘

22
Stringfunctions
Some of the mostly used functions to perform operations on or manipulate
strings are:
Len function:
Len is a built in function that is used to determine the length of a particular string.
>>> fruit = 'banana'
>>> len(‗fruit‘)
Output:
6
To get the last letter of a string, you might be tempted to try something like this:
>>> length = len(fruit)
>>> last = fruit[length]
Index Error: string index out of range
The reason for the Index Error is that there is no letter in ‘banana‘ with the index 6.
Since we started counting at zero, the six letters are numbered 0 to 5. To get
thelast character, you have to subtract 1 fromlength:
>>> last = fruit[length-1]
>>> print last
a
Alternatively, you can use negative indices, which count backward from the end of
the
string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to
last, and so on.
2. string.endswith(“as”): This function tells whether the variable string ends
withthestring―as‖ornot.ifstringis―vyas‖,itreturnstruefor―as‖since―vyas‖end
swith―as‖.
3. string.count(“c”) : counts the total number of occurrence of anycharacter.
4. string.capitalize(): This function capitalizes the first character of a givenstring.

23
5.string.find(word): Thisfunctionfindsthewordandreturnsindexoffirst
occurrence of that word in thestring.
6. string.replace(oldword,newword): This function replace the old word with
new word in the entire string

Escape sequencecharacter
Sequence of character after backslash ‗\‘ are called as escape sequence characters

Escape sequence character comprises of more than one character character


but represents one character when used within the strings.
Examples: \n,\t, \‘ , \\ ,etc..
\n is used for new line
\t is for tab
\‘ single quote and \\ backslash

24
CHAPTER- 4
Conditional
Statements

After reading this chapter, the reader will be able to


• Use conditional statements inprograms
• Appreciate the importance of the if-elseconstruct
• Use the if-elif-elseladder
• Use the ternaryoperator
• Understand the importance of & and|
• Handle conditional statements using the getconstruct

INTRODUCTION
A conditional control structure is used to execute statement(s) based on some
condition. When the condition is associated with a statement(s) that is true only
then we want to execute the related/associated statement(s) otherwise, we want
to ignore/skip those statement(s). If we want the execution of the statement(s) or
skipping of the statement(s) to happen only once based on the outcome of the
condition, it's preferred to use the conditional control structures. In Python
programming, indentation is the keyfactor.

Therefore, we need to indent the statement(s) properly. We must also note that
Python programming language is case-sensitive and most of the keywords are in
lowercase ( like the keywords if and else must be written in lower case only).
Type of conditionalstatements

Simple ifstatement

Whenever we have a condition to be tested and we need to execute statement(s)


based on a condition then we can use a simple if statement. In the above syntax
25
ifthe condition-1 evaluates to true then statement-1 and statement-2 will be
executed, otherwise, sequential execution continues from statement-p onwards.

26
Syntax:
if (<condition-1>):
statement-1
statement-2
statement-p

Flow chart:

Example: output:

27
4.2.2 if....elsestatement

Whenever we have a situation where we want to test a condition and if the


condition is true we want to execute some statement(s) and when the
condition is not true we want to execute another set of statements, we must
use the if-else statement. As per the above syntax of the if-else statement,
when condition-1 evaluates to true the statement-1 and statement-2 will be
executed and, when the condition-1 evaluates to false the statement-3 and,
statement-4 will be executed. Therefore either of the statement-1 and
statement-2 or statement-3 or statement-4 will be executed but not both.

Syntax:
if(<condition-1>):
statement-1
statement-2
else:
statement-3
statement-4

Flow chart of if-else statements:

28
Example:

4.2.3. if....elif.....elsestatement

When we have more than one condition to be tested then we must use the if-
elif-else statement. The construct of an if-elif-else statement begins with an
if-statement and we can write any number of times elif-statements followed
by a final else-statement (which is optional).
The execution model of the if-elif-else statement is as follows. It will start
by testing the condition-1 in case the condition-1 evaluates to true then the
statement associated with the first condition (statement-block-1) will alone
be executed and after that, the control will branch to statement-q which is
outside the if-elif-else construct. In case the condition-1 evaluates to false,
then
2 the second condition (condition-2) is tested and, in case the condition-
evaluates to true then the statement-block-2 alone will be executed, after
which the control will branch outside the if-elif-else statement (that is to
statement-q). In case the control reaches condition-n it means that the
previous n-1 condition evaluated to false and if the condition-n evaluates to
true then the statement-block-n will be executed otherwise statement-

block-p
will be executed. An if-elif-else construct can be used to avoid multiple if
statements aswell. Syntax:
if(<condition-1>):
statement-block-1
elif(<condition-2>):
statement-block-2
elif(<condition-3>):

29
statement-block-3
.....................
.....................
elif(<condition-n>):
statement-block-n
[else:
statement-block-p]
statement-q

Flowchart if....elif.....else:

Example:

30
4.2.4 Nested-if statement

Whenever we write an if-statement inside another if-statement or


if- statement inside an else-statement is known as a nested-if.

Sample syntax #1

if(<condition-1>):
if(<condition-2>):
statement-1
statement-2

Only if condition-1 and condition-2 both evaluate to true, then statements


1 and 2 will be executed, otherwise not.

Sample syntax #2

if(<condition-1>)
statement-1
statement-2
else:
if(<condition-2>):
statement-3
statement-4

31
flowchart:

Example:

Output:

22
Chapter- 5 List and Tuples

What areLists?

Declaring a List ofNumbers:

For our first list, we’re going to create a list filled with only numbers.
Defining a list is like any other data type; on the left of the operator is the
name of the variable, and on the right is the value. The difference here is that
the value is a set of items declared between square brackets. This is useful
for storing similar information, as you can easily pass around one variable
name that stores several elements. To separate each item within a list, we
simply use commas.
Let‘s try:

Example
# declaring a list of numbers
nums = [5, 10, 15.2, 20]
print(nums)
Output:
[5,10,15.2,20]
Go ahead and run that cell. You‘ll get an output of [5, 10, 15.2, 20]. When a
list is
output, it includes the brackets with it. This current list is made up of three
integers and one float.

Accessing Elements Within aList:

Now that we know how to define a list, we need to take the next step and
understand how to access items within them. In order to access a specific
element within a list, you use an index. When we declare our list variable,
each item is given an index. Remember that indexing in Python starts at zero
and is used with brackets.

Example

23
# accessing elements within a list
Code:
print( nums[1] ) # will output the value at index 1 = 10
Output:
10
Code:
num = nums[2] # saves index value 2 into num
Output:
15.2
Code:
print(num) # prints value assigned to num
Output:
[5,10,15.2,20,25]

Declaring a List of Mixed DataTypes:

Lists can hold any data type, even other lists. Let‘s check out an example of
several data types:
Example:
# declaring a list of mixed data types
num =4.3
data = [num, "word", True] # the power of data collection
print(data)

Output:
[4.3, 'word', True]
This will output [4.3, ‗word‘, True]. It outputs4.3 as the first item because
when the list is defined, it stores the value of num, not theitself.
variable

24
Lists Within Lists:

Let‘s get a little more complex and see how lists can be stored within
another list:
Example:
# understanding lists within lists
data = [5, "book", [ 34, "hello" ], True] # lists can hold any type
print(data)
Output
[5, 'book', [34, 'hello'], True] it saw list with in a list
print( data[2] )
Output
[34, 'hello'] it saw elements of within a list data type
This will output [5, ‗book‘, [34, ‗hello‘], True] and [34,‗hello‘]. The first
output is the entire data variable‘s value, which stores an integer, a string, a
list, and a boolean data type. The second output is the list stored inside of our
data variable, which is located at index 2 and includes an integer and string
data type.

Accessing Lists WithinLists:

In the last cell, we saw how to output the list stored within the data variable.
Now,we‘ll see how we can access the items within the inner list. To access
items within a list normally, we simply use bracket notation and the index
location. When that item is another list, you simply add a second set of
brackets after the first set. Let‘s check out an example and come back to it:

Example
# using double bracket notation to access lists within
lists print( data[2][0] ) # will output 34
Output
34
inner_list = data[2] # inner list will equal [34, 'hello']

25
output
[34, 'hello']
print( inner_list[1] ) # will output 'hello‗
Output
Hello

The first output will be 34. This is because our first index location is
accessing the second index in
location specified is accessing the value in that
integer of 34. The second output is
because we declared a variable to store the value at index 2 of our

is the string

Changing Values in alist:

When you work with lists you need to be able to alter the value of the items
within the list. It‘s like re-declaring a normal variable to a different value,
except you access the index first:

Example:
# changing values in a list through index
data = [5, 10, 15, 20]
print(data)
Output
[5, 10, 15, 20]
# change the value at index 0 - (5 to
100) data[0] = 100
print(data)

Output

26
[100, 10, 15, 20]

Before we altered the value at index 0, it outputs [5, 10,15, 20]. Once we
accessed the zero index and changed its value to 100, however, the list
ended up changing to [100, 10, 15, 20].

Variable StorageLocations:

When variables are declared, the value assigned is put into a location in
memory. These locations have a specific reference ID. It‘s not often you‘ll
need to check the ID of a variable, but for educational purposes, it‘s good to
know how storage works. We would use the id() function to check the
storage location in memory for a variable:
>>>a=[5,10]
>>> print( id(a) ) # large number represents location in memory
Output
44814584
When a list is stored in memory, each item is given its own location.
Changing thevalue using index notation will change the value stored within
that memory block. Now, if a variable‘s value is another variable, like so:
Example
>>> a = [5, 10]
>>>b=a
Output
print(id(b))
40236056
Changing the value at a specific index will change the value for both lists

Copying aList:

27
So how do you create a similar list without altering the original? You copy
it! Let‘s see how:
# using [:] to copy a list
data = [5, 10, 15, 20]
data_copy = data[ : ] # a single colon copies the list
data[0] = 50
print( "data: { }\t data_copy: { }".format(data, data_copy) )
Go ahead and run that cell. The output this time will result in only our data
variable having the first item set to 50. As data_copy was merely a copy of
the list, now we’re able to always keep the original list in tact if we need to
use it again.

Listmethods:
Consider the following list:
L1 = [1,8,7,2,21,15]
 L1.sort(): updates the list to[1,8,7,2,21.15]
 L1.reverse(): updates the list to[15,21,2,7,8,1]
 L1.append(8): adds 8 at the end of thelist
 L1.insert(3,8): this will add 8 at index3.
 L1.pop(2): will delete elements at index 2 and returns itsvalue
 L1.remove(21): will remove 21 from thelist.

Tuples
Python Tuple is used to store the sequence of immutable Python objects. The
tuple is similar to lists since the value of the items stored in the list can be
changed, whereas the tuple is immutable, and the value of the items stored in
the tuple cannot be changed.

Creating a tuple:
28
A tuple can be written as the collection of comma-separated (,) values
enclosed with the small () brackets. The parentheses are optional but it is
good practice to use. A tuple can be defined as follows.

Creating a tuple with single element is slightly different. We will need to put
comma after the element to declare the tuple:

29
A tuple is indexed in the same way as the lists. The items in the tuple can
be accessed by using their specific index value.
Consider the following example of tuple:

Example:
>>tuple1 = (10, 20, 30, 40, 50, 60)
>>print(tuple1)
>>count = 0
>>for i in tuple1:
>>print("tuple1[%d] = %d"%(count, i))
>>count = count+1

Tuple indexing andslicing

The indexing and slicing in the tuple are similar to lists. The indexing in the
tuple starts from 0 and goes to length(tuple) - 1.

30
The items in the tuple can be accessed by using the index [] operator.
Python also allows us to use the colon operator to access multiple items in
the tuple.
Consider the following image to understand the indexing and slicing in
detail.

EXAMPLE:

31
Basic Tupleoperations
The operators like concatenation (+), repetition (*), Membership (in) works in the
same way as they work with the list. Consider the following table for more detail.

Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.

Operator Description Example

Repetition The repetition operator T1*2 = (1, 2,


enablesthetupleelementsto3, 4, 5, 1, 2,
berepeatedmultipletimes. 3, 4, 5)

Concatenation It concatenates the tupleT1+T2 = (1,


mentioned on either side of 2, 3, 4, 5,
the operator. 6, 7,
8,9)
Membership Itreturnstrueifaparticular
print (2 in
item exists in the tuple T1) prints
otherwisefalse True.
Iteration Theforloopisusedtoiterate
for i inT1:
overthetupleelements. print(i)
Output
1
2
3
4
5

Length Itisusedtogetthelengt len(T1) = 5


hof thetuple.

32
Tuple inbuiltfunctions:

SN Function Description

1 cmp(tupl Itcomparestwotuplesandreturns
e1, true if tuple1 is greater than
tuple2) tuple2 otherwisefalse.

2 len(tuple) It calculates the length of the

tuple.
3 max(tuple) It returns the maximum
element ofthe tuple

4 min(tuple) Itreturnstheminimumelementof

the
tuple.
5 tuple(seq)
It converts the specified

sequence to
the tuple.

Where usetuple?
Using tuple instead of list is used in the following scenario.

1. Using tuple instead of list gives us a clear idea that tuple data
isconstant and must not bechanged
2. Tuple can simulate a dictionary without keys. Consider the following
nested structure, which can be used as a dictionary. Forex
[(101, "John", 22), (102, "Mike", 28), (103, "Dustin", 30)]

33
Chapter – 6 Loops in Python
INTRODUCTION
When we were young, we were taught tables of numbers. The table of a
number had a pattern. Writing a table in an examination required writing,
say,―n×‖ followedby ―i‖ (i varyingfrom1ton) andthenthe resultof
calculations (that is n × 1, n × 2 and so on). Many such situations require us
to repeat a given task many times. This repetition can be used to calculate
the value of a function, to print a pattern or to simply repeat something. This
chapter discusses loops and iterations, which are an integral part of
procedural programming. Looping means repeating a set of statements until
a condition
is true. The number of times this set is repeated depends on the test
condition. Also, what is to be repeated needs to be chalked out with due
deliberation.

Looping inpython:
Python programming language provides following types of loops to handle
looping requirements. Python provides three ways for executing the loops.

34
While all the ways provide similar basic functionality, they differ in their
syntax and condition checking time.

WhileLoop:

In python, while loop is used to execute a block of statements repeatedly


until a given a condition is satisfied. And when the condition becomes false,
the line immediately after the loop in program is executed.
A while loop allows code to be repeated an unknown number of times as
long as a condition is being met . this may be 100 times , just the once or
even never . In a while loop the condition is checked before the code is run ,
which means it could skip the loop altogether if the condition is not being
met to start with . It is important , therefore , to make sure the correct
conditions are in place to run the loop before it starts .

Syntax:
while expression:
statement(s)

35
Example code:
Ask the user to enter a number. Keep asking until they enter a value over 5 and
then display the message ―The last number you entered was a [number]‖ and stop
the program.

ForLoop:

A for loop allows Python to keep repeating code a set number of times. It
is sometimesknownasacountingloopbecauseyouknowthenumberof
times the loop will run before itstarts.
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated
programming languages.

36
With the for loop we can execute a set of statements, once for each item in
a list, tuple, set etc.

Flow chart:

Example:
Q44.Ask how many people the user wants to invite to a party. If they enter a
number below 10, ask for the names and after each name display ―[name] has been
invited‖. If they enter a number which is 10 or higher, display the message ―Too
many people”.

37
CHAPTER – 7 FUNCTION IN
PYTHON
Defination
Functions are the most important aspect of an application. A function can be
defined as the organized block of reusable code, which can be called
whenever required.
Python allows us to divide a large program into the basic building blocks
known as a function. The function contains the set of programming
statements enclosed by {}. A function can be called multiple times to
provide reusability and modularity to the Pythonprogram.
The Function helps to programmer to break the program into the smaller

part.
It organizes the code very effectively and avoids the repetition of the code.
As the program grows, function makes the program moreorganized.
Python provide us various inbuilt functions like range() or print(). Although,
the user can create its functions, which can be called user-defined functions.
Types offunctions.

o User-definefunctions - The user-defined functions are those define by


the user to perform the specifictask.
- The built-in functions are those functions that are
o Built-infunctions pre-
defined inPython.

Advantage of Functions in Python:


There are the following advantages of Python functions.

o Usingfunctions,wecanavoidrewritingthesamelogic/codeagainandagain
in aprogram.
o WecancallPythonfunctionsmultipletimesinaprogramandanywhereina
program.
o WecantrackalargePythonprogrameasilywhenitisdividedintomultiple
functions.
o ReusabilityisthemainachievementofPythonfunctions.
o However,FunctioncallingisalwaysoverheadinaPythonprogram.

38
Creating aFunction
Python provides the def keyword to define the function. The syntax of the
define function is given below.

Syntax:

Let's understand the syntax of functions definition.

o Thedefkeyword,alongwiththefunctionnameisusedtodefinethefunction.
o Theidentifierrulemustfollowthefunctionname.
o Afunctionacceptstheparameter(argument),andtheycanbeoptional.
o Thefunctionblockisstartedwiththecolon(:),andblockstatementsmustbe
at the sameindentation.
o Thereturnstatementisusedtoreturnthevalue.Afunctioncanhaveonly
one return
Function Calling

In Python, after the function is created, we can call it from another function.
A function must be defined before the function call; otherwise, the Python
interpreter gives an error. To call the function, use the function name
followed by the parentheses.
Consider the following example of a simple example that prints the message
"Hello World".

Output:

39
The returnstatement
The return statement is used at the end of the function and returns the
result of the function. It terminates the function execution and transfers the
result where the function is called. The return statement cannot be used
outside of the function.

Syntax:

return [expression_list]
It can contain the expression which gets evaluated and value is returned to
the caller function. If the return statement has no expression or does not exist
itself in the function then it returns the None object.
EXAMPLE:
# Defining function
d ef sum ():
a=10
b=20
c = a+b
return c
# calling sum() function in print
statement print("The sum is:",sum())

output:
The sum is: 30

Example 2 Creating function without return statement


# Defining function
d ef sum ():
a=10
b=20
c = a+b
# calling sum() function in print statement
print(sum())

output:
None
40
Arguments infunction
Theargumentsaretypesofinformationwhichcanbepassedintothefunction.
Theargumentsarespecifiedintheparentheses.Wecanpassanynumberof
arguments,buttheymustbeseparatethemwithacomma.

Considerthefollowingexample,whichcontainsafunctionthatacceptsastring
theargument.

Example 1
#defining the
function def func
(name):
print("Hi ",name)
#calling the
function Output:
func("Devansh")
Hi Devansh

Example 2

#Pythonfunctiontocalculatethesumoftwov
ariables #defining the function
def sum (a,b):
return a+b;

#takingvaluesfromtheuser
a = int(input("Enter a: "))
b = int(input("Enter b: "))

#printing the sum of a and b


print("Sum = ",sum(a,b))

Output:

Enter a:10
Enter b:20
Sum= 30

41
Call by reference inPython
In Python, call by reference means passing the actual value as an argument
in the function. All the functions are called by reference, i.e., all the changes
made to the reference inside the function revert back to the original value
referred by thereference.
Example 1 Passing Immutable Object (List)

#defining the function


def change_list(list1):
list1.append(20)
list1.append(30)
print("list inside function = ",list1)

#defining the list


list1 = [10,30,40,50]

#calling the function


change_list(list1)
print("list outside function = ",list1)

Output:

list insidefunction= [10, 30, 40, 50, 20,30]


list outsidefunction= [10, 30, 40, 50, 20,30]

Python Built-inFunctions
The Python built-in functions are defined as the functions whose
functionality is pre-defined in Python. The python interpreter has several
functions that are always present for use. These functions are known as
Built-in Functions. Forexample

Python abs() Function:


The python abs() function is used to return the absolute value of a
number. It takes only one argument, a number whose absolute value is
42
to be returned. The argument can be an integer and floating-point
number. If the argument is a complex number, then, abs() returns its
magnitude.

Python abs() Function Example

# integer number
integer = -20
print('Absolute value of -40 is:', abs(integer))

# floating number
floating = -20.83
print('Absolute value of -40.83 is:', abs(floating))

Output:
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83

43
Chapter – 8 My project

8.1 All About the project

I will show you how to build and design a random password generator using
python. We use built-in modules that comes with Python named random and
array.
We will use List , loop ,array and random module in this project.
The outcome of this project is a 12 character long password which is
unpredictable.

Table of Contents
 Python


Import Modules

 Run theProgram

Python

Python is a general-purpose programming language that is becoming ever more


popular for analyzing data. Python also lets you work quickly and integrate systems
more effectively. Companies from all around the world are utilizing Python to
gather bits of knowledge from their data.

Import Modules

We will use two libraries in this project. And both of them come with Python,
which means we don‘t have to install them. These kind of libraries is called Python
built-in modules.

The main modules we will use is random.


So for this step, all we need to do is to import them to our program:
44
import

random

import array

45
Output :-

46
References

Books:
1) Allen B. Downey - Think Python-O'ReillyMedia
2) Eric Matthes - Python Crash Course_ A Hands-On, Project-Based
Introduction toProgramming.

Web sites:
https://www.geeksforgeeks.org

47
48

You might also like