Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
51 views

Python Unit 1

python
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Python Unit 1

python
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

lOMoARcPSD|32795027

programming in python

Master of Computer Applications (Anna University)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sri Harshini (sriharshini927@gmail.com)
lOMoARcPSD|32795027

UNIT 1
1) INTRODUCTION TO PYTHON BASICS
What is Python?
 Python is a very popular general-purpose interpreted, interactive, object-oriented, and
high-level programming language.
 Python is dynamically-typed and garbage-collected programming language. It was
created by Guido van Rossum during 1985- 1990.
 Python supports multiple programming paradigms, including Procedural, Object Oriented
and Functional programming language.

Why learn Python?


Python provides many useful features to the programmer. We have listed below few-essential
feature of Python.

o Easy to use and Learn


o Expressive Language
o Interpreted Language
o Object-Oriented Language
o Open Source Language
o Extensible
o Learn Standard Library
o GUI Programming Support
o Integrated
o Embeddable
o Dynamic Memory Allocation
o Wide Range of Libraries and Frameworks

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Where is Python used?


Python is a general-purpose, popular programming language and it is used in almost every
technical field. The various areas of Python use are given below.

o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions

Python Popular Frameworks and Libraries


Python has wide range of libraries and frameworks widely used in various fields such as machine
learning, artificial intelligence, web applications, etc. We define some popular frameworks and
libraries of Python as follows.

o Web development (Server-side) - Django Flask, Pyramid, CherryPy


o GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
o Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
o Mathematics - Numpy, Pandas, etc.

Python Syntax compared to other programming languages


 Python was designed for readability, and has some similarities to the English language with
influence from mathematics.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

 Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this
purpose.

Example
print("Hello, World!")

python features

 Interpreted
 There are no separate compilation and execution steps like C and C++.
 Directly run the program from the source code.
 Internally, Python converts the source code into an intermediate form
called bytecodes which is then translated into native language of specific
computer to run it.
 No need to worry about linking and loading with libraries, etc.
 Platform Independent
 Python programs can be developed and executed on multiple operating
system platforms.
 Python can be used on Linux, Windows, Macintosh, Solaris and many
more.
 Free and Open Source; Redistributable
 High-level Language
 In Python, no need to take care about low-level details such as managing
the memory used by the program.
 Simple
 Closer to English language;Easy to Learn
 More emphasis on the solution to the problem rather than the syntax
 Embeddable
 Python can be used within C/C++ program to give scripting capabilities
for the program’s users.
 Robust:
 Exceptional handling features
 Memory management techniques in built
 Rich Library Support
 The Python Standard Library is very vast.
 Known as the “batteries included” philosophy of Python ;It can help do
various things involving regular expressions, documentation generation,

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

unit testing, threading, databases, web browsers, CGI, email, XML,


HTML, WAV files, cryptography, GUI and many more.
 Besides the standard library, there are various other high-quality libraries
such as the Python Imaging Library which is an amazingly simple image
manipulation library.
Organizations using Python :
1. Google(Components of Google spider and Search Engine)
2. Yahoo(Maps)
3. YouTube
4. Mozilla
5. Dropbox
6. Microsoft
7. Cisco
8. Spotify
9. Quora

Python Getting Started


Python Install

Many PCs and Macs will have python already installed.

To check if you have python installed on a Windows PC, search in the start bar for Python or run the
following on the Command Line (cmd.exe):

C:\Users\Your Name>python --version

To check if you have python installed on a Linux or Mac, then on linux open the command line or on
Mac open the Terminal and type:

python --version

If you find that you do not have Python installed on your computer, then you can download it for free
from the following website: https://www.python.org/

Python Quickstart

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Python is an interpreted programming language, this means that as a developer you write Python
(.py) files in a text editor and then put those files into the python interpreter to be executed.

The way to run a python file is like this on the command line:

C:\Users\Your Name>python helloworld.py

Where "helloworld.py" is the name of your python file.

Let's write our first Python file, called helloworld.py, which can be done in any text editor.

helloworld.py

print("Hello, World!")

Try it Yourself »

Simple as that. Save your file. Open your command line, navigate to the directory where you saved
your file, and run:

C:\Users\Your Name>python helloworld.py

The output should read:

Hello, World!

Congratulations, you have written and executed your first Python program.

The Python Command Line


To test a short amount of code in python sometimes it is quickest and easiest not to write the code in
a file. This is made possible because Python can be run as a command line itself.

 Type the following on the Windows, Mac or Linux command line:

C:\Users\Your Name>python

Or, if the "python" command did not work, you can try "py":

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

C:\Users\Your Name>py

 From there you can write any python, including our hello world example from earlier in the
tutorial:

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")

 Which will write "Hello, World!" in the command line:

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!

 Whenever you are done in the python command line, you can simply type the following to
quit the python command line interface:

exit()

2)Interpreted and Interactive mode in Python

Interpreted Python

 Python is an interpreted object-oriented programming language. By


interpreted it is meant that each time a program is run the interpreter
checks through the code for errors and then interprets the instructions
into machine-readable bytecode.
 An interpreter is a translator in computer's language which translates
the given code line-by-line in machine readable bytecodes.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

 And if any error is encounterd it stops the translation until the error is
fixed.

Interactive mode
In the Python programming language, there are two ways in which we can run our code:
1. Interactive mode
2. Script mode
In the interactive mode as we enter a command and press enter, the very next step we
get the output. The output of the code in the interactive mode is influenced by the last
command we give. Interactive mode is very convenient for writing very short lines of
code.

How to run python code in Interactive mode?


In order to run our program in the interactive mode, we can use command prompt in
windows. Let us see understand the execution of python code in the command prompt
with the help of an example:
Example 1:
To run python in command prompt type “python”. Then simply type the Python
statement on >>> prompt. As we type and press enter we can see the output in the very
next line.

# Python program to display "Hello GFG"

print("Hello GFG")

Output:

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Disadvantages of interactive mode


 The interactive mode is not suitable for large programs.
 The interactive mode doesn’t save the statements. Once we make a program it is
for that time itself, we cannot use it in the future. In order to use it in the future, we
need to retype all the statements.
 Editing the code written in interactive mode is a tedious task. We need to revisit
