Professional Documents
Culture Documents
VV PURAM BANGALORE
SUBJECT CODE:
PREPARED BY
TEJASHWINI P S
ASSISTANT PROFESSOR
tejashwinips@bit-bangalore.edu.ins
TEXT BOOKS
1. Al Sweigart, “Automate the Boring Stuff with Python”, Edition, No Starch Press, 2015.
2. Allen B. Downey, “Think Python: How to Think Like a omputer Scientist”, 2 nd Edition ,
Green Tea Press, 2015.
REFEENCE BOOKS
1
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
INTRODUCTION
History
Features of python
2
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Flavors of Python
Types of Python compilers are referred as flavors of Python. They help to integrate
various types of programming languages in Python some of them are:
1. CPython:
It is a Python compiler that was implemented in C language. Even C++ code can be
execute using CPython.
2. JPython:
It is enables Python implementation to be run on Java platform. It runs on JVM.
3. IronPython:
3
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
It is compiler designed for .NET framework, but it is written in C#. It can run on
CLR(Common Language Run time).
4. PyPy:
It is a Python implemented by using Python language itself. It runs fast since JIT is
incorporated to PVM.
5. Ruby Python:
It acts as a bridge from Ruby to Python interpreter. It embeds the Python interpreter
inside the Ruby application.
6. Anaconda Python:
The name Anaconda Python is obtained after redeveloping it to handle large scale
data processing, predictive analytics and scientific computing. It handles huge amount
of data.
Python Versions
In python.org downloads click on python 3 version for the respective operating system.
After downloading the python version 3, enable add to path button and click on install.
Once installation is done can execute the python programs in 3 ways :
IDLE
PYTHON Shell
Editplus
Notepad
IDEs: Pycharm, Eclipse, Spyder, Jypter etc..
Note: It‟s always good to learn core Python and Advanced Python without IDEs because IDEs
provide inbuilt support during programming. SO, the chance to learn the python syntax is less.
4
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Identifiers
Reserved words
There are some words in Python which represents some meaning or functionality. Such
words are called as reserved words.
There are 33 reserved words. They are;
False; None; True;
and, or, not, is
if, else, elif (switch is not supported)
while, for, break, continue, return, in yield(dowhile not supported)
try, except, finally, raise, assert,(catch is replaced by except throw and throws are not
supported)
import, from, as, class, def, pass, global, nonlocal, lambda, del, with
Note : All the keywords are lower case alphabets except Boolean keywords.
Modifiers such as private, public etc are not supported. Only 2 types of data are
available such global and nonlocal.
Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments starts with a #, and Python will ignore them.
5
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Data types
Note :
In java byte, short, int and long is considered as integral data type.
Long datat ype available in python 2 but not in python 3.
In python, everything is object that is datatype, methods etc..
6
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
int()
decimal:
it is base 10 representation.
Digits allowed are from 0 to 9.
Ex: 9999
octal :
it is base 8 representation.
Digits allowed are from 0 and 7.
octal numbers prefix with 0o or 0O.
Ex: 0o777, 0O555
hexa decimal
it is base 16 representation.
Digits allowed are from 0 to 9 and a to f or A to F.
hexadecimal numbers prefix with 0x or 0X.
Ex: 0xFace, 0Xbeef
Note: size, range concept not supported for data type because in python data type
is object. For Objects we cannot predict the size and range.
Base conversion :
In python, we can convert the data from one base to another base by using utility
function.
Utility function consist of :
7
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
complex()
How to get the real and imaginary data in the given data?
Ex: a = 10 + 20j
a.real = >10
a.imag =>20
bool()
Ex: 3. a=10
8
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
b=20
c=a<b //c=True
str()
Slice Operator
Breaking or slicing the given string into substring or slice can be achieved by Slice
operator.
It is the most commonly used operator in Strings, Collections, etc..in Python.
-6 -5 -4 -3 -2 -1
P Y T H O N
0 1 2 3 4 5
9
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
string_variable[begin:end]
It returns substring from begin to end-1.
Ex: s=”PYTHON”
s[2:5] //THO
s[3:] //HON
s[:4] //PYTH
s[-5:-1] ///YTHO
s[-1:-5] //‟ „
s[1:-1] YTHO
s[-1:1] //‟ ‟
s[1:20] //YTHON
Syntax 2 :
string_variable[begin:end:step]
It returns substring from begin to end-1 with skip count.
Ex: s=”python developer”
s[1:10:2] // 'yhndv
Type Casting
The process of converting the value of one data type to another data type is called type
conversion.
Python has two types of type conversion :-
Implicit Type Conversion
Python interpreter automatically converts one data type to another data type of
higher range to avoid data loss without user involvement.
Ex:
num_int = 123
num_flo = 1.23
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
10
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
print("datatype of num_new:",type(num_new))
output:
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
Explantion:
Adding the data of 2 variables num_int and num_float.
num_new has a data type float because python automatically converts smaller
data type into larger data type to avoid loss of data.
Ex 2.
num_int = 123
num_str = "456"
print(num_int+num_str)
output :
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
Traceback (most recent call last):
File "D:/TPS/PYTHON/sample5.py", line 7, in <module>
print(num_int+num_str)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Explantion:
Python automatically cannot convert string data type with interger.
Python has a solution for above situation which is known as Explicit Type
Conversion
.
Explicit Type Conversion/Type casting
User convert the data type of an object to another required data type using pre-
defined functions like int(), float(), str(), complex(), bool() to perform explicit
type conversion.
Syntax : required_datatype(expression)
11
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Ex:
num_int = 123
num_str = "456"
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
output:
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>
Explanation
Converts num_str from string(higher) to interger(lower)type using int()
function to perform the addition.
After converting num_str to an integer value, python interpreter wil be able to
add these two variables.
int() function is used to convert other type of value to int data type.
Ex:
int(10.23) = 10
int(True) = 1
int(False) =0
12
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
int(“10”) = 10
string can be converted into integral value only if string is integral and
should be in base 10 form.
int(“10.5”) = Value Error
float() function is used to convert other type of value to float data type.
Ex:
float(10) = 10.0
float(2+3j) = Type error
It is not possible to convert complex to float
float(True) = 1.0
float (False) =0.0
Internally Boolean value True and False is implemented as integral value
1 and 0 respectively.
float(“10”) = 10.0
string can be converted into float value only if string is integral/float and
should be in base 10 form.
float(“10.5”) = 10.5
13
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
bool() function is used to convert other type of value to bool data type.
For int argument
Ex:
bool(0) = False
bool(10) = True
For float argument
Ex:
bool (0.0) = False
bool(0.1) = True
For complex arguments
Ex:
bool(0+0j) = False
If both the arguments are 0 then result is False.
bool(0+0.1j) = True
if any one of the argument is non zero then the result is True.
For string argument
Ex:
bool(„‟) = False
If argument is empty string=False.
bool(“xyz”) = True.
str() functions is used to convert any other data type to string type without any
restriction.
Ex:
str(10) = 10
str(10.5) = 10.5
str(True) = True
str(2+3j) = 2+3j
14
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Python 2.x
It has raw_input(), and input() function for reading the data from the console.
raw_input() is used to read the data from the console and convert into string.
Example
X = raw_input(‘Enter x’) #10
Y = raw_input(‘Enter y’) #20
print(‘sum = ‘,X+Y)
Output :1020
input() is used to read the data from the console and provide the data in the same
type.
Example
X =input(‘Enter x’) #10
Y =input(‘Enter y’) #20
print(‘sum = ‘,X+Y)
Output :30
Python 3.x
It has only input() function for reading as data from the console.
The role of input() function is to read and convert into string data implicitly.
Example1
X =input(„Enter x‟) #10
Y =input(„Enter y‟) #20
print(„sum = „,X+Y)
output : 1020
Expalantion
In the above example, the+ symbol performs concatenation between X and Y
instread of adding the values of X and Y because the input function reads the data
X and Y and then convert into string. Hence, the + symbol concatenates the value
of X and Y.
Example 2 :
X =int(input(„Enter x‟)) #10
Y =int(input(„Enter y‟)) #20
print(„sum = „,X+Y)
15
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
output : 30
print()
The print() function displays the string value inside the parentheses on the screen.
Example:
print('Hello world!')
Python is calling the print() function and the string value „Hello world‟ is being passed as
an argument to the function.
The quotes are not printed on the screen which are used to indicate the begins and ends of
the screen and are not part of the string value.
But i want colon in between the values as a separator. Then will use sep attribute
in print().
print(a,b,c,sep = „:‟)
16
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
output :
python
developer
The above output can be obtained in a single line by using end attribute.
print(“python”, end=‟‟)
print(“developer”)
pythondeveloper
print(„python‟,end = „***‟)
print(„developer‟,end = „$$$‟)
python***developer$$$
Operators
Arithmetic Operator
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
17
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
x = 15
y=4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.
18
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
> If the value of left operand is greater than (a > b) is not true.
the value of right operand, then condition
becomes true.
< If the value of left operand is less than the (a < b) is true.
value of right operand, then condition
becomes true.
>= If the value of left operand is greater than (a >= b) is not true.
or equal to the value of right operand, then
condition becomes true.
x = 10
y = 12
19
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
Assignment Operator
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a
on the left.
There are various compound operators in Python like a += 5 that adds to the variable and
later assigns the same. It is equivalent to a = a + 5.
20
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Bitwise Operator
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b
= 13. In the binary format their values will be 0011 1100 and 0000 1101 respectively.
Ex:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
& Binary Operator copies a bit to the result if (a & b) (means 0000
21
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Logical Operator
Logical operators are the and, or, not operators.
and Logical AND If both the operands are true then (a and b) is true.
condition becomes true.
22
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
not Logical NOT Used to reverse the logical state of its Not(a and b) is
operand. false.
Ex: x = True
y = False
print('x or y is',x or y)
print('not x is',not x)
Special Operator
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 –
not in Evaluates to true if it does not finds a x not in y, here not in results in a
variable in the specified sequence and 1 if x is not a member of
false otherwise. sequence y.
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
23
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
# Output: False
print('a' in y)
Identity Operators
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below –
Ex:
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
24
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
1
** :- Exponentiation (raise to the power)
13
not or and :- Logical operators
25
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Flow control
The program‟ control flow is the order in which program code executes at runtime.
The control flow of a python program is regulated by
Conditional / selection statements
It performs different computations or action depending on expressions evaluates to True
or False.
It is categorised into :
if
An if statements clause is executed if the statements condition is true.
The clause is skipped if the condition is False.
An if statement consist of the following:
if keyword
a condition(Parenthesis for the condition is optional)
a colon
starting on the next line, an indented block of code(called the if
clause)
Syntax :
if(condition) :
indented Statement Block
Ex:
if name = „Alice‟:
print(„Hi Alice‟)
flow chart :
26
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
if – else
An if clause can optionally be followed by an else statement. The else
clause is executed only when the if statement‟s condition is False.
An if- else statement consist of the following:
if keyword
a condition(Parenthesis for the condition is optional)
a colon
starting on the next line, an indented block of code(called the if
clause)
else keyword
a colon
starting on the next line, an indented block of code(called the else
clause)
Syntax :
if(condition) :
indented statement block when condition is True.
else:
indented statement block when condition is False.
Ex:
if name == 'Alice':
print('Hi, Alice.')
27
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
else:
print('Hello, stranger.')
Flow chart:
if – elif – else
. The if – elif – else statement is an “else if” statement that always
follows an if or elif or else statement. It provides another condition that
is checked only if any of the previous conditions were False. The else
clause is executed only when the if or elif statement‟s condition is False.
28
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Syntax :
if(condition1):
indented statement block of condition1.
elif(condition2):
indented statement block of condition2.
else:
alternate statement block if all condition check above fails.
Ex:
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
else:
print('You are neither Alice nor a little kid.')
if – elif
The if – elif statement is an “else if” statement that always follows an if or
another elif statement. It provides another condition that is checked only
if any of the previous conditions were False.
An if – elif – else statement always consists of the following:
if keyword
a condition(Parenthesis for the condition is optional)
a colon
starting on the next line, an indented block of code(called the if
clause)
elif keyword
29
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
a condition
a colon
starting on the next line, an indented block of code(called the elif
clause)
Syntax :
if(condition1):
indented statement block of condition1.
elif(condition2):
indented statement block of condition2.
elif(condition3):
indented statement block of condition3.
Ex :
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 100:
print('You are not Alice, grannie.') elif
age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
Flow chart :
30
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
31
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
The code in the for loop‟s clause will run five times. The first time the
variable i is set to 0. The print() function call in the clause will print
Jimmy Five Times (0). After Python finishes an iteration through all the
code inside the for loop‟s clause, the execution goes back to the top of the
loop, and the for statement increments i by one and the process will repeat
until the variable i will go up to range -1, but will not include, the integer
passed to range().
Output :
My name is
Jimmy Five Times (0)
Jimmy Five Times (1)
JimmyFive Times (2)
Jimmy Five Times (3)
JimmyFive Times (4)
Ex 2: write a program to add up all the numbers from 0 to 100.
total=0
total=total+num
print(total)
Output:
5050
Explanation:
The result is 5,050.Intially total variable is set to 0.
32
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
The for loop then executes total = total + num 100 times.
Every integer from 0 to 100 will have been added to total.
Ex:
for i in range(12,16):
print(i)
12 13 14 15
for i in range(0,10,2):
print(i)
Explanation :
02468
while loop
A block of code execute over and over again with a while statement.
The code in a while clause will be executed as long as the while
statement‟s condition is True.
A while statement always consists of the following:
The while keyword
A condition (that is, an expression that evaluates to True or False).
33
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
A colon Starting on the next line, an indented block of code (called the
while clause)
Syntax:
While(condition) :
indented block of code/while clause
Flow chart :
Example :
n=10
sum = 0
i=1
while i<n:
sum = sum + i
i=i+1
print(„the sum is „, sum)
Output :
Enter n : 10
The sum is 55
34
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
if statement
spam = 0
if spam < 5:
print('Hello, world.')
spam = spam+1
While statement
spam = 0
while spam < 5:
print('Hello, world.')
spam=spam+1
Example:
name = „‟
while name ! = „your name‟
print(„Please type your name‟)
name = input()
print(„Thank you !‟)
The name != 'your name' condition will evaluate to True and the
program execution will enter the while loop‟s clause.
The code inside this clause asks the user to type their name, which is
assigned to the name variable .
After the last line of the block, the execution moves back to the start of
the while loop and reevaluates the condition. If the value in name is not
35
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
equal to the string 'your name', then the condition is True and the
execution enters the while clause again.
Execution of while loop repeats until the user types your name, the
condition of the while loop will be 'your name' !='your name', which
evaluates to False. The condition is now False, and instead of the
program execution reentering the while loop‟s clause, it skips past it and
continues running the rest of the program
break
If the execution reaches a break statement, it immediately exits the
while loop‟s clause.
Syntax:
break
Example :
while True:
print('Thank you!')
Flow chart
continue
36
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Example
for i in range(1, 11):
if i == 6:
continue
else:
print(i, end = " ")
output
1 2 3 4 5 7 8 9 10
Flow chart
37
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Functions
Once function is defined, need to call a function with function name with appropriate
parameters.
Example 1
def hello():
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
hello()
hello()
hello()
output:
Howdy!
Howdy!!!
Hello there.
Howdy!
Howdy!!!
Hello there.
Howdy!
Howdy!!!
38
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Hello there
Example 2
def greet(name):
print(“hello, “ + name + “. Good morning!”)
greet(„nisha‟)
output:
hello, nisha. Good morning!
Docstrings
The first string after the function header is called the docstring which is briefly used to
explain what a function does.
Return statement:
output:
hello
None
In java, if the function does not return anything but compulsory and explicitly should
write the void return type in function definition.
How to return multiple values?
Example 1
def cal(a,b):
sum=a+b
sub=a-b
mul=a*b
div=a/b
return sum,sub,mul,div
m,n,o,p=cal(100,50)
print('sum=',m)
print('sub=',n)
print('mul=',o)
39
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
print('div=',p)
t=cal(200,50)
for x in t:
print(x)
output:
m= 150
n= 50
o= 5000
p= 2.0
250
150
10000
4.0
Function Parameters
In python,4 different type of parameter/argument are available for functions.
Positional parameters
In positional arguments, the number and order of parameters should match both in
function def and calling function.
Example 1
def cal(a,b):
sum=a+b
sub=a-b
mul=a*b
div=a/b
return sum,sub,mul,div
m,n,o,p=cal(100,50)
Keyword parameters
In keyword parameters, its only required to match the number of parameters but not
necessary to match with order both function def and calling function.
Example
def cal(a,b)
cal(a=100,b=50)
cal(b=50,a=100)
Note : we can use both positional and keyword argument simultaneously with a
condition that positional argument should be followed by keyword argument and vice
versa does not hold support in python.
Example
cal(100,b = 50) //valid
40
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Default parameters
Example
def greet(name, msg=‟good morning‟);
print(„hello‟, name + ‟,‟ + msg)
greet(„nisha‟)
greet(“ravi”,”how r you!”)
output
hello nisha,good morning
hello ravi,how r you!
Explantion :
The parameter name does not have a default value and required during a call.
The pararmeter msg has a default value of “Good morning!” and msg is optional
during a call. Explicitly provided value will overwrite the default value.
Var-args parameters
In Python, variable number of argument to a function can be done by using 2 special
symbols:
*args
The special syntax *args in function definition is used to pass a variable
number of arguments to a function and are non- key worded variable
length argument list.
Example
def myFun(*argv):
for arg in argv:
print (arg)
output:
Hello
Welcome
to
BIT
41
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
**kwargs
The special syntax **kwargs in function definitions in python is used to
pass a keyworded, variable-length argument list. The name kwargs with
the double star allows us to pass through keyword arguments
Example
def myFun(**kwargs):
for key, value in kwargs.items():
print(“%s == %s" %(key, value))
myFun(first ='welcome', mid ='to', last='BIT')
output
first == welcome
mid == to
last == BIT
Modules
A group of related built in functions and variables saved in a file is called Module.
Adv:
Code reusability
Length of the code is reduced and readability of the program increases.
An import statement consists of the following:
The import keyword
The name of the module
Optionally, more module names, as long as they are separated by commas
Example
import random
for i in range(5):
print(random.randint(1, 10))
output
41841
The random.randint() function call evaluates to a random integer value between the two
integers that you pass it. Since randint() is in the random module, so module name
random. should be provided in front of the function name.
from import statement
An alternative form of the import statement is
from keyword, followed by module name, followed by import keyword followed
by function_name/variable.
42
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Parameters and variables that are assigned in a called function are said to exist in local
scope. Variables that are assigned outside all functions are said to exist in the global
scope.
A variable that exists in a local scope is called a local variable, while a variable that
exists in the global scope is called a global variable.
A variable must be one or the other; it cannot be both local and global. When a scope is
destroyed, all the values stored in the scope‟s variables are forgotten.
Global scope: There is only one global scope, and it is created when the program begins.
When the program terminates, the global scope is destroyed, and all its variables are
forgotten. Otherwise, the next time when the program executes, the variables would
remember their values from the last execution that leads to inappropriate output.
Local scope: A local scope is created whenever a function is called. Any variables
assigned in this function exist within the local scope. When the function returns, the local
scope is destroyed, and these variables are forgotten. The next time by calling the
function, the local variables will not remember the values stored in them from the last
time the function was called.
Scopes matter for several reasons:
Code in the global scope cannot use any local variables.
A local scope can access global variables.
Code in a function‟s local scope cannot use variables in any other local scope.
The same name can be used for different variables if they are in different scopes.
def spam():
eggs = 31337
spam()
print(eggs)
Explanation:
43
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
The error happens because the eggs variable exists only in the local scope
created when spam() is called. Once the program execution returns from
spam, that local scope is destroyed, and there is no longer a variable
named eggs. So when the program tries to run print(eggs), Python gives
you an error saying that eggs is not defined.
When the program execution is in the global scope, no local scopes exist,
so there can‟t be any local variables.
Hence, local variables cannot be used in the global scope.
def bacon():
ham = 101
eggs = 0
spam()
output: 99
Explanation:
When the program starts, the spam() function is called, and a local scope is
created. The local variable eggs is set to 99.
Then the bacon() function is called, and a second local scope is created. Multiple
local scopes can exist at the same time. In this new local scope, the local variable
ham is set to 101, and a local variable eggs which is different from the spam()‟s
local scope is also created and set to 0. When bacon() returns, the local scope for
that call is destroyed.
The program execution continues in the spam() function to print the value of eggs,
and since the local scope for the call to spam() still exists here, the eggs variable
is set to 99.
Hence, local variables in one function are completely separate from the local
variables in another function.
Global Variables Can Be Read from a Local Scope
Example :
def spam():
print(eggs)
44
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
eggs = 42
spam()
print(eggs)
output : 42
Explanation:
There is no parameter named eggs or any code that assigns eggs a value in the spam()
function, when eggs is used in spam(), Python considers it a reference to the global
variable eggs. 42 is printed.
Local and Global Variables with the Same Name
Example :
def spam():
eggs = 'spam local'
print(eggs) # prints 'spam local'
def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'
Output :
bacon local
spam local
bacon local
global
There are actually three different variables in this program, all named eggs. The
variables are as follows:
A variable named eggs that exists in a local scope when spam() is called.
A variable named eggs that exists in a local scope when bacon() is called.
A variable named eggs that exists in the global scope.
Since these three separate variables all have the same name, it can be
confusing to keep track of which one is being used at any given time. This is
why you should avoid using the same variable name in different scopes.
45
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
A global variable from within a function can be modified by the global statement. A
global statement such as global eggs at the top of a function, tells Python, “In this
function, eggs refers to the global variable, so don‟t create a local variable with this
name.”
Example
def spam():
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs)
Output: spam
Explanation:
Eggs is declared global at the top of spam() function call.
Eggs is set to 'spam' this assignment is done to the globally scoped spam. No local
spam variable is created.
There are four rules to tell whether a variable is in a local scope or global scope:
If a variable is being used in the global scope (that is, outside of all
functions), then it is always a global variable.
If there is a global statement for that variable in a function, it is a global
variable.
If the variable is used in an assignment statement in the function, it is a
local variable.
If the variable is not used in an assignment statement, it is a global
variable.
Example :
def spam():
global eggs
eggs = 'spam' # this is the global
def bacon():
eggs = 'bacon' # this is a local
def ham():
print(eggs) # this is the global
eggs = 42 # this is the global
spam()
print(eggs)
output : spam
46
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
Explanation:
In the spam() function, eggs is the global eggs variable, because there‟s a
global statement for eggs at the beginning of the function.
In bacon(), eggs is a local variable, because there‟s an assignment
statement for it in that function.
In ham(), eggs is the global variable, because there is no assignment
statement or global statement for it in that function
In a function, a variable will either always be global or always be local.
There‟s no way that the code in a function can use a local variable named
eggs and then later in that same function use the global eggs variable.
Exception Handling
If an error occurs in python program then the entire program will crash.to overcome the
situations detect the errors, handle them and then continue to run.
Example:
def spam(divideBy):
return 42 / divideBy
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
output:
21.0
3.5
Traceback (most recent call last):
File "C:/zeroDivide.py", line 6, in
print(spam(0))
File "C:/zeroDivide.py", line 2, in spam
return 42 / divideBy
ZeroDivisionError: division by zero
Explanation:
A function called spam, given a parameter, and then printed the value of that
function with various parameters.
A ZeroDivisionError happens by dividing a number by zero.
The return statement in spam() is causing an error.
Errors can be handled with try and except statements. The code that could
potentially have an error is put in a try clause. If an error happens then the
program execution moves to the start of a except clause
47
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
Output :
21.0
3.5
Error: Invalid argument.
None
42.0
Explanation:
The code in a try clause causes an error, the program execution immediately
moves to the code in the except clause. After running that code, the execution
continues as normal.
Example 3
def spam(divideBy):
return 42 / divideBy
try:
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
except ZeroDivisionError:
print('Error: Invalid argument.')
output:
21.0
48
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON
3.5
Error: Invalid argument.
Explanation:
The print(spam(1)) is never executed is because once the execution jumps to the code in
the except clause, it does not return to the try clause. Instead, it just continues moving
down as normal.
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
49
Prepared By: TEJASHWINI P S