Practical Training Aruu
Practical Training Aruu
Practical Training Aruu
bhiwadi, Alwar
Submitted in partial fulfillment for the award of
the
Diploma
In
Computer Science &
Engineering
Of
SUBMITTEDBY:
GUIDEDBY:
MR. B.R. MALI DAKSH LIMBA
(LECTURER)
ADAMYA RAJPUROHIT
DR. MURLIDHAR VERMA
KAILASH DAS
(LECTURER)
HARSHIT NATH
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
qualities are very important every field and these for an Engineer, in my
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
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
( 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
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
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
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‖
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.
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)
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:-
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
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
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.
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.).
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
>>>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
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
24
CHAPTER- 4
Conditional
Statements
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
26
Syntax:
if (<condition-1>):
statement-1
statement-2
statement-p
Flow chart:
Example: output:
27
4.2.2 if....elsestatement
Syntax:
if(<condition-1>):
statement-1
statement-2
else:
statement-3
statement-4
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
Sample syntax #1
if(<condition-1>):
if(<condition-2>):
statement-1
statement-2
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?
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.
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]
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.
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
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
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.
32
Tuple inbuiltfunctions:
SN Function Description
1 cmp(tupl Itcomparestwotuplesandreturns
e1, true if tuple1 is greater than
tuple2) tuple2 otherwisefalse.
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:
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 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:
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
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: "))
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)
Output:
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
# 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
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
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.
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