all our previous commands and if still, we could not edit we need to type everything
again.

Script Mode:

 In the script mode, a python program can be written in a file. This file can then
be saved and executed using the command prompt.
 We can view the code at any time by opening the file and editing becomes quite
easy as we can open and view the entire code as many times as we want.
 Script mode is very suitable for writing long pieces of code. It is much preferred
over interactive mode by experts in the program.
 The file made in the script made is by default saved in the Python installation
folder and the extension to save a python file is “.py”.
How to run python code in script mode?

In order to run a code in script mode follow the following steps.

Step 1: Make a file using a text editor. You can use any text editor of your choice(Here
I use notepad).
Step 2: After writing the code save the file using “.py” extension.
Step 3: Now open the command prompt and command directory to the one where your
file is stored.
Step 4: Type python “filename.py” and press enter.
Step 5: You will see the output on your command prompt.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

3)Python Variables and identifier


 Variable is a name that is used to refer to memory location. Python variable is also known
as an identifier and used to hold value.

 In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.

 Variable names can be a group of both the letters and digits, but they have to begin with a
letter or an underscore.

Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.

o The first character of the variable must be an alphabet or underscore ( _ ).


o All the characters except the first character may be an alphabet of lower-case(a-z), upper-
case (A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,
*).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values


Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the variable,
that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Object References

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

It is necessary to understand how the Python interpreter works when we declare a variable. The
process of treating variables is somewhat different from many other programming languages.

Python is the highly object-oriented programming language; that's why every data item belongs
to a specific type of class. Consider the following example.

1. print("John")

Output:

John

The Python object creates an integer object and displays it to the console. In the above print
statement, we have created a string object. Let's check the type of it using the Python built-
in type() function.

1. type("John")

Output:

<class 'str'>

In Python, variables are a symbolic name that is a reference or pointer to an object. The variables
are used to denote objects by that name.

Let's understand the following example

1. a = 50

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

In the above image, the variable a refers to an integer object.

Suppose we assign the integer value 50 to a new variable b.

a = 50

b=a

The variable b refers to the same object that a points to because Python does not create another
object.

Let's assign the new value to b. Now both variables will refer to the different objects.

a = 50

b =100

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Variable Names
We have already discussed how to declare the valid variable. Variable names can be any length
can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore character(_).
Consider the following example of valid variables names.

1. name = "Devansh"
2. age = 20
3. marks = 80.50
4.
5. print(name)
6. print(age)
7. print(marks)

Output:

Devansh
20
80.5

Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.

We can apply multiple assignments in two ways, either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Consider the following example.

1. Assigning single value to multiple variables

Eg:

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)

Output:

50
50
50

2. Assigning multiple values to multiple variables:

Eg:

1. a,b,c=5,10,15
2. print a
3. print b
4. print c

Output:

5
10
15

Python Variable Types


There are two types of variables in Python - Local variable and Global variable. Let's understand
the following variables.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Local Variable
Local variables are the variables that declared inside the function and have scope within the
function. Let's understand the following example.

Example -

1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
10. add()

Output:

The sum is: 50

Explanation:

In the above code, we declared a function named add() and assigned a few variables within the
function. These variables will be referred to as the local variables which have scope only inside
the function. If we try to use them outside the function, we get a following error.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

1. add()
2. # Accessing local variable outside the function
3. print(a)

Output:

The sum is: 50


print(a)
NameError: name 'a' is not defined

Global Variables
Global variables can be used throughout the program, and its scope is in the entire program. We
can use global variables inside or outside the function.

A variable declared outside the function is the global variable by default. Python provides
the global keyword to use global variable inside the function. If we don't use
the global keyword, the function treats it as a local variable. Let's understand the following
example.

Example -

1. # Declare a variable and initialize it


2. x = 101
3.
4. # Global variable in function
5. def mainFunction():
6. # printing a global variable
7. global x
8. print(x)
9. # modifying a global variable
10. x = 'Welcome To Javatpoint'
11. print(x)
12.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

13. mainFunction()
14. print(x)

Output:

101
Welcome To Javatpoint
Welcome To Javatpoint

Explanation:

In the above code, we declare a global variable x and assign a value to it. Next, we defined a
function and accessed the declared variable using the global keyword inside the function. Now
we can modify its value. Then, we assigned a new string value to the variable x.

Now, we called the function and proceeded to print x. It printed the as newly assigned value of x.

Delete a variable
We can delete the variable using the del keyword. The syntax is given below.

Syntax -

1. del <variable_name>

In the following example, we create a variable x and assign value to it. We deleted variable x,
and print it, we get the error "variable x is not defined". The variable x will no longer use in
future.

Example -

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

1. # Assigning a value to x
2. x=6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)

4) ARITHMETIC OPERATORS IN PYTHON


The arithmetic operations are performed by calculator where we can perform addition, subtraction,
multiplication and division. This example shows the basic arithmetic operations

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

Operator Description Example

+ Addition Adds values on either side of the operator. a+b=


30

- Subtraction Subtracts right hand operand from left hand operand. a–b=
-10

* Multiplies values on either side of the operator a*b=


Multiplication 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and returns remainder b%a=
0

** Exponent Performs exponential (power) calculation on operators a**b =10


to the
power 20

// Floor Division - The division of operands where the result is the quotient in 9//2 = 4
which the digits after the decimal point are removed. But if one of the and
operands is negative, the result is floored, i.e., rounded away from zero 9.0//2.0

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

(towards negative infinity) − = 4.0,


-11//3 =
-4,
-11.0//3
= -4.0

Example
Assume variable a holds 21 and variable b holds 10, then −

a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c

c=a-b
print "Line 2 - Value of c is ", c

c=a*b
print "Line 3 - Value of c is ", c

c=a/b
print "Line 4 - Value of c is ", c

c=a%b
print "Line 5 - Value of c is ", c

a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c

a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c
When you execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

5) VALUES AND TYPES

 A value is one of the most basic things in any program works with.
 A value may be characters i.e. ‘Hello, World!’ or a number like 1,2.2 ,3.5 etc.Values
belong to different types: 1 is an integer, 2 is a float and ‘Hello, World!’ is a string etc.
 First, we type the python command to start the interpreter.

