0% found this document useful (0 votes)
171 views

PP-Unit 1-Notes

Python is a high-level, interpreted, interactive and object-oriented programming language that is designed to be highly readable. It was created by Guido van Rossum in the late 1980s. Some key features of Python include being free and open source, simple yet powerful syntax, easy to learn and read, versatile for a wide range of applications, and having a large standard library. Python is well-suited for tasks like software development, system scripting, rapid prototyping, and general purpose programming due to its simplicity, readability, extensive standard library, and ability to interface with other languages.

Uploaded by

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

PP-Unit 1-Notes

Python is a high-level, interpreted, interactive and object-oriented programming language that is designed to be highly readable. It was created by Guido van Rossum in the late 1980s. Some key features of Python include being free and open source, simple yet powerful syntax, easy to learn and read, versatile for a wide range of applications, and having a large standard library. Python is well-suited for tasks like software development, system scripting, rapid prototyping, and general purpose programming due to its simplicity, readability, extensive standard library, and ability to interface with other languages.

Uploaded by

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

Python Programming Unit:1

Basics of Python Jupyter:

Python is a high-level, interpreted, interactive and object-oriented and a


reliable language that is very simple and uses English-like words.
Python is designed to be highly readable. It has fewer syntactical
constructions than other languages.
 Python is Interpreted: Python is processed at runtime by the
interpreter. You do not need to compile your program before
executing it. This is similar to PERL and PHP.
 Python is Interactive: You can actually sit at a Python prompt
and interact with the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented
style or technique of programming that encapsulates code within
objects.
 Python is a Beginner's Language: Python is a great language for
the beginner-level programmers and supports the development of a
wide range of applications from simple text processing to WWW
browsers to games.

History of Python
 Python was developed by Guido van Rossum in the late eighties
and early nineties at the National Research Institute for
Mathematics and Computer Science in the Netherlands.
 Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, Unix shell, and other
scripting languages.
 At the time when he began implementing Python, Guido van
Rossum was also reading the published scripts from "Monty
Python's Flying Circus" (a BBC comedy series from the seventies,
in the unlikely case you didn't know). It occurred to him that he
needed a name that was short, unique, and slightly mysterious, so
he decided to call the language Python.
 Python is now maintained by a core development team at the
institute, although Guido van Rossum still holds a vital role in
directing its progress.
 Python 1.0 was released on 20 February, 1991.
 Python 2.0 was released on 16 October 2000 and had many major
new features, including a cycle detecting garbage collector and

1
Python Programming Unit:1

support for Unicode. With this release the development process


was changed and became more transparent and community-
backed.
 Python 3.0 (which early in its development was commonly
referred to as Python 3000 or py3k), a major, backwards-
incompatible release, was released on 3 December 2008 after a
long period of testing. Many of its major features have been back
ported to the backwards-compatible Python 2.6.x and 2.7.x version
series.
 In January 2017 Google announced work on a Python 2.7 to go
transcompiler, which The Register speculated was in response to
Python 2.7's planned end-of-life.
 Python 3.10.0 was released on Oct 4, 2021.

Python Features:
Python's features include:
 Free and Open Source: Python is an open source software i.e.,
anyone can freely distribute it, read the source code, edit it, and
even use the code to write new (free) programs.
 Simple: Python is a simple and a small language. Reading a
program written in puthon feels almost like reading English.
 Easy-to-learn: Python has few keywords, simple structure, and a
clearly defined syntax. This allows the student to pick up the
language quickly.
 Easy-to-read: Python code is more clearly defined and visible to
the eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 Versatile: Python supports development of a wide range of
applications ranging from simple text processing to WWW
browsers to games.
 High-level language: Python is a high-level language.
 Object Oriented: Python is a powerful language for OOP concepts,
especially when compared to languages like C++ or Java.
 Interpreted: Python program is processed at run-time by the
interpreter. So, there is no need to compile a program before
executing it. We can simply run the program.
 A broad standard library: Python's bulk of the library is very
portable and cross- platform compatible on UNIX, Windows, and

2
Python Programming Unit:1

Macintosh.
 Interactive Mode: Python has support for an interactive mode
which allows interactive testing and debugging of snippets of
code.
 Portable: Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
 Extendable: You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
 Databases: Python provides interfaces to all major commercial
databases.
 GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries, and windows
systems, such as Windows MFC, Macintosh, and the X Window
system of UNIX.
 Multi-threaded: Python supports multi-threading, i.e executing
more than one process of program simultaneously.
 Scalable: Python provides a better structure and support for large
programs than shell scripting.
 Robust: Python programmers cannot manipulate memory directly.
For every syntactical mistake, a simple and easy to interpret
message is displayed.

Need of Python Programming


 Software quality
Python code is designed to be readable, and hence reusable
and maintainable— much more so than traditional scripting
languages. The uniformity of Python code makes it easy to
understand, even if you did not write it. In addition, Python has
deep support for more advanced software reuse mechanisms, such
as object-oriented (OO) and function programming.
 Developer productivity
Python boosts developer productivity many times beyond
compiled or statically typed languages such as C, C++, and Java.
Python code is typically one-third to less to debug, and less to
maintain after the fact. Python programs also run immediately,
without the lengthy compile and link steps required by some other
tools, further boosting programmer speed. Program portability

3
Python Programming Unit:1

Most Python programs run unchanged on all major computer


platforms. Porting Python code between Linux and Windows, for
example, is usually just a matter of copying a script‘s code
between machines.
 Support libraries
Python comes with a large collection of prebuilt and
portable functionality, known as the standard library. This library
supports an array of application-level programming tasks, from
text pattern matching to network scripting. In addition, Python can
be extended with both home grown libraries and a vast collection
of third-party application support software. Python‘s third-party
domain offers tools for website construction, numeric
programming, serial port access, game development, and much
more (see ahead for a sampling).
 Component integration
Python scripts can easily communicate with other parts of an
application, using a variety of integration mechanisms. Such
integrations allow Python to be used as a product customization
and extension tool. Today, Python code can invoke C and C++
libraries, can be called from C and C++ programs, can integrate
with Java and .NET components, can communicate over
frameworks such as COM and Silverlight, can interface with
devices over serial ports, and can interact over networks with
interfaces like SOAP, XML-RPC, and CORBA. It is not a
standalone tool.
 Enjoyment
Because of Python‘s ease of use and built-in toolset, it can
make the act of programming more pleasure than chore. Although
this may be an intangible benefit, its effect on productivity is an
important asset. Of these factors, the first two (quality and
productivity) are probably the most compelling benefits to most
Python users, and merit a fuller description.
 It's Object-Oriented