Numbers:

Python supports 3 types of numbers: integers, float and complex number. If you want to know
what type a value has you can use type() function.
print(type(1))
print(type(2.2))
print(type(complex(2,3)))

<class 'int'>

<class 'float'>

<class 'complex'>

Strings:

Strings are defined either with a single quote or a double quotes. The difference between the two
is that using double quotes makes it easy to include apostrophes.
print(type('Hello World'))
print(type("Today's News Paper"))

 Python Statement
Instructions that a Python interpreter can execute are called statements. For example, a

=1 is an assignment statement. if statement, for statement, while statement, etc.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Multi-line statement

In Python, the end of a statement is marked by a newline character. But we can make
a statement extend over multiple lines with the line continuation character (\). For
example:

a=1+2+3+\
4+5+6+\
7+8+9

This is an explicit line continuation. In Python, line continuation is implied inside


parentheses ( ), brackets [ ], and braces { }. For instance, we can implement the above
multi-line statement as:

a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)

Here, the surrounding parentheses () do the line continuation implicitly. Same is the
case with [] and { }. For example:

colors = ['red',
'blue',
'green']

We can also put multiple statements in a single line using semicolons, as follows:

a = 1; b = 2; c = 3

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Python Indentation
 A code block (body of a function, loop, etc.) starts with indentation and ends
with the first unindented line.
 The amount of indentation is up to you, but it must be consistent throughout
that block.
Generally, four whitespaces are used for indentation and are preferred over tabs. Here
is an example.

for i in range(1,11):
print(i)
if i == 5:
break
Run Code

The enforcement of indentation in Python makes the code look neat and clean. This
results in Python programs that look similar and consistent.

Indentation can be ignored in line continuation, but it's always a good idea to indent. It
makes the code more readable. For example:

if True:
print('Hello')
a=5

and

if True: print('Hello'); a = 5

both are valid and do the same thing, but the former style is clearer.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

7)PYTHON OPERATORS
Operators are used to perform operations or mathematical calculation on variables and values.

In the example below, we use the + operator to add together two values:

Example
print(10 + 5)

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

 Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Example:

X = 10
Y = 20
# output: x + y = 30
print ( ‘x + y =’, x + y )

 Assignment Operators
Assignment operators are used to assign values to variables:

Operator Example Same As Try

= x=5 x=5 Try i

+= x += 3 x=x+3 Try i

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

-= x -= 3 x=x-3 Try i

*= x *= 3 x=x*3 Try i

/= x /= 3 x=x/3 Try i

%= x %= 3 x=x%3 Try i

//= x //= 3 x = x // 3 Try i

**= x **= 3 x = x ** 3 Try i

&= x &= 3 x=x&3 Try i

|= x |= 3 x=x|3 Try i

^= x ^= 3 x=x^3 Try i

>>= x >>= 3 x = x >> 3 Try i

<<= x <<= 3 x = x << 3 Try i

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Example: 5 = 2+3 Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

ex :

x = 20
y = 25
# Output: x > y is False
print('x > y is',x>y)

Run:

x > y is False

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Logical Operators:

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

Or Returns True if one of the statements is true x < 5 or x < 4

Not Reverse the result, returns False if the not(x < 5 and x < 10)

Ex: variable A = 10, B = 20,

x = 10
y = 20
# Output: x and y is True
print('x and y is',x and y)

Output:

Ans: A and B is True

Identity Operators:

Identity operators are used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location:

Operator Description Example

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

is Returns True if both variables are the same x is y


object

is not Returns True if both variables are not the same x is not y
object

Example –
number1 = 5
number2 = 5
number3 = 10
print(number1 is number2) # check if number1 is equal to number2
print(number1 is not number3) # check if number1 is not equal to number3

Output:
True
True

The first print statement checks if number1 and number2 are equal or not; if they are, it gives
output as True, otherwise False—the next print statement checks for number1 and number3. To
return True, number1 and number3 shouldn’t be equal.

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

in Returns True if a sequence with the specified value is x in y


present in the object

not in Returns True if a sequence with the specified value is not x not in y
present in the object

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall off
shift

>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let the rightm

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

shift off

Let’s see an example –


number1 = 4 # 0100 in binary
number2 = 3 # 0011 in binary
print("& operation- ", number1 & number2) # AND
print("| operation- ", number1 | number2) # OR
print("^ operation- ", number1 ^ number2) # XOR
print("~ operation- ", ~number2) # negation
print("<< operation- ", number1 << 1) # shift left by 1 bit
print(">> operation- ", number1 >> 1) # shift right by 1bit

Output:
Output-
& operation- 0
| operation- 7
^ operation- 7
~ operation- -4
<< operation- 8
>> operation- 2

For the and operation, the results become 0 because at least 1 bit is 0 in 4 or 3. In the case of
the or operator, if at least one bit is 1, then it returns 1.

8)Boolean Values
In programming you often need to know if an expression is True or False.

You can evaluate any expression in Python, and get one of two answers, True or False.

When you compare two values, the expression is evaluated and Python returns the Boolean
answer:

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Example
print(10 > 9)
print(10 == 9)
print(10 < 9)

When you run a condition in an if statement, Python returns True or False:

Example
Print a message based on whether the condition is True or False:

a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Evaluate Values and Variables


The bool() function allows you to evaluate any value, and give you True or False in return,

Example
Evaluate a string and a number:

print(bool("Hello"))
print(bool(15))

Example
Evaluate two variables:

x = "Hello"
y = 15

print(bool(x))

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

print(bool(y))

Most Values are True

Almost any value is evaluated to True if it has some sort of content.

Any string is True, except empty strings.

Any number is True, except 0.

Any list, tuple, set, and dictionary are True, except empty ones.

Example
The following will return True:

bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])

Some Values are False


In fact, there are not many values that evaluate to False, except empty values, such
as (), [], {}, "", the number 0, and the value None. And of course the
value False evaluates to False.

Example
The following will return False:

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

One more value, or object in this case, evaluates to False, and that is if you have an object that is
made from a class with a __len__ function that returns 0 or False:

Example
class myclass():
def __len__(self):
return 0

myobj = myclass()
print(bool(myobj))

Functions can Return a Boolean


You can create functions that returns a Boolean Value:

Example
Print the answer of a function:

def myFunction() :
return True

print(myFunction())

You can execute code based on the Boolean answer of a function:

Example
Print "YES!" if the function returns True, otherwise print "NO!":

def myFunction() :
return True

if myFunction():
print("YES!")
else:
print("NO!")

Python also has many built-in functions that return a boolean value, like
the isinstance() function, which can be used to determine if an object is of a certain data type:

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Example
Check if an object is an integer or not:

x = 200
print(isinstance(x, int))

9)OPERATOR PRECEDENCE
 The Python interpreter executes operations of higher precedence operators first in any
given logical or arithmetic expression. Except for the exponent operator (**), all other
operators are executed from left to right.
 An expression is a collection of numbers, variables, operations, and built-in or user-
defined function calls. The Python interpreter can evaluate a valid expression.

Code 2 - 7

Output:

-5

The following table lists all operators from highest precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

~+- Complement, 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'td>

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

^| 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 / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e

e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e

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


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

e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
When you execute the above program, it produces the following result −

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

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

10) EXPRESSION IN PYTHON


A combination of operands and operators is called an expression. The expression in Python
produces some value or result after being interpreted by the Python interpreter.

An example of expression can be : x = x + 10x=x+10. In this expression, the first 1010 is


added to the variable x. After the addition is performed, the result is assigned to the variable x.

Example :

x = 25 # a statement
x = x + 10 # an expression

print(x)

Output :

35

The expression in Python can be considered as a logical line of code that is evaluated to obtain
some result. If there are various operators in an expression then the operators are resolved based
on their precedence. We have various types of expression in Python

Types of Expression in Python


.

1. Constant Expressions

A constant expression in Python that contains only constant values is known as a constant
expression. In a constant expression in Python, the operator(s) is a constant. A constant is a
value that cannot be changed after its initialization.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Example :

x = 10 + 15

# Here both 10 and 15 are constants but x is a variable.


print("The value of x is: ", x)

Output :

The value of x is: 25


2. Arithmetic Expressions

An expression in Python that contains a combination of operators, operands, and sometimes


parenthesis is known as an arithmetic expression.

Operator Syntax Working

+ x+y Addition or summation of x and y.

- x-y Subtraction of y from x.

x xxy Multiplication or product of x and y.

/ x/y Division of x and y.

// x // y Quotient when x is divided by y.

% x%y Remainder when x is divided by y.

** x ** y Exponent (x to the power of y).

Example :

x = 10
y=5

addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y

print("The sum of x and y is: ", addition)


print("The difference between x and y is: ", subtraction)
print("The product of x and y is: ", product)
print("The division of x and y is: ", division)
print("x to the power y is: ", power)

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Output :

The sum of x and y is: 15


The difference between x and y is: 5
The product of x and y is: 50
The division of x and y is: 2.0
x to the power y is: 100000
3. Integral Expressions

An integral expression in Python is used for computations and type conversion


(integer to float, a string to integer, etc.). An integral expression always produces an integer
value as a resultant.

Example :

x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the floating-point number into an integer or vice versa for summation.
result = x + int(y)

print("The sum of x and y is: ", result)

Output :

The sum of x and y is: 15


4. Floating Expressions

A floating expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). A floating expression always produces a floating-point number as a
resultant.

Example :

x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the integer number into a floating-point number or vice versa for
summation.
result = float(x) + y

print("The sum of x and y is: ", result)

Output :

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

The sum of x and y is: 15.0


5. Relational Expressions

A relational expression in Python can be considered as a combination of two or more arithmetic


expressions joined using relational operators. The overall expression results in
either True or False (boolean result). We have four types of relational operators in Python (i.e. >
, < , >= , <=)(i.e.>,<,>=,<=).
A relational operator produces a boolean result so they are also known as Boolean Expressions.

For example :
10 + 15 > 2010+15>20

In this example, first, the arithmetic expressions (i.e. 10 + 1510+15 and 2020) are evaluated,
and then the results are used for further comparison.

Example :

a = 25
b = 14
c = 48
d = 45

# The expression checks if the sum of (a and b) is the same as the difference of (c and d).
result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)

Output :

Type: <class 'bool'>


The result of the expression is: False
6. Logical Expressions

As the name suggests, a logical expression performs the logical computation, and the overall
expression results in either True or False (boolean result). We have three types of logical
expressions in Python, let us discuss them briefly.

Operator Syntax Working

And xx and yy The expression return True if both xx and yy are true, else it returns False.

Or xx or yy The expression return True if at least one of xx or yy is True.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Operator Syntax Working

Not not xx The expression returns True if the condition of xx is False.

Note :
In the table specified above, xx and yy can be values or another expression as well.

Example :

from operator import and_

x = (10 == 9)
y = (7 > 5)

and_result = x and y
or_result = x or y
not_x = not x

print("The result of x and y is: ", and_result)


print("The result of x or y is: ", or_result)
print("The not of x is: ", not_x)

Output :

The result of x and y is: False


The result of x or y is: True
The not of x is: True
7. Bitwise Expressions

The expression in which the operation or computation is performed at the bit level is known as
a bitwise expression in Python. The bitwise expression contains the bitwise operators.

Example :

x = 25
left_shift = x << 1
right_shift = x >> 1

print("One right shift of x results: ", right_shift)


print("One left shift of x results: ", left_shift)

Output :

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

One right shift of x results: 12


One left shift of x results: 50
8. Combinational Expressions

As the name suggests, a combination expression can contain a single or multiple expressions
which result in an integer or boolean value depending upon the expressions involved.

Example :

x = 25
y = 35

result = x + (y << 1)

print("Result obtained : ", result)

Output :

Result obtained: 95

Whenever there are multiple expressions involved then the expressions are resolved based on
their precedence or priority. Let us learn about the precedence of various operators in the
following section.

Multiple Operators in Expression (Operator Precedence) ?


The operator precedence is used to define the operator's priority i.e. which operator will be
executed first. The operator precedence is similar to the BODMAS rule that we learned in
mathematics. Refer to the list specified below for operator precedence.