Python is an object-oriented language, from the ground up.
Its class model supports advanced notions such as polymorphism,
operator overloading, and multiple inheritance; yet in the context
of Python's dynamic typing, object-oriented programming (OOP)

4
Python Programming Unit:1

is remarkably easy to apply. Python's OOP nature makes it ideal as


a scripting tool for object-oriented systems languages such as C++
and Java. For example, Python programs can subclass (specialized)
classes implemented in C++ or Java.
 It's Free
Python is freeware—something which has lately been come
to be called open source software. As with Tcl and Perl, you can
get the entire system for free over the Internet. There are no
restrictions on copying it, embedding it in your systems, or
shipping it with your products. In fact, you can even sell Python, if
you're so inclined. But don't get the wrong idea: "free" doesn't
mean "unsupported". On the contrary, the Python online
community responds to user queries with a speed that most
commercial software vendors would do well to notice.
 It's Portable
Python is written in portable ANSI C, and compiles and runs
on virtually every major platform in use today. For example, it
runs on UNIX systems, Linux, MS-DOS, MS-Windows (95, 98,
NT), Macintosh, Amiga, Be-OS, OS/2, VMS, QNX, and more.
Further, Python programs are automatically compiled to portable
bytecode, which runs the same on any platform with a compatible
version of Python installed (more on this in the section "It's easy to
use"). What that means is that Python programs that use the core
language run the same on UNIX, MS-Windows, and any other
system with a Python interpreter.
 It's Powerful
From a features perspective, Python is something of a
hybrid. Its tool set places it between traditional scripting languages
(such as Tcl, Scheme, and Perl), and systems languages (such as C,
C++, and Java). Python provides all the simplicity and ease of use
of a scripting language, along with more advanced programming
tools typically found in systems development languages.
 Automatic memory management
Python automatically allocates and reclaims ("garbage
collects") objects when no longer used, and most grow and shrink
on demand; Python, not you, keeps track of low- level memory
details.

5
Python Programming Unit:1

 Programming-in-the-large support
Finally, for building larger systems, Python includes tools
such as modules, classes, and exceptions; they allow you to
organize systems into components, do OOP, and handle events
gracefully.
 It's Mixable
Python programs can be easily "glued" to components
written in other languages. In technical terms, by employing the
Python/C integration APIs, Python programs can be both extended
by (called to) components written in C or C++, and embedded in
(called by) C or C++ programs. That means you can add
functionality to the Python system as needed and use Python
programs within other environments or systems.

 It's Easy to Use


For many, Python's combination of rapid turnaround and
language simplicity make programming more fun than work. To
run a Python program, you simply type it and run it. There are no
intermediate compile and link steps (as when using languages such
as C or C++). As with other interpreted languages, Python
executes programs immediately, which makes for both an
interactive programming experience and rapid turnaround after
program changes. Strictly speaking, Python programs are compiled
(translated) to an intermediate form called bytecode, which is then
run by the interpreter.
 It's Easy to Learn
This brings us to the topic of this book: compared to other
programming languages, the core Python language is amazingly
easy to learn. In fact In fact, you can expect to be coding
significant Python programs in a matter of days (and perhaps in
just hours, if you're already an experienced programmer).
 Internet Scripting
Python comes with standard Internet utility modules that
allow Python programs to communicate over sockets, extract form
information sent to a server-side CGI script, parse HTML, transfer
files by FTP, process XML files, and much more. There are also a
number of peripheral tools for doing Internet programming in
6
Python Programming Unit:1

Python. For instance, the HTMLGen and pythondoc systems


generate HTML files from Python class-based descriptions, and
the JPython system mentioned above provides for seamless
Python/Java integration.
 Database Programming
Python's standard pickle module provides a simple object-
persistence system: it allows programs to easily save and restore
entire Python objects to files. For more traditional database
demands, there are Python interfaces to Sybase, Oracle, Informix,
ODBC, and more. There is even a portable SQL database API for
Python that runs the same on a variety of underlying database
systems, and a system named gadfly that implements an SQL
database for Python programs.
 Image Processing, AI, Distributed Objects, Etc.
Python is commonly applied in more domains than can be
mentioned here. But in general, many are just instances of Python's
component integration role in action. By adding Python as a
frontend to libraries of components written in a compiled language
such as C, Python becomes useful for scripting in a variety of
domains. For instance, image processing for Python is
implemented as a set of library components implemented in a
compiled language such as C, along with a Python front-end layer
on top used to configure and launch the compiled components.

Who Uses Python Today?


1. Google makes extensive use of Python in its web search systems.
2. The popular YouTube video sharing service is largely written in
Python.
3. The Dropbox storage service codes both its server and desktop
client software primarily in Python.
4. The Raspberry Pi single-board computer promotes Python as its
educational language.
5. The widespread BitTorrent peer-to-peer file sharing system began
its life as a Python program.
6. Google‘s App Engine web development framework uses Python

7
Python Programming Unit:1

as an application language.
7. Maya, a powerful integrated 3D modeling and animation system,
provides a Python scripting API.
8. Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use
Python for hardware testing.
9. NASA, Los Alamos, Fermilab, JPL, and others use Python for
scientific programming tasks.

Byte code Compilation:


Python first compiles your source code (the statements in your
file) into a format known as byte code. Compilation is simply a
translation step, and byte code is a lower-level, platform independent
representation of your source code. Roughly, Python translates each of
your source statements into a group of byte code instructions by
decomposing them into individual steps. This byte code translation is
performed to speed execution —byte code can be run much more
quickly than the original source code statements in your text file.

The Python Virtual Machine:

Once your program has been compiled to byte code (or the byte
code has been loaded from existing .pyc file), it is shipped off for
execution to something generally known as the python virtual machine
(PVM).
Applications of Python:
Python is a high-level general purpose programming language that is
used to develop a wide range of applications including
1. Systems Programming
2. GUIs
3. Internet Scripting
4. Component Integration
5. Database Programming
6. Rapid Prototyping

8
Python Programming Unit:1

7. Numeric and Scientific Programming


8. Games
9. Network programming

What Are Python’s Technical Strengths?


1. It‘s Object-Oriented and Functional
2. It‘s Free
3. It‘s Portable
4. It‘s Powerful
5. It‘s Mixable
6. It‘s Relatively Easy to Use
7. It‘s Relatively Easy to Learn

Limitations of Python
Speed -
Python is slower than C or C++.
Mobile Development
Python is not a very good language for mobile development . It is
seen as a weak language for mobile computing. This is the reason very
few mobile applications are built in it like Carbonnelle.
Memory Consumption
Python is not a good choice for memory intensive tasks. Due to
the flexibility of the data-types, Python's memory consumption is also
high.
Database Access
As compared to the popular technologies like JDBC and ODBC,
the Python's database access layer is found to be bit underdeveloped
and primitive . However, it cannot be applied in the enterprises that
need smooth interaction of complex legacy data .
Runtime Errors
Python programmers cited several issues with the design of the
language. Because the language is dynamically typed , it requires more
testing and has errors that only show up at runtime .

Application Basics of Python Programming Using the REPL(shell)

REPL(Read Evaluate Print Loop): 

Running Python:
Python is also considered as an interpreted language because Python programs

9
Python Programming Unit:1

are executed by an interpreter. Python shell can be used in two ways,


viz., interactive mode and script mode.

Interactive Mode:

Interactive Mode, as the name suggests, allows us to interact with OS. Hear,
when we type Python statement, interpreter displays the result(s)
immediately. That means, when we type Python expression / statement /
command after the prompt (>>>), the Python immediately responses with the
output of it.

Let's see what will happen when we type print "WELCOME TO PACEITS" after
the prompt.

>>>print "WELCOME TO KMIT “

WELCOME TO KMIT

Example:

>>> print 5+10

15

>>> x=10

10
Python Programming Unit:1

Note: Python, in interactive mode, is good enough to learn, experiment


or explore, but its only drawback is that we cannot save the statements
and have to retype all the statements once again to re-run them.

Script Mode:

In script mode, we type Python program in a file and then use


interpreter to execute the content of the file. Working in interactive
mode is convenient for beginners and for testing small pieces of code,
as one can test them immediately. But for coding of more than few
lines, we should always save our code so that it can be modified and
reused.

Example: Input any two numbers to find Quotient and Remainder.

a. Running Python Scripts in IDLE:


 Run the program by pressing F5 or RunRun Module.

11
Python Programming Unit:1

Output:

Interacting with Python through an IDE

An Integrated Development Environment (IDE) is an application that


more or less combines all the functionality you have seen so far. IDEs
usually provide REPL capability as well as an editor with which you
can create and modify code to then submit to the interpreter for
execution.

You may also find cool features such as:

 Syntax highlighting: IDEs often colorize different syntax elements


in the code to make it easier to read.
 Context-sensitive help: Advanced IDEs can display related
information from the Python documentation or even suggested fixes
for common types of code errors.
 Code-completion: Some IDEs can complete partially typed pieces
of code (like function names) for you—a great time-saver and
convenience feature.
 Debugging: A debugger allows you to run code step-by-step and
inspect program data as you go. This is invaluable when you are trying
to determine why a program is behaving improperly, as will inevitably
happen.

IDLE
Most Python installations contain a rudimentary IDE called IDLE. The
name ostensibly stands for Integrated Development and Learning

12
Python Programming Unit:1

Environment, but one member of the Monty Python troupe is


named Eric Idle, which hardly seems like a coincidence.

The procedure for running IDLE varies from one operating system to
another.

Starting IDLE in Windows


Go to the Start menu and select All Programs or All Apps. There
should be a program icon labeled IDLE (Python 3.x 32-bit) or
something similar. This will vary slightly between Win 7, 8, and 10.
The IDLE icon may be in a program group folder named Python 3.x.
You can also find the IDLE program icon by using the Windows search
facility from the start menu and typing in IDLE.

Click on the icon to start IDLE.

Using IDLE
Once IDLE is installed and you have started it successfully, you should
see a window titled Python 3.x.x Shell, where 3.x.x corresponds to
your version of Python:

The  >>> prompt
should look
familiar. You
can type REPL
commands
interactively,
just like when you
started the
interpreter
from a
console
window. Mindful of the qi of the universe, display Hello,
World! again:

13
Python Programming Unit:1

The interpreter behaves more or less the same as when you ran it
directly from the console. The IDLE interface adds the perk of
displaying different syntactic elements in distinct colors to make things
more readable.

It also provides context-sensitive help. For example, if you


type print( without typing any of the arguments to the print function
or the closing parenthesis, then flyover text should appear specifying
usage information for the print() function.

One other feature IDLE provides is statement recall:

 If you have typed in several statements, you can recall them


with  Alt + P  and  Alt + N  in Windows or Linux.
 Alt + P  cycles backward through previously executed
statements;  Alt + N cycles forward.
 Once a statement has been recalled, you can use editing keys on
the keyboard to edit it and then execute it again. The corresponding
commands in macOS are  Cmd + P and  Cmd + N .

You can also create script files and run them in IDLE. From the Shell
window menu, select File → New File. That should open an additional
editing window. Type in the code to be executed:

14
Python Programming Unit:1

From the menu in that window, select File → Save or File → Save


As… and save the file to disk. Then select Run → Run Module. The
output should appear back in the interpreter Shell window:

OK, that’s probably enough Hello, World!. The qi of the universe


should be safe.

Once both windows are open, you can switch back and forth, editing
the code in one window, running it and displaying its output in the
other. In that way, IDLE provides a rudimentary Python development
platform.

Running Python:
b. Running Python Interpreter:
Python comes with an interactive interpreter. When you type

15
Python Programming Unit:1

python in your shell or command prompt, the python interpreter


becomes active with a >>> prompt and waits for your commands.

Now you can type any valid python expression at the prompt.
Python reads the typed expression, evaluates it and prints the result.

c. Running python scripts in Command Prompt:


 Before going to run we have to check the PATH in environment
variables.
 Open your text editor, type the following text and save it as
hello.py.
print "hello"

 And run this program by calling python hello.py. Make sure you
change to the directory where you saved the file before doing it.

16
Python Programming Unit:1

Python Comments

Comments in Python are the lines in the code that are ignored by the
interpreter during the execution of the program. Comments enhance
the readability of the code and help the programmers to understand the
code very carefully. There are three types of comments in Python – 
 Single line Comments
 Multiline Comments
 Docstring Comments

Single-Line Comments
Python single-line comment starts with the hashtag symbol (#) with no
white spaces and lasts till the end of the line. If the comment exceeds
one line then put a hashtag on the next line and continue the comment.
Python’s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions. See
the following code snippet demonstrating single line comment:
Example:
# Hello World Demo
Print(“Hello World”)
Multi-Line Comments
Python does not provide the option for multiline comments. However,
there are different ways through which we can write multiline
comments.

Using Multiple Hashtags (#)

We can multiple hashtags (#) to write multiline comments in Python.


Each and every line will be considered as a single-line comment.
Example: Multiline comments using multiple hashtags (#)
 Python3

# Python program to demonstrate

# multiline comments

print("Multiline comments")

17
Python Programming Unit:1

Output

Multiline comments

Using String Literals

Python ignores the string literals that are not assigned to a variable so
we can use these string literals as a comment. 

Example 1:
 Python3

'This will be ignored by Python'

On executing the above code we can see that there will not be any
output so we use the strings with triple quotes(“””) as multiline
comments.

Example 2: Multiline comments using string literals

 Python3

""" Python program to demonstrate

 multiline comments"""

print("Multiline comments")

Output

Multiline comments

Python Docstring
Python docstring is the string literals with triple quotes that are
appeared right after the function. It is used to associate documentation
that has been written with Python modules, functions, classes, and
methods. It is added right below the functions, modules, or classes to
18
Python Programming Unit:1

describe what they do. In Python, the docstring is then made available
via the __doc__ attribute.
Example:
 Python3

def multiply(a, b):

    """Multiplies the value of a and b"""

    return a*b

# Print the docstring of multiply function

print(multiply.__doc__)

Output: 
Multiplies the value of a and b
Variables:
Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in
memory.

We use objects (variables) to capture data, which then can be


manipulated by computer to provide information. By now, we know
that object/variable is a name which refers to a value.

Every object has:

An Identity,

A type, and

A value.

A. Identity of the object is its address in memory and does not get
change once it is created. We may know

19
Python Programming Unit:1

it by typing id (variable)

We would be referring to objects as variable for now.

B. Type (i.e data type) is a set of values, and the allowable operations
on those values.
C. Value: Value is any number or a letter or string. To bind value
to a variable, we use assignment operator (=).

Rules for creating variables in Python:


 A variable name must start with a letter or the underscore character.
 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
 Variable names are case-sensitive (name, Name and NAME are
three different variables).
 The reserved words(keywords) cannot be used naming the variable.

Assigning Values to Variables


Python variables do not need explicit declaration to reserve
memory space. The declaration happens automatically when you
assign a value to a variable. The equal sign (=) is used to assign values
to variables.
The operand to the left of the = operator is the name of the
variable and the operand to the right of the = operator is the value
stored in the variable.

For example –
Program for assignments to variables

a = 100 # An integer assignment


avg = 75.3 # A floating point
name = "John" # A string
print(a)
print(avg)
print(name)

20
Python Programming Unit:1

Multiple Assignments to variables:


Python allows you to assign a single value to several variables
simultaneously.
For example –
a=b=c=1
Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location. You can also
assign multiple objects to multiple variables.
For example –
a, b, c = 1, 2.5, ”KMIT”
Here, two integer objects with values 1 and 2 are assigned to
variables a and b respectively, and one string object with the value
"KMIT" is assigned to the variable c.

Program for multiple assignments to variable

x=y=z=0
print(x)
print(y)
print(z)

In this example, all three of the variables (x, y, and z) are


assigned to the same memory location.
They are each equal to the value of 0.

Variables : Delete

● Deleting the variables after you have finished using it.

● If you've finished with a variable in your program then it should

be destroyed and the memory it occupied will be released when you

exit from your program.

● In many languages, variables within named blocks of code have an

even shorter "shelf life“.

● In languages like C, C++, Java , PHP variable used within a function will
be lost once you leave the function.

21
Python Programming Unit:1

● But what if I've got a long-running program and I want to release

the memory that a variable occupies once I've finished with it?

● Most languages support TWO ways of getting rid of variables:

a) You can set the variable to being empty (None).

In this case, the variable name still exists but it contains no data,

so what might previously have been a memory hog is shrunk to virtually


nothing

b) You can actually remove (del) the variable name itself from the
symbol table,

so that the very name ceases to exist.

Getting rid of variables after you have finished with them

Python

To set a variable to empty, assign None to it:

queue = None

To destroy a variable, use the del keyword:

del queue

Example:

>>> a = 1

>>> a

>>> a = None

>>> a

>>> del a

>>> a

22
Python Programming Unit:1

Traceback (most recent call last): File "<stdin>", line 1, in <module>

NameError: name 'a' is not defined

KEYWORDS
The following list shows the Python keywords. These are
reserved words and you cannot use them as constant or variable or any
other identifier names. All the Python keywords contain lowercase

letters only.
INPUT Function: input()
To get input from the user you can use the input function. When
the input function is called the program stops running the program,
prompts the user to enter something at the keyboard by printing a
string called the prompt to the screen, and then waits for the user to
press the Enter key. The user types a string of characters and presses
enter. Then the input function returns that string and Python continues
running the program by executing the next statement after the input
statement.
Python provides the function input(). input has an optional
parameter, which is the prompt string.
Syntax: input([optional])
For example,
>>> name=input()
pace
>>> print(name)

OUTPUT function: print()


The print() function prints the given object to the standard output device
(screen) or to the text stream file.
The actual syntax of the print() function is

23
Python Programming Unit:1

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)


Here, objects is the value(s) to be printed.
The sep separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line ( \n ).

# Python program to swap two variables


# To take input from the user
x = input('Enter value of x: ')
y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x=y
y = temp
print('The value of x after swapping: ',x)
print('The value of y after swapping: ',y)

Output
Enter value of x:5
'Enter value of y:10
The value of x after swapping: 10
The value of y after swapping: 5

Indentation
Code blocks are identified by indentation rather than using
symbols like curly braces. Without extra symbols, programs are easier
to read. Also, indentation clearly identifies which block of code a
statement belongs to. Of course, code blocks can consist of single
statements, too. When one is new to Python, indentation may come as
a surprise. Humans generally prefer to avoid change, so perhaps after
many years of coding with brace delimitation, the first impression of
using pure indentation may not be completely positive. However,
recall that two of Python's features are that it is simplistic in nature and
easy to read.

Most of the programming languages like C, C++, Java use braces { } to


define a block of code. Python uses indentation. A code block (body of
a function, loop etc.) starts with indentation and ends with the first
unindented line.

Python does not support braces to indicate blocks of code for

24
Python Programming Unit:1

class and function definitions or flow control. Blocks of code are


denoted by line indentation. All the continuous lines indented with
same number of spaces would form a block. Python strictly follow
indentation rules to indicate the blocks.

Numbers:

DATA TYPES

Python data types are:

25
Python Programming Unit:1

1. Number: Number data type stores Numerical Values. This data


type is immutable i.e. value of its object cannot be changed.

2. None: This is special data type with a single value. It is used to


signify the absence of value/false in a situation. It is represented by None.

3. Sequence: A sequence is an ordered collection of items, indexed by


positive integers. It is a combination of mutable (a mutable variable is
one, whose value may change) and immutable (an immutable variable is
one, whose value may not change) data types. There are three types of
sequence data type available in Python, they are Strings, Lists & Tuples.

3.1 Strings: A string is a contiguous set of characters. They are


enclosed in single quotes (' ') or double quotes ('' ").

3.2 Lists: List is also a sequence of values of any type. Values in the
list are called elements / items. These are mutable and
indexed/ordered. List is enclosed in square brackets ([]).

3.3 Tuples: Tuples are a sequence of values of any type and


are indexed by integers. They are immutable. Tuples are enclosed in
().

4. Sets: Set is unordered collection of values of any type with no duplicate


entry. It is immutable.

5.Mapping: This data type is unordered and mutable. Dictionaries fall under
Mappings.

5.1Dictionaries:

It can store any number of python objects. What they store is a key -
value pairs, which are accessed using key. Dictionary is enclosed in
curly brackets ({}).

Operators:
1. Arithmetic Operators

26
Python Programming Unit:1

2. Comparison (Relational) Operators


3. Assignment Operators
4. Logical Operators, Bitwise Operators
5. Membership Operators
6. Identity Operators
1.1. Arithmetic Operators

Operator Description Example


a+b=
+ Addition Adds values on either side of the 30
operator.
Subtracts right hand operand
- Subtraction from left a – b = -10
hand operand.
Multiplies values on either side
* of the a * b = 200
Multiplicatio
n operator
Divides left hand operand by right
/ Division hand b/a=2
operand
Divides left hand operand by right
% Modulus hand b%a=0
operand and returns
remainder
Performs exponential (power) a**b =10 to
** Exponent calculation the
power
on operators 20
Floor Division - The division of 9//2 = 4
// operands and
Floor where the result is the quotient in
Division which 9.0//2.0 = 4.0

27
Python Programming Unit:1

the digits after the decimal point


are

removed.

a = 21

b = 10

c=0

c=a+b

print("a+b=",c
)

c=a-b

print("a-
b=" ,c)

c=a*b

print("a*b=" ,c
)

c=a/b
print("a/
b=" ,c)
c=a%b

print("a%b=",
c)

a=2b=3
c = a**b
print("a pow b=", c) a = 10
b=5
c = a//b
print("a//b=" ,c)

Output

28
Python Programming Unit:1

a+b= 31
a-b= 11
a*b= 210
a/b= 2.1
a%b= 1
a pow b= 8
a//b= 2

2. 1.2. Relational Operators


These operators compare the values on either sides of them and decide
3. the relation among them. They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then:

Operat
or Description Example

If the values of two operands are equal,


== then the (a == b) is not true.
condition becomes true.
If values of two operands are not
!= equal, then (a != b) is true.
condition becomes true.
If values of two operands are not (a <> b) is true. This
<> equal, then is
similar to !=
condition becomes true. operator.
If the value of left operand is greater than
> the (a > b) is not true.
value of right operand, then condition
becomes

true.
If the value of left operand is less than the
< value of (a < b) is true.

29
Python Programming Unit:1

right operand, then condition becomes


true.
If the value of left operand is greater than
>= or equal (a >= b) is not true.
to the value of right operand, then
condition

becomes true.
If the value of left operand is less than or
<= equal to (a <= b) is true.
the value of right operand, then
condition

becomes true.

Ex::

a = 21

b = 10
if ( a == b ):
print( "Line 1 - a is equal to b")
else:
print( "Line 1 - a is not equal to b")
Output:
Line 1 - a is not equal to b
1.3 Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then:

Operator Description Example


Assigns values from right side c = a + b
= operands to assigns
value of a + b
left side operand into c
It adds right operand to the left c += a is
+= operand and equivalent

30
Python Programming Unit:1

to c = c +
assign the result to left operand a
It subtracts right operand from the c -= a is
-= left equivalent
operand and assign the result to left to c = c -
Subtract operand a

It multiplies right operand with the c *= a is


*= left equivalent
operand and assign the result to left to c = c *
Multiply operand a

It divides left operand with the right c /= a is


/= operand equivalent
to c = c /
Divide and assign the result to left operand a
It takes modulus using two %
%= operands and c = a is
equivalent to c =
Modulus assign the result to left operand c

%
a
*
Performs exponential (power) *
**= calculation on c = a is
operators and assign value to the left equivalent to c =
Exponent operand c

*
*
a
//= It performs floor division on operators c //= a is

31
Python Programming Unit:1

and equivalent
to c = c //
Floor assign value to the left operand a

Division

Example:
4. a = 21 b = 10 c = 0
c=a+b
print( "Line 1 - Value of c is ", c )
c += a
print ("Line 2 - Value of c is ", c )
5. c *= a
print ("Line 3 - Value of c is ", c)
c /= a
print( "Line 4 - Value of c is ", c )
c=2
c %= a
print ("Line 5 - Value of c is ", c )
c **= a
print( "Line 6 - Value of c is ", c)
c //= a
print ("Line 7 - Value of c is ", c)

Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

1.4 Python Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation.

Assume if a = 60; and b = 13;


Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
32
Python Programming Unit:1

-----------------

a&b = 0000 1100


a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language

Operato
r Description Example
Operator copies a bit to the result
& if it (a & b) = 12
Binary AND exists in both operands. (means 0000 1100)
It copies a bit if it exists in
| Binary OR either (a | b) = 61
operand. (means 0011 1101)
It copies the bit if it is set in one
^ Binary XOR operand (a ^ b) = 49 (means 0011 0001)
but not both.
It is unary and has the effect of
~ 'flipping' (~a ) = -61 (means 1100 0011 in 2's
O
n
e complement form due to a signed
Binary sbits. binary

Complement number.
The left operands value is moved
<< left by a << 2 = 240
Binary Left the number of bits specified by the
Shift right (means 1111 0000)

33
Python Programming Unit:1

operand.
The left operands value is moved
>> right a >> 2 = 15
R
i
g
h
t

S
h
Binary i
right fby the number of bits specified by
shift tthe right operand (means 0000 1111)

Example:

a = 60 # 60 = 0011 1100

b = 13# 13 = 0000 1101

c=0

c = a & b; # 12 = 0000 1100

print("a&b=",c)

c = a | b; # 61 = 0011 1101

print("a|b=",c)

c = a ^ b; # 49 = 0011 0001

print("a^b=",c)

c = ~a; # -61 = 1100 0011

print("~a=",c)

34
Python Programming Unit:1

c = a << 2; # 240 = 1111 0000

print("a<<2",c)

c = a >> 2; # 15 = 0000 1111

print("a>>2",c)

Output:

#a&b= 12

#a|b= 61

#a^b= 49

#~a= -61

#a<<2 240

#a>>2 15

1. 5 Python Logical Operators

There are following logical operators supported by Python language.


Assume variable a holds 10 and variable b holds 20 then:

Operator Description Example


If both the operands are true then
and condition (a and b) is true.
(Logical becomes true.

AND)
If any of the two operands are non-
or zero (a or b) is true.
(Logical then condition becomes true.

OR)

35
Python Programming Unit:1

Used to reverse the logical state Not (a and b) is


not of its false.
(Logical operand.

NOT)

1.6 Python Membership Operators

Python‘s membership operators test for membership in a sequence,


such as strings, lists, or tuples.
There are two membership operators as explained below:

Operator Description Example

Evaluates to true if it finds a variable in x in y, here in results in a


in the 1 if
x is a member of
specified sequence and false otherwise. sequence y.
not Evaluates to true if it does not finds a x not in y, here not in
in variable in results
in a 1 if x is not a member
the specified sequence and false otherwise. of

sequence y.

1.7 Python Identity Operators

Identity operators compare the memory locations of two objects.


There are two Identity operators as explained below:

Operato
r Description Example

36
Python Programming Unit:1

Evaluates to true if the variables on either x is y, here is results in 1


is side of if
the operator point to the same object and
false id(x) equals id(y).

otherwise.
is
no Evaluates to false if the variables on either x is not y, here is not
t side of results
the operator point to the same object
and true in 1 if id(x) is not equal to

otherwise. id(y).

2. Expressions and order of evaluations

Python Operators Precedence

The following table lists all operators from highest precedence to


lowest

Operator Description
** Exponentiation (raise to the power)
Ccomplement, unary plus and
~+- minus (method
names for the last two are +@ and -
@)
Multiply, divide, modulo and floor
* / % // division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'

37
Python Programming Unit:1

Bitwise exclusive `OR' and regular


^| `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //=
-= += Assignment operators
*= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators

Operator precedence affects how an expression is evaluated.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because


operator * has higher precedence than +, so it first multiplies 3*2 and
then adds into 7. Here, operators with the highest precedence appear
at the top of the table, those with the lowest appear at the bottom.

a = 20

b = 10

c = 15

d=5

e=0

e = (a + b) * c #( 30 *
/d 15 ) / 5

print ("Value of (a + b) * c / d
is ", e)

e = ((a + b) * # (30 * 15

38
Python Programming Unit:1

c) / d )/5

print ("Value of ((a + b) * c) / d


is ", e)

e = (a + b) * # (30) *
(c / d); (15/5)

print( "Value of (a + b) * (c / d)
is ", e)

e = a + (b * c) # 20 +
/ d; (150/5)

print("Value of a + (b * c) / d is ", e)

When you execute the above program, it produces the following result:

Value of (a + b) * c / d is 90

Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50

Conditional Statements and Loops:


if Statement

syntax:-
if test expression:
statement(s)

the program evaluates the test expression and will execute


statement(s) only if the text expression is True.
If the text expression is False, the statement(s) is not executed.

39
Python Programming Unit:1

In Python, the body of the if statement is indicated by the indentation.


Body starts with an indentation and the first unindented line marks the
end.
Python interprets non-zero values as True. None and 0 are interpreted
asFalse.

Program

a = int(input(“enter a value”))
b = int(input(“enter b value”))
if a == b:
print('yes')

if...else Statement
syntax:-

if test expression:
Body of if
else:
Body of else

The if..else statement evaluates test expression and will


execute body ofif only when test condition is True.
If the condition is False, body of else is executed. Indentation is
used to separate the blocks.

Write a program to find larger of two numbers

a=int(input(“enter the value of a: “))


b=int(input(“enter the value of b: “))

if a>b:
large=a
else:
large=b
print(large)

40
Python Programming Unit:1

if...elif...else
syntax:-

if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

The elif is short for else if. It allows us to check for multiple


expressions.
If the condition for if is False, it checks the condition of the
next elifblock and so on.
If all the conditions are False, body of else is executed.
Only one block among the several if...elif...else blocks is
executed according to the condition.
The if block can have only one else block. But it can have
multiple elifblocks.

Write a program to determine whether the character entered is a


vowel or not

ch=input(“enter any character : “)


if ch==”A” or ch==”E” or ch==”I” or ch==”O” or ch==”U”:
print(ch, “is a vowel”)
elif ch==”a” or ch=”e” or ch==”i” or ch==”o” or ch==”u”:
print(ch,”is a vowel”)
else:
print(ch, “is not a vowel”)

Nested if statements
We can have a if...elif...else statement inside
another if...elif...elsestatement. This is called nesting in computer
programming.

41
Python Programming Unit:1

Any number of these statements can be nested inside one another.


Indentation is the only way to figure out the level of nesting. This can
get confusing, so must be avoided if we can.

for loop

The for loop in Python is used to iterate over a sequence


(list, tuple, string) or other iterable objects. Iterating over a sequence is
called traversal.

Syntax of for Loop

for val in sequence:


Body of for

Here, val is the variable that takes the value of the item inside the
sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of
for loop is separated from the rest of the code using indentation.

example:-
# Program to find the sum of all numbers stored in a list

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]


sum = 0

# iterate over the list


for val in numbers:
sum = sum+val
print("The sum is", sum) # Output: The sum is 48
Program to check if a number is a Perfect number.

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


sum1 = 0
for i in range(1, n):
if(n % i == 0):

42
Python Programming Unit:1

sum1 = sum1 + i
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")

Output

Enter any number: 6


The number is a Perfect number

The range() function

We can generate a sequence of numbers


using range() function. range(10)will generate numbers from 0 to 9 (10
numbers).
We can also define the start, stop and step size as range(start,stop,step
size). step size defaults to 1 if not provided.
This function does not store all the values in memory, it would be
inefficient. So it remembers the start, stop, step size and generates the
next number on the go.
To force this function to output all the items, we can use the
function list().

Example:-

# Program to iterate through a list using indexing

genre = ['pop', 'rock', 'jazz']

# iterate over the list using index


for i in range(len(genre)):
print("I like", genre[i])

43
Python Programming Unit:1

o/p

I like pop
I like rock
I like jazz

for loop with else

A for loop can have an optional else block as well. The else part is


executed if the items in the sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else
part is ignored.
Hence, a for loop's else part runs if no break occurs.

Ex:-
digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")

o/p

0
1
5
No items left.

Program to reverse a string

string1 =  "pace student"

44
Python Programming Unit:1

string2 = ""

i = len(string1)-1

while(i>=0):

  string2 = string2 + string1[i]

  i = i-1

print "original = " + string1

print "reverse  = " + string2

Output:

original = pace student


reverse = tneduts ecap

While loop

The while loop in Python is used to iterate over a block of code as long
as the test expression (condition) is true.
We generally use this loop when we don't know beforehand, the
number of times to iterate.

Syntax

while test_expression:
Body of while

In while loop, test expression is checked first. The body of the loop is
entered only if the test_expression evaluates to True. After one

45
Python Programming Unit:1

iteration, the test expression is checked again. This process continues


until the test_expression evaluates to False.

In Python, the body of the while loop is determined through


indentation.
Body starts with indentation and the first unindented line marks the
end.
Python interprets any non-zero value as True. None and 0 are
interpreted asFalse.

Ex:-
# Program to add natural numbers upto n
# sum = 1+2+3+...+n

n = int(input("Enter n: "))
n = 10
sum = 0
i=1

while i <= n:
sum = sum + i
i = i+1 # update counter

print("The sum is", sum)

o/p

Enter n: 10
The sum is 55

while loop with else


Same as that of for loop, we can have an optional else block with while
loop as well.
The else part is executed if the condition in the while loop evaluates
toFalse. The while loop can be terminated with a break statement.

46
Python Programming Unit:1

In such case, the else part is ignored. Hence, a while loop's else part
runs if no break occurs and the condition is false.
Here is an example to illustrate this.
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
o/p
Inside loop
Inside loop
Inside loop
Inside else

break and continue statements


In Python, break and continue statements can alter the flow of a normal
loop.
Loops iterate over a block of code until test expression is false, but
sometimes we wish to terminate the current iteration or even the whole
loop without cheking test expression.
The break and continue statements are used in these cases.

break statement

The break statement terminates the loop containing it. Control of the
program flows to the statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop),
break will terminate the innermost loop.

Syntax of break
break
# Use of break statement inside loop

for val in "string":


if val == "i":
break
print(val)

47
Python Programming Unit:1

print("The end")

o/p

s
t
r
The end

continue statement
The continue statement is used to skip the rest of the code inside a
loop for the current iteration only. Loop does not terminate but
continues on with the next iteration.

Syntax
continue

# Program to show the use of continue statement inside loops

for val in "string":


if val == "i":
continue
print(val)

print("The end")

o/p

s
t
r
n
g
The end

48
Python Programming Unit:1

Pass

In Python programming, pass is a null statement. The difference


between a comment and pass statement in Python is that, while the
interpreter ignores a comment entirely, pass is not ignored.
However, nothing happens when pass is executed. It results into no
operation (NOP).

Syntax of pass
pass

We generally use it as a placeholder.

PROGRAMS

Program to Swap Two numbers


a =int( input('Enter value of a: '))
b =int( input('Enter value of b: '))

temp = a
a=y
b = temp

print('After swapping a: {}'.format(x))


print('After swapping b: {}'.format(y))

o/p

Enter value of a: 10
Enter value of b: 20

After swapping a:20


After swapping b:10

Program to find the sum of all numbers stored in a list

49
Python Programming Unit:1

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

sum = 0
# iterate over the list
for val in numbers:
sum = sum+val

# Output: The sum is 48


print("The sum is", sum)

o/p
The sum is 48

Program to Find Largest Among Three Numbers


print("enter three numbers:")
 
a = int(input())
b = int(input())
c = int(input())
 
if a>b and a>c:
    print(a, " is largest")
elif b>a and b>c:
    print(b, " is largest")
else:
    print(c, " is largest")

o/p

enter three numbers:


12
7
9
12 is largest

Program to find the H.C.F of two input numbers

50
Python Programming Unit:1

# take input from the user


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1,


num2))

o/p
The H.C.F. of 54 and 24 is 6

Program to check if the input number is prime or not take input from
the user

num = int(input("Enter a number: "))


if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")

# if input number is less than or equal to 1, it is not prime


else:
print(num,"is not a prime number")

o/p
Enter a number: 13
Sample Output
13 is a prime number

Sample Input
Enter a number :25
Sample Output

51
Python Programming Unit:1

25 is not a prime number

Program for prime numbers in a range

lower = int(input("Enter lower range: "))


upper = int(input("Enter upper range: "))

print("Prime numbers between",lower,"and",upper,"are:")

for num in range(lower,upper + 1):


if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
o/p

Prime numbers between 900 and 1000 are:


907
911
919
929
937
941
947
953
967
971
977
983
991
997

Program to calculate Factorial of number


num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
52
Python Programming Unit:1

elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

o/p

Enter a number: 6
The factorial of 6 is 720

ARMSTRONG NUMBER

number = int(input("Enter any number: "))


temp = number
Sum = 0
while temp != 0:
rem = temp % 10
Sum = Sum + (rem * rem * rem)
temp = temp / 10
if(number == Sum):
print ("Armstrong Number")
else:
print ("Not an Armstrong Number")

O/P

Enter any number: 153


Armstrong number

Enter any number: 132


Not an Armstrong number

Palindrome number

num = raw_input("Enter any number: ")


rev_num = reversed(num)
if list(num) == list(rev_num):
print("Palindrome number")

53
Python Programming Unit:1

else:
print("Not Palindrome number")

o/p

Enter any number: 131


Palindrome number

Enter any number: 132


Not Palindrome number

Reverse of number

num = int(input("Enter any Number: "))


Reverse = 0
while(num > 0):
Reminder = num %10
Reverse = (Reverse *10) + Reminder
num = num //10

print("\n Reverse of entered number is: %d" %Reverse)

o/p

Enter any number: 231


Reverse of entered number is: 132
Print Table of any number
n = int(input('Enter any number of Table: '))

for i in range(1,11):
print(n,'x',i,'=',n*i)

o/p

Enter any number of Table: 5


(5, 'x', 1, '=', 5)
(5, 'x', 2, '=', 10)
(5, 'x', 3, '=', 15)
(5, 'x', 4, '=', 20)
(5, 'x', 5, '=', 25)
(5, 'x', 6, '=', 30)
(5, 'x', 7, '=', 35)

54
Python Programming Unit:1

(5, 'x', 8, '=', 40)


(5, 'x', 9, '=', 45)
(5, 'x', 10, '=', 50)

Functions

Function:- It is a block of re-usable code to perform specific tasks.

Functions in Python are built-in and user-defined.

Built-in functions are usually a part of Python packages and libraries,


whereas user-defined functions are written by the developers to meet
certain requirements. In Python, all functions are treated as objects, so
it is more flexible compared to other high-level languages.

Syntax:-

def function_name(parameters):
"""docstring"""
statement(s)

A function definition consists of following components.

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same
rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They
are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function
does.
6. One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

def greet(name):
"""This function greets to the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")

55
Python Programming Unit:1

def Executes at Runtime

The Python def is a true executable statement: when it runs, it creates a


new function object and assigns it to a name. Because it‘s a statement, a
def can appear any where a statement can—even nested in other
statements.

if test:
def func():

else:
def func():

The def statement makes a function but does not call it. After the def
has run, you can call (run) the function in your program by adding
parentheses after the function‘s name.

Function Call

Once we have defined a function, we can call it from another function,


program or even the Python prompt. To call a function we simply type the
function name with appropriate parameters.

Syntax:- func ()

Pass by reference vs value


All parameters (arguments) in the Python language are passed by
reference. It means if you change what a parameter refers to within a
function, the change also reflects back in the calling function.

def changeme( mylist ):


#This changes a passed list into this function
mylist.append([11,12,13,14])
print("Values inside the function: ", mylist)
return
# Now you can call changeme function

56
Python Programming Unit:1

mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)
output

Values inside the function: [8, 9, 10, [11,12, 13, 14]]


Values outside the function: [8, 9, 10, [11, 12, 13, 14]]

Passed by reference and the reference is being overwritten inside the


called function.

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assign new reference in mylist
print("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print("Values outside the function: ", mylist)

output

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]

Function Arguments

In Python, user-defined functions can take four different types of


arguments. The argument types and their meanings, however, are pre-
defined and can’t be changed. But a developer can, instead,  follow
these pre-defined rules to make their own custom functions. The
following are the four types of arguments and their rules.

Default arguments:

57
Python Programming Unit:1

Default values indicate that the function argument will take that value if
no argument value is passed during function call. The default value is
assigned by using assignment (=) operator. 

def printinfo( name, id = 101 ):


#"This prints a passed info into this function"
print( "Name: ", name)
print( "Id: ", id)
return;
# Now you can call printinfo function
printinfo( id=101, name="joy" )
printinfo( name="joy" )

output

Name: joy
Id 50
Name: joy
Id 101

Required arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call should
match exactly with the function definition

# Function definition is here


def printme( str ):
#"This prints a passed string into this function"
print(str)
return;

# Now you can call printme function


printme()

Keyword arguments
Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
58
Python Programming Unit:1

This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values
with parameters.

def printinfo( name, age ):


#"This prints a passed info into this function"
print("Name: ", name)
print("Age ", age)
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

output

Name: miki
Age 50

Variable-length arguments
You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-
length arguments and are not named in the function definition, unlike
required and default arguments.

def printinfo( arg1, *vartuple ):


#"This prints a variable passed arguments"
print("Output is: ", arg1)
for var in vartuple:
print(var)
return;

# Now you can call printinfo function


printinfo(10)
printinfo(70, 60, 50 )

output

Output is:
10
Output is:
70

59
Python Programming Unit:1

60

50

The Anonymous Functions(Lambda)
These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use
the lambda keyword to create small anonymous functions.

 Lambda forms can take any number of arguments but return just one value
in the form of an expression. They cannot contain commands or multiple
expressions.
 An anonymous function cannot be a direct call to print because lambda
requires an expression
 Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
 Although it appears that lambda's are a one-line version of a function, they
are not equivalent to inline statements in C or C++, whose purpose is by
passing function stack allocation during invocation for performance
reasons.

Syntax
The syntax of lambda functions contains only a single statement, which is
as follows −

lambda [arg1 [,arg2,.....argn]]:expression

ex:-

sum = lambda arg1, arg2: arg1 + arg2;


# Now you can call sum as a function
print( "Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))

output

Value of total : 30
Value of total : 40

60
Python Programming Unit:1

Ex:-

# Program to show the use of lambda functions


double = lambda x: x * 2
# Output: 10
print(double(5))

output

10

It is often used in conjunction with typical functional concepts


like filter(), map() and reduce().

lambda useful in specialized roles:

1. lambda is an expression, not a statement.


Because of this, a lambda can appear in places a def is not allowed. For
example, places like inside a list literal, or a function call's arguments. As
an expression, lambda returns a value that can optionally be assigned a
name. In contrast, the def statement always assigns the new function to
the name in the header, instead of returning is as a result.

2. lambda's body is a single expression, not a block of statements.


The lambda's body is similar to what we'd put in
a def body's returnstatement. We simply type the result as an expression
instead of explicitly returning it. Because it is limited to an expression,
a lambda is less general that a def. We can only squeeze design, to limit
program nesting. lambda is designed for coding simple functions,
and def handles larger tasks.

Namespaces and Scoping


Variables are names (identifiers) that map to objects. A namespace is a
dictionary of variable names (keys) and their corresponding objects
(values).

61
Python Programming Unit:1

A Python statement can access variables in a local namespace and in


the global namespace. If a local and a global variable have the same name,
the local variable shadows the global variable.

Each function has its own local namespace. Class methods follow the same
scoping rule as ordinary functions.

Python makes educated guesses on whether variables are local or global. It


assumes that any variable assigned a value in a function is local.

Therefore, in order to assign a value to a global variable within a function,


you must first use the global statement.

The statement global VarName tells Python that VarName is a global


variable. Python stops searching the local namespace for the variable.

For example, we define a variable Money in the global namespace. Within


the function Money, we assign Money a value, therefore Python
assumes Money as a local variable. However, we accessed the value of the
local variable Money before setting it, so an UnboundLocalError is the
result. Uncommenting the global statement fixes the problem.

money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
money = money + 1

print( money)
AddMoney()
print (money)

62

You might also like