Precedence Operator Name

1. ()[]{} Parenthesis

2. ** Exponentiation

3. -value , +value , ~value Unary plus or minus, complement

4. / * // % Multiply, Divide, Modulo

5. +– Addition & Subtraction

6. >> << Shift Operators

7. & Bitwise AND

8. ^ Bitwise XOR

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Precedence Operator Name

9. pipe symbol Bitwise OR

10. >= <= > < Comparison Operators

11. == != Equality Operators

12. = += -= /= *= Assignment Operators

13. is, is not, in, not in Identity and membership operators

14. and, or, not Logical Operators

Let us take an example to understand the precedence better :

x = 12
y = 14
z = 16

result_1 = x + y * z
print("Result of 'x + y + z' is: ", result_1)

result_2 = (x + y) * z
print("Result of '(x + y) * z' is: ", result_2)

result_3 = x + (y * z)
print("Result of 'x + (y * z)' is: ", result_3)

Output :

Result of 'x + y + z' is: 236


Result of '(x + y) * z' is: 416
Result of 'z + (y * z)' is: 236

Difference between Statements and Expressions in Python


We have earlier discussed statement expression in Python, let us learn the differences between
them.

Statement in Python Expression in Python

A statement in Python is used for creating variables The expression in Python produces some value or result after being
or for displaying values. interpreted by the Python interpreter.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Statement in Python Expression in Python

A statement in Python is not evaluated for some


An expression in Python is evaluated for some results.
results.

The execution of a statement changes the state of the


The expression evaluation does not result in any state change.
variable.

A statement can be an expression. An expression is not a statement.

Example: x = 3 + 6x=3+6.
Example : x= 3x=3. Output : 99
Output : 33

11) conditional if else ( control flow )


Decision-making statements in programming languages decide the direction of the flow
of program execution.

if statement
if statement is the most simple decision-making statement. It is used to decide whether
a certain statement or block of statements will be executed or not i.e if a certain
condition is true then a block of statement is executed otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if
statement will be identified as shown in the below example:
if condition:
statement1
statement2

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Example: Python if Statement

i = 10

if (i > 15):

print("10 is less than 15")

print("I am Not in if")

Output:
I am Not in if
As the condition present in the if statement is false. So, the block below the if statement
is executed.

if-else
if a condition is true it will execute a block of statements and if the condition is false it
won’t. But what if we want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to execute a block of
code when the condition is false.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flow chart

Example 1: Python if-else statement

i = 20

if (i < 15):

print("i is smaller than 15")

print("i'm in if Block")

else:

print("i is greater than 15")

print("i'm in else Block")

print("i'm not in if and not in else Block")

Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

The block of code following the else statement is executed as the condition present in
the if statement is false after calling the statement which is not in block(without spaces).

Example 2: Python if else in list comprehension

def digitSum(n):

dsum = 0

for ele in str(n):

dsum += int(ele)

return dsum

List = [367, 111, 562, 945, 6726, 873]

newList = [digitSum(i) for i in List if i & 1]

print(newList)

Output
[16, 3, 18, 18]

nested-if
A nested if is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement. Yes, Python allows us to
nest if statements within if statements. i.e, we can place an if statement inside another if
statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Flowchart of Python Nested if Statement

Example: Python Nested if

i = 10

if (i == 10):

if (i < 15):

print("i is smaller than 15")

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

if (i < 12):

print("i is smaller than 12 too")

else:

print("i is greater than 15")

Output:

i is smaller than 15
i is smaller than 12 too

if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed from
the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement

FlowChart of Python if else elif statements

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Example: Python if else elif statements

i = 20

if (i == 10):

print("i is 10")

elif (i == 15):

print("i is 15")

elif (i == 20):

print("i is 20")

else:

print("i is not present")

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Output:

i is 20

Short Hand if statement


Whenever there is only a single statement to be executed inside the if block then
shorthand if can be used. The statement can be put on the same line as the if statement.
Syntax:
if condition: statement
Example: Python if shorthand

i = 10

if i < 15:

print("i is less than 15")

Output:
i is less than 15

Short Hand if-else statement


This can be used to write the if-else statements in a single line where there is only one
statement to be executed in both if and else block.
Syntax:
statement_when_True if condition else statement_when_False
Example: Python if else shorthand

i = 10

print(True) if i < 15 else print(False)

Output:
True

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

The following sorts of loops are available in the Python programming language.

Sr.No. Name of the Loop Type & Description


loop

1 While loop Repeats a statement or group of statements while a given condition is TRUE. It tests th
condition before executing the loop body.

2 For loop This type of loop executes a code block multiple times and abbreviates the code tha
manages the loop variable.

3 Nested loops We can iterate a loop inside another loop.

Loop Control Statements


Statements used to control loops and change the course of iteration are called control statements.
All the objects produced within the local scope of the loop are deleted when execution is
completed.

Python provides the following control statements.

Sr.No. Name of the Description


control statement

1 Break statement This command terminates the loop's execution and transfers the program's contro
to the statement next to the loop.

2 Continue statement This command skips the current iteration of the loop. The statements following th
continue statement are not executed once the Python interpreter reaches th
continue statement.

3 Pass statement The pass statement is used when a statement is syntactically necessary, but no cod
is to be executed.

The for Loop

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Python's for loop is designed to repeatedly execute a code block while iterating through a list,
tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is
known as iteration.

Syntax of the for Loop

1. for value in sequence:


2. { code block }

In this case, the variable value is used to hold the value of every item present in the sequence
before the iteration begins until this particular iteration is completed.

Loop iterates until the final item of the sequence are reached.

Code

1. # Python program to show how the for loop works


2.
3. # Creating a sequence which is a tuple of numbers
4. numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
5.
6. # variable to store the square of the number
7. square = 0
8.
9. # Creating an empty list
10. squares = []
11.
12. # Creating a for loop
13. for value in numbers:
14. square = value ** 2
15. squares.append(square)
16. print("The list of squares is", squares)

Output:

The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Using else Statement with for Loop


As already said, a for loop executes the code block until the sequence element is reached. The
statement is written right after the for loop is executed after the execution of the for loop is
complete.

Only if the execution is complete does the else statement comes into play. It won't be executed if
we exit the loop or if an error is thrown.

Here is a code to better understand if-else statements.

Code

# Python program to show how if-else statements work

1.
2. string = "Python Loop"
3.
4. # Initiating a loop
5. for s in a string:
6. # giving a condition in if block
7. if s == "o":
8. print("If block")
9. # if condition is not satisfied then else block will be executed
10. else:
11. print(s)

Output:

P
y
t
h
If block
n

L
If block
If block
p

Now similarly, using else with for loop.

Syntax:

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

for value in sequence:

else:

Code

1. # Python program to show how to use else statement with for loop
2.
3. # Creating a sequence
4. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
5.
6. # Initiating the loop
7. for value in tuple_:
8. if value % 2 != 0:
9. print(value)
10. # giving an else statement
11. else:
12. print("These are the odd numbers present in the tuple")

Output:

3
9
3
9
7
These are the odd numbers present in the tuple

The range() Function


With the help of the range() function, we may produce a series of numbers. range(10) will
produce values between 0 and 9. (10 numbers).

We can give specific start, stop, and step size values in the manner range(start, stop, step size). If
the step size is not specified, it defaults to 1.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Since it doesn't create every value it "contains" after we construct it, the range object can be
characterized as being "slow." It does provide in, len, and __getitem__ actions, but it is not an
iterator.

The example that follows will make this clear.

Code

# Python program to show the working of range() function

1.
2. print(range(15))
3.
4. print(list(range(15)))
5.
6. print(list(range(4, 9)))
7.
8. print(list(range(5, 25, 4)))

Output:

range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]

To iterate through a sequence of items, we can apply the range() method in for loops. We can use
indexing to iterate through the given sequence by combining it with an iterable's len() function.
Here's an illustration.

Code

1. # Python program to iterate over a sequence with the help of indexing


2.
3. tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")
4.
5. # iterating over tuple_ using range() function
6. for iterator in range(len(tuple_)):
7. print(tuple_[iterator].upper())

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Output:

PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE

While Loop
While loops are used in Python to iterate until a specified condition is met. However, the
statement in the program that follows the while loop is executed once the condition changes to
false.

Syntax of the while loop is:

1. while <condition>:
2. { code block }

All the coding statements that follow a structural command define a code block. These
statements are intended with the same number of spaces. Python groups statements together with
indentation.

Code# Python program to show how to use a while loop

1. counter = 0
2. # Initiating the loop
3. while counter < 10: # giving the condition
4. counter = counter + 3
5. print("Python Loops")

Output:

Python Loops
Python Loops
Python Loops
Python Loops

Using else Statement with while Loops


As discussed earlier in the for loop section, we can use the else statement with the while loop
also. It has the same syntax.

Code

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

1. #Python program to show how to use else statement with the while loop
2. counter = 0
3.
4. # Iterating through the while loop
5. while (counter < 10):
6. counter = counter + 3
7. print("Python Loops") # Executed untile condition is met
8. # Once the condition of while loop gives False this statement will be executed
9. else:
10. print("Code block inside the else statement")

Output:

Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement

Single statement while Block


The loop can be declared in a single statement, as seen below. This is similar to the if-else block,
where we can write the code block in a single line.

Code

# Python program to show how to write a single statement while loop

1. counter = 0
2. while (count < 3): print("Python Loops")

Loop Control Statements


Now we will discuss the loop control statements in detail. We will see an example of each
control statement.

Continue Statement
It returns the control to the beginning of the loop.

Code

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

1. # Python program to show how the continue statement works


2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == "o" or string == "p" or string == "t":
6. continue
7. print('Current Letter:', string)

Output:

Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s

Break Statement
It stops the execution of the loop when the break statement is reached.

# Python program to show how the break statement works

1.
2. # Initiating the loop
3. for string in "Python Loops":
4. if string == 'L':
5. break
6. print('Current Letter: ', string)

Output:

Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes,
functions, and empty control statements.

Code# Python program to show how the pass statement works

1. for a string in "Python Loops":


2. pass
3. print( 'Last Letter:', string)

Output:

Last Letter: s

14) FUNCTION CALL AND RETURNING VALUES


 functions are the block of statements used to perform some specific tasks in programming. It also
helps to break the large group of code into smaller chunks or modules
 . Functions can be called anywhere and the number of times in a program. It allows us to reuse
the code by simply calling the particular function or block in a program.
 Thus, it avoids the repetition of the same code. We can define functions inside the class, modules,
nested functions, etc.

Rules for defining a function


1. The def keyword is used in the Python function to declare and define a function.
2. The function name must begin with the following identifiers such as: A-Z, a- z, and underscore
(_).
3. Every function must follow colon (:) and then indention to write the program.
4. In a Python function, the reserved word cannot be used as a function name or identifier.
5. In Python, the function parameter can be empty or multiples.

Create a function in Python


To create a function, we need to use a def keyword to declare or write a function in Python. Here
is the syntax for creating a function:

SYNTAX

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

1. def function_name(): # use def keyword to define the function


2. Statement to be executed
3. return statement # return a single value.

Let's create a function program in Python.

Myfun.py

1. def myFun(): # define function name


2. print(" Welcome to JavaTpoint")
3. myFun() # call to print the statement

Output:

Welcome to JavaTpoint

Function Calling in Python


Once a function is created in Python, we can call it by writing function_name() itself or another
function/ nested function. Following is the syntax for calling a function.

Syntax:

1. def function_name():
2. Statement1
3. function_name() # directly call the function
4.
5. # calling function using built-in function
6. def function_name():
7. str = function_name('john') # assign the function to call the function

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

8. print(str) # print the statement

Consider the following example to print the Welcome Message using a function in Python.

CallFun.py

1. def MyFun():
2. print("Hello World")
3. print(" Welcome to the JavaTpoint")
4.
5. MyFun() # Call Function to print the message.

Output:

Hello World
Welcome to the JavaTpoint

In the above example, we call the MyFun() function that prints the statements.

Calling Nested Function in Python


When we construct one function inside another, it is called a nested function. We can create
nested functions using the def keyword. After creating the function, we have to call the outer and
the inner function to execute the statement..

Nest.py

1. def OutFun(): # outer function


2. print("Hello, it is the outer function")
3.
4. def InFun(): # inner function
5. print("Hello, It is the inner function")
6. InFun() # call inner
7.
8. OutFun() # call outer function

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Output:

Hello, it is the outer function


Hello, it is the inner function
As we can see in the above example, the InFun() function is defined inside the OutFun()
function. To call the InFun() function, we first call the OutFun() function in the program. After
that, the OutFun() function will start executing and then call InFun() as the above output.

Program to print the multiplication of two numbers using the nested function in Python.

Nest_arg.py

1. def fun1(): # outer function


2. a = 6 # define variable
3. def fun2(b): # inner function
4. a = 4 # inner variable
5. print ("Display the sum of inner function", a + b) # sum of inner function
6. print ("Display the value of outer variable", a) # it displays the value of outer function fun2(4
) # Inner function

Output:6

Day Display the value of outer variable 6


Display the sum of inner function

Functions as First-Class Objects


In Python, the functions as First-Class Objects. Because it treats the same as the object, and it has
the same properties and method as an object. A function can be assigned to a variable, pass them
as an argument, store them in data structures and return a value from other functions. It can be
manipulated, such as other objects in Python. Furthermore, all the data in the Python program is
represented in the objects or relations. Hence it is also called first-class citizens of Python
function.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Properties of First-Class functions


1. Functions can be assigned to a variable
2. A function is an example of an object type.
3. We also return the function from a function.
4. Functions have the same properties and methods as objects
5. The function is treated as an object to pass as an argument to another function.

Create a program to understand Python functions as an object.

Obj.py

1. def MyObject(text): # Pass an argument.


2. return text.upper()
3.
4. # Call the function inside the print() function.
5. print (MyObject("Welcome to JavaTpoint"))
6.
7. str = MyObject # assign the function to a variable
8.
9. # call the function using the str variable.
10. print (str("Hello, Welcome to JavaTpoint"))

Output:

WELCOME TO JAVATPOINT
HELLO, WELCOME TO JAVATPOINT

Write a program to call a function inside the class.

Student.py

1. class Student:

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

2. Roll_no = 101
3. name = "Johnson"
4. def show(self):
5. print(" Roll no. is %d\nName of student is %s" % (self.Roll_no, self.name))
6.
7. stud = Student() # Create the stud object of Student class
8. stud.show() # call the function using stud object.

Output:

Roll no. is 101


Name of student is Johnson

 A return statement is used to end the execution of the function call and
“returns” the result (value of the expression following the return keyword) to the
caller. The statements after the return statements are not executed. If the return
statement is without any expression, then the special value None is
returned. A return statement is overall used to invoke a function so that the
passed statements can be executed.

Note: Return statement can not be used outside the function.


Syntax:
def fun():
statements
.
.
return [expression]
EXAMPLE
Python program to
# demonstrate return statement

def add(a, b):

# returning sum of a and b


return a + b

def is_true(a):

# returning boolean of a

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

return bool(a)

# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))

res = is_true(2<5)

print("\nResult of is_true function is {}".format(res))

Output:
Result of add function is 5

Result of is_true function is True

Returning Multiple Values


In Python, we can return multiple values from a function. Following are different
ways.
 Using Object: This is similar to C/C++ and Java, we can create a class (in C,
struct) to hold multiple values and return an object of the class.
Example
 Python3

# A Python program to return multiple

# values from a method using class

class Test:

def __init__(self):

self.str = "geeksforgeeks"

self.x = 20

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

# This function returns an object of Test

def fun():

return Test()

# Driver code to test above method

t = fun()

print(t.str)

print(t.x)

Output
geeksforgeeks
20
 Using Tuple: A Tuple is a comma separated sequence of items. It is created with
or without (). Tuples are immutable. See this for details of tuple.
 Python3

# A Python program to return multiple

# values from a method using tuple

# This function returns a tuple

def fun():

str = "geeksforgeeks"

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

x = 20

return str, x; # Return tuple, we could also

# write (str, x)

# Driver code to test above method

str, x = fun() # Assign returned tuple

print(str)

print(x)

 Output:
geeksforgeeks
20
 Using a list: A list is like an array of items created using square brackets. They
are different from arrays as they can contain items of different types. Lists are
different from tuples as they are mutable. See this for details of list.
 Python3

# A Python program to return multiple

# values from a method using list

# This function returns a list

def fun():

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

str = "geeksforgeeks"

x = 20

return [str, x];

# Driver code to test above method

list = fun()

print(list)

 Output:
['geeksforgeeks', 20]
 Using a Dictionary: A Dictionary is similar to hash or map in other languages.
See this for details of dictionary.
 Python3

# A Python program to return multiple

# values from a method using dictionary

# This function returns a dictionary

def fun():

d = dict();

d['str'] = "GeeksforGeeks"

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

d['x'] = 20

return d

# Driver code to test above method

d = fun()

print(d)

 Output:
{'x': 20, 'str': 'GeeksforGeeks'}

Function returning another function


In Python, functions are objects so, we can return a function from another function.
This is possible because functions are treated as first class objects in Python. To know
more about first class objects click here.
In the below example, the create_adder function returns the adder function.

 Python3

# Python program to illustrate functions

# can return another function

def create_adder(x):

def adder(y):

return x + y

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

return adder

add_15 = create_adder(15)

print("The result is", add_15(10))

# Returning different function

def outer(x):

return x * 10

def my_func():

# returning different function

return outer

# storing the function in res

res = my_func()

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

print("\nThe result is:", res(10))

Output:
The result is 25

The result is: 100

15)PARAMETER PASSING

Pass-by-value vs Pass-by-reference

If you have other programming language background, such as C/C++, it is


easy to understand that there are two common types of parameter
passing: pass-by-value and pass-by-reference.

 pass-by-value: Copying the value of the parameter and passing it to the


new variable in the function

 pass-by-reference: Passing the reference of the parameter to the new


variable, so that the original variable and the new variable will point to the
same memory address

So how does parameter passing work in Python? Are they pass-by-value,


pass-by-reference, or something else?

Before answering this question, let’s first understand the basic principles of
Python variables and assignments.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Python Variables and Assignments

Let’s start by looking at the following Python code example:


a=1
b=a
a=a+1

Here, 1 is first assigned to a, that is, a points to the object 1, as shown in the
following flowchart:

Then b = a means, let the variable b also, point to the object 1 at the same
time. Note here that objects in Python can be pointed to or referenced by
multiple variables. Now the flowchart looks like this:

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Finally the a = a + 1 statement. It should be noted that Python data types, such
as integers (int), strings (string), etc., are immutable. So, a = a + 1, does not
increase the value of a by 1, but means that a new object with a value of 2 is
created and a points to it. But b remains unchanged and still points to
the 1 object:

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

At this point, you can see that a simple assignment b = a does not mean that a
new object is recreated, but that the same object is pointed or referenced by
multiple variables.

At the same time, pointing to the same object does not mean that the two
variables are bound together. If you reassign one of the variables, it will not
affect the value of the other variables.

Now let’s take a look at a list examples:


l1 = [1, 2, 3]
l2 = l1
l1.append(4)
l1
[1, 2, 3, 4]
l2
[1, 2, 3, 4]

At first, we let the lists l1 and l2 point to the object [1, 2, 3] at the same time:

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

Since the list is mutable, l1.append(4) does not create a new list, it just inserts
element 4 at the end of the original list, which becomes [1, 2, 3, 4].
Since l1 and l2 point to this list at the same time, the change of the list will be
reflected in the two variables of l1 and l2 at the same time, then the values
of l1 and l2 will become [1, 2, 3, 4] at the same time.

Also, note that variables in Python can be deleted, but objects cannot be
deleted. For example the following code:
l = [1, 2, 3]
del l

del l deletes the variable l, and you cannot access l from now on, but the object
[1, 2, 3] still exists. When a Python program runs, its own garbage collection
system keeps track of every object reference. If [1, 2, 3] is referenced in other
places besides l, it will not be collected, otherwise, it will be collected.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

So, in Python:

 The assignment of a variable only means that the variable points to an


object, and does not mean that the object is copied to the variable; and an
object can be pointed to by multiple variables.

 Changes to mutable objects (lists, dictionaries, sets, etc.) affect all


variables that point to that object.

 For immutable objects (strings, ints, tuples, etc.), the value of all
variables that point to the object is always the same and does not change.
But when the value of an immutable object is updated by some operation
(+= etc.), a new object is returned.

 Variables can be deleted, but objects cannot be deleted.

Argument Passing for Python Functions

Let’s take a look at the official Python quote:

“Remember that arguments are passed by assignment in Python. Since


assignment just creates references to objects, there’s no alias between an
argument name in the caller and callee, and so no call-by-reference per
Se.”

Python’s argument passing is passed by assignment, or pass by object


reference. All data types in Python are objects, so when passing parameters,
just let the new variable and the original variable point to the same object,
and there is no such thing as passing by value or passing by reference.

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

For example:
def my_func1(b):
b = 2a = 1
my_func1(a)
a
1

The parameter passing here makes the variables a and b point to the object 1 at
the same time. But when we get to b = 2, the system will create a new object
with a value of 2 and let b point to it; a still points to the 1 object. So, the value
of a doesn’t change, it’s still 1.

However, when a mutable object is passed as a parameter to a function,


changing the value of the mutable object will affect all variables that point to
it. For example:
def my_func3(l2):
l2.append(4)l1 = [1, 2, 3]
my_func3(l1)
l1
[1, 2, 3, 4]

Here l1 and l2 first both point to lists with values [1, 2, 3]. However, since the
list is variable when the append() the function is executed and a new
element 4 is added to the end of the list, the values of the variables l1 and l2 are
also changed.

However, the following example, which seems to add a new element to the
list, yields significantly different results.
def my_func4(l2):
l2 = l2 + [4]l1 = [1, 2, 3]
my_func4(l1)
l1
[1, 2, 3]

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

This is because statement l2 = l2 + [4], which means that a new list with
“element 4 added at the end” is created, and l2 points to this new object.

16)LOCAL AND GLOBAL SCOPE

A variable is only available from inside the region it is created. This is


called scope.

Local Scope
A variable created inside a function belongs to the local scope of that function,
and can only be used inside that function.

Example
A variable created inside a function is available inside that function:

def myfunc():
x = 300
print(x)

myfunc()

Function Inside Function


As explained in the example above, the variable x is not available outside the
function, but it is available for any function inside the function:

Example
The local variable can be accessed from a function within the function:

def myfunc():
x = 300
def myinnerfunc():

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

print(x)
myinnerfunc()

myfunc()

Global Scope
A variable created in the main body of the Python code is a global variable and
belongs to the global scope.

Global variables are available from within any scope, global and local.

Example
A variable created outside of a function is global and can be used by anyone:

x = 300

def myfunc():
print(x)

myfunc()

print(x)

Naming Variables
If you operate with the same variable name inside and outside of a function,
Python will treat them as two separate variables, one available in the global
scope (outside the function) and one available in the local scope (inside the
function):

Example
The function will print the local x, and then the code will print the global x:

x = 300

def myfunc():
x = 200
print(x)

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

myfunc()

print(x)

Global Keyword
If you need to create a global variable, but are stuck in the local scope, you can
use the global keyword.

The global keyword makes the variable global.

Example
If you use the global keyword, the variable belongs to the global scope:

def myfunc():
global x
x = 300

myfunc()

print(x)

Also, use the global keyword if you want to make a change to a global variable
inside a function.

Example
To change the value of a global variable inside a function, refer to the variable
by using the global keyword:

x = 300

def myfunc():
global x
x = 200

myfunc()

print(x)

Downloaded by Sri Harshini (sriharshini927@gmail.com)


lOMoARcPSD|32795027

17) RECURSIVE FUNCTION

Recursion
Python also accepts function recursion, which means a defined function can call
itself.

Recursion is a common mathematical and programming concept. It means that


a function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.

The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.

In this example, tri_recursion() is a function that we have defined to call


itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not greater
than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works,
best way to find out is by testing and modifying it.

Example
Recursion Example

def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

Downloaded by Sri Harshini (sriharshini927@gmail.com)

You might also like