You are on page 1of 49

BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

BANGALORE INSTITUTE OF TECHNOLOGY

VV PURAM BANGALORE

APPLICATION DEVELOPMENT USING PYTHON

NOTES FOR 5TH SEMESTER COMPUTER SCIENCE

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. Gowrishankar S, Veena A, “Introduction to Python Programming”, 1st Edition, CRC


Press/Taylor & Francis, 2018. ISBN-13:978-0815394372
2. Jake VanderPlas, “pythonDta SciencebHandbook: Essential Tools for Working with
Data”, 1st Edition, O‟Reilly Media, 2016.ISBN-13:978-1491912058
3. Charles Dierbach, “Introduction to Computer Science Using Python”, Edition, Wiley
India Pvt Ltd, 2015. ISBN-13:978-8126556014
4. Wesley J Chun,”Core Python Applications programming”, 3rd Edition, Pearson
Education Ondia, 2015. ISBN-13:978-9332555365
5.

1
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

INTRODUCTION

History

 Python is an interpreted, high-level, general-purpose programming language.


 Developed by Guido van Rossum and first released in 1991,
 Python was conceived in the late 1980s as a successor to the ABC language.
 Python officially available in feb 20th 1991.
 Python 2.0, released in 2000
 Python 3.0, released in 2008, Python 2 code does not run on Python 3.
 The Python 2 language was officially discontinued in 2020.
 Python is combination of
 Functional feature from C
 Object oriented feature from C++
 Scripting language feature from Perl and Shell Script
 Modular programming features from Modula - 3
 Most of the syntax derived from C and ABC languages.
 Applications:
 Desktop Applications
 Web application
 Database Applications
 Network Programming
 Machine Learning Application
 IoT
 Data Analysis Applications etc..

Features of python

1. Simple and Easy to Learn


 It is high level programming languages because it is similar to English statements.
 Only 30 + keyword are available and syntax is very easy and simple.
 Programs are written with less number of lines of code. Hence, Applications are more
readable.
 It is also a developer-friendly language.
2. Freeware and Open Source:
 It is freely available at official website.
 Its source code is easily available to public.
3. Object Oriented Language
 Python supports object-oriented language and concepts of classes, objects
encapsulation, etc.

2
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

4. GUI Programming Support


 Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in python.
 PyQt5 is the most popular option for creating graphical apps with Python.
5. High Level Language
 Python is a high-level language. When we write programs in python, we do not need
to remember the system architecture, nor do we need to manage the memory.
6. Extensible feature
 Python is a Extensible language. Python code can be included in C or C++ language
and and can be compiled in C/C++ language.
7. Python is Portable language
 Python language is also a portable language.
 For example, if we have python code for windows and if we want to run this code on
other platforms such as Linux, Unix, and Mac then we do not need to change it, we
can run this code on any platform.
8. Python is Integrated language
 Python is also an Integrated language because we can easily integrated python with
other languages like c, c++, etc.
9. Interpreted Language
 Python is an Interpreted Language because Python code is executed line by line at a
time. like other languages C, C++, Java, etc.
 The source code of python is converted into an immediate form called bytecode.
10. Large Standard Library
 Python has a large standard library which provides a rich set of module and functions
 There are many libraries present in python for such as regular expressions, unit-
testing, web browsers, etc.
11. Dynamically Typed Language
 Python is a dynamically-typed language.

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

 Python 1.0V introduced in Jan 1994.


 Python 2.0V introduced in Oct 2000.
 Python 3.0V introduced in Dec 2008.

Note: Python 3 will not provide backward compatibility to Python 2.

Current Version: Python 3.6.1

How to install Python?

 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

 Alphabet Symbols(Either Upper case or Lower case).


Eg: total100
 If identifier starts with underscore „_‟ then it is indicated as private.
Eg: _sum
 If it starts with „__'(two underscores symbols) then it is indicated as strongly private
identifier.
Eg: __sum
 If the identifier starts and ends with two underscore symbols then it is language defined
special name, which is also know as magic methods.
Eg: sum
 Identifiers should not start with digits.
 Identifiers are case sensitive.
 Reserved words cannot be used as identifiers.
 There is no length limit for Python identifiers. But it is not recommended to use too
lengthy identifiers.
 Dollar ($) symbol is not allowed in python.

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

Eg: print("Hello, World!") # will print hello world


 Python does not really have a syntax for multi-line comments.
To add a multiline comment you could insert# for each line.
Eg:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
 Python will ignore string literals.
Eg:
"""This is a comment
written in more
than just one line """
print("Hello, World!")

Data types

Python provides inbuilt data type such as :


 int
 float
 complex
 bool
 str
 bytes
 bytearray
 range
 list
 tuple
 set
 frozenset
 dict
 None

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()

 It is used to represent whole numbers or integral values.


Ex: x = 5
 To know the type of the variable a
Ex : type(x)
<class „int‟>
 To print the value of x.
Ex: print(x)
 int data type is can be represented 4 different froms:
 binary:
it is base 2 representation.
Digits allowed are from 0 and 1.
Binary numbers prefix with 0b or 0B.
Ex: 0b1111, 0B0101

 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

bin() : - ex: bin(15)=0b1111, bin(555)=?, bin(0x4321)=?


oct() : - ex: oct(777) =
hex() : - ex: hex(10) = 0xa, hex(16789) = ox4195

Note : utility functions accepts the data in integral form.


float()

 It is used to represent decimal point values or floating point values.


 The only allowed data form in float is decimal form.
 Exponential form of data representation is allowed.
Ex: 3.14e2
Note: python does not support double data type.

complex()

 It is mainly used to develop mathematical or scientific based application.


 The only symbol allowed is j to represent imaginary data.
Ex : a+bj
a = real part
b =imaginary part
j = sqrt(-1)
 The value of a and b can be int or float values.
 In the real part it supports all the base values but in imaginary part the only allowed data
is decimal form.

How to get the real and imaginary data in the given data?
Ex: a = 10 + 20j
a.real = >10
a.imag =>20

bool()

 It is used to represent logical or Boolean values.


 Allowed Boolean values are True and False.
Ex: 1. b = True //valid
type(b) //<class „bool‟>

Ex: 2. b = true ///error

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

Ex: 4. b=‟true‟ //it will treat as string.

 Internally True is represented as 1 and False is represented as False.


Ex: 1. True+True = 2
2 False +True = 1

str()

 It is used to represent a character and sequence of character.


 String should be enclosed with single or double quote.
 Single quote and double quote is used to represent singleline String literals.
Ex: “python
Developer” //invalid
 Multi line String literal can be represented by 3 single quote or 3 double quote.
Ex: „‟‟ python
Developer‟‟‟

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

 In python string can be accessed in both the directions:


 positive index from right to left and
 negative index from left to right.
Ex: s[2] = T
s[-2] = O
s[-7] //string index out of range
s [7] //string index out of range

 Slice Operator categories : -


Syntax1 :

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

 If I want to print particular string 10 times.


Syntax : string_variable*no of times to print
Ex: s =”python”
s*5 // pythonpythonpythonpythonpython

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

num_new = num_int + num_flo

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("Data type of num_int:",type(num_int))


print("Data type of num_str:",type(num_str))

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"

print("Data type of num_int:",type(num_int))


print("Data type of num_str before Type Casting:",type(num_str))

num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))

num_sum = num_int + num_str

print("Sum of num_int and num_str:",num_sum)


print("Data type of the sum:",type(num_sum))

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.

Type casting Functions

 int() function is used to convert other type of value to int data type.

Ex:

int(10.23) = 10

int(2+3j) = Type error

It is not possible to convert complex to int.

int(True) = 1
int(False) =0

12
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

Internally Boolean value True and False is implemented as integral value


1 and 0 respectively.

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

 complex() function is used to convert other types to complex type.


 It can be done in 2 ways by using complex(x) and complex(x,y) functions. The
above 2 functions are called overloaded because it is having same name but differ
in argument list.
 complex(x) = x+0j : it is with 1 argument having real value.
Ex:
complex(10) = 10+0j
complex(10.5) = 10.5+0j
complex(True) = 1+0j
complex(False) = 0+0j = 0j
complex(“10”) = 10+0j
complex(“10.5”) = 10.5+0j
complex(“ten”) = error
complex(“0b1111) = error
string can be converted into complex value only if string is
integral/float and should be in base 10 form.

13
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

 complex(x,y) = x+yj : it is with 2 argument having first argument as real


and second argument as imaginary.
Ex:
complex(10,20) = 10+20j
complex(True,False) = 1+0j
complex(10,20.5) = 10+20.5j
complex(“10.5”,”12”) = error
if first argument is string integral/float then compulsory only one
argument should be passed to complex functions.
complex(“ten”) = error
complex(“0b1111) = error

 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

Reading the data from the console

 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.

Therefore the input() function must be typecasted.

 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

Displaying the data into the console

 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.

 Various cases of print()

 Case 1:print() function without an argument.


The above function by default or implicitly contains \n as an argument.
 Case 2 : print() function with string as an argument.
print(„Hello world‟)
 Case 3 : print() function with escape character
print(„hello \n world‟)
 Case 4 : print() function with string concatenation as an argument
print(„hello‟+‟ world‟)
 Case 5 : print() function with string repetition as an argument.
print(10*‟Hello‟)
 Case 6 : print() function with sep attribute
a,b,c = 10,20,30
print(a,b,c)
output : 10 20 30

But i want colon in between the values as a separator. Then will use sep attribute
in print().

print(a,b,c,sep = „:‟)

By default value for sep is space.


 Case 7 : print() function with end attribute.
The default value for end attribute is new line (\n).
print(„python‟)
print(„developer‟)

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.

Operator Description Example

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

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


operand.

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


Multiplication operator

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


operand

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


operand and returns remainder

17
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

** Exponent Performs exponential (power) calculation a**b =10 to the


on operators power 20

// Floor Division - The division of operands 9//2 = 4 and


where the result is the quotient in which the 9.0//2.0 = 4.0, -
digits after the decimal point are removed. 11//3 = -4, -
But if one of the operands is negative, the 11.0//3 = -4.0
result is floored, i.e., rounded away from
zero (towards negative infinity) −

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)

 Relational /Comparison Operators

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

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

18
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

Operator Description Example

== If the values of two operands are equal, (a == b) is not true.


then the condition becomes true.

!= If values of two operands are not equal, (a != b) is true.


then condition becomes true.

<> If values of two operands are not equal, (a <> b) is true.


then condition becomes true. This is similar to
!= operator.

> 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.

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


equal to the value of right operand, then
condition becomes true.

x = 10
y = 12

# Output: x > y is False


print('x > y is',x>y)

# Output: x < y is True


print('x < y is',x<y)

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)

# 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.

Operator Description Example

= Assigns values from right side c = a + b assigns


operands to left side operand value of a + b into c

+= Add It adds right operand to the left


c += a is equivalent to
AND operand and assign the result to left
c=c+a
operand

-= Subtract It subtracts right operand from the left


c -= a is equivalent to
AND operand and assign the result to left
c=c-a
operand

*= Multiply It multiplies right operand with the


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

20
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

/= Divide It divides left operand with the right


c /= a is equivalent to
AND operand and assign the result to left
c=c/a
operand

%= It takes modulus using two operands


c %= a is equivalent
Modulus and assign the result to left operand
to c = c % a
AND

**= Performs exponential (power)


c **= a is equivalent
Exponent calculation on operators and assign
to c = c ** a
AND value to the left operand

//= Floor It performs floor division on operators c //= a is equivalent to


Division and assign value to the left operand c = c // a

 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

Operator Description Example

& 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

AND it exists in both operands 1100)

| Binary OR It copies a bit if it exists in either (a | b) = 61 (means


operand. 0011 1101)

^ Binary XOR It copies the bit if it is set in one (a ^ b) = 49 (means


operand but not both. 0011 0001)

~ Binary Ones (~a ) = -61 (means


Complement 1100 0011 in 2's
It is unary and has the effect of
complement form due
'flipping' bits.
to a signed binary
number.

<< Binary Left The left operands value is moved left


a << 2 = 240 (means
Shift by the number of bits specified by
1111 0000)
the right operand.

>> Binary The left operands value is moved


a >> 2 = 15 (means
Right Shift right by the number of bits specified
0000 1111)
by the right operand.

 Logical Operator
Logical operators are the and, or, not operators.

Operator Description Example

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

or Logical OR If any of the two operands are non- (a or b) is true.


zero then 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 and y is',x and y)

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 –

Operator Description Example

in Evaluates to true if it finds a variable in


x in y, here in results in a 1 if x is
the specified sequence and false
a member of sequence y.
otherwise.

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.

Ex: x = 'Hello world'


y = {1:'a',2:'b'}

# 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 –

Operator Description Example

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


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

is not Evaluates to false if the variables on either x is not y, here is


side of the operator point to the same not results in 1 if id(x)
object and true otherwise. is not equal to id(y).

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)

 Python Operators Precedence


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

24
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

Sl.No. Operator & Description

1
** :- Exponentiation (raise to the power)

2 ~ + - : -Complement, unary plus and minus (method


names for the last two are +@ and -@)

3 * / % // :- Multiply, divide, modulo and floor division

4 + - :- Addition and subtraction

5 >> << :- Right and left bitwise shift

6 & :- Bitwise 'AND'

7 ^ | :- Bitwise exclusive `OR' and regular `OR'

8 <= < > >= :- Comparison operators

9 <> == != : - Equality operators

10 = %= /= //= -= += *= **= :- Assignment operators

11 is is not :- Identity operators

12 in not in :- Membership operators

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.

 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
 a condition
 a colon
 starting on the next line, an indented block of code(called the elif
clause)
 else keyword
 a colon
 starting on the next line, an indented block of code(called the else
clause)

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 :

 Iterative statements /Loops


Block of code to be executed repeatedly can be achieved by looping/Iterative statements.
Python provides 2 ways for executing the loops.
 for loop

30
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

 Block of code will be executed multiple times without checking the


condition.
 For loops are used for sequential traversal. For example: traversing a list
or string or array etc.
 There is “for in” loop which is similar to for each loop in other languages.
 Syntax :
for iterator_variable in sequence :
for clause
 Ex1:
str="python developer"
count = 0
for x in str:
count=count+1
print(x)
print("the number of character in str is:",str)
 Ex2:
str="python developer"
count = 0
for x in str:
count=count+1
print(x)
print("the number of character in str is:",str)

 for Loops and the range() Function


 Block of code will be executed for a particular number of times.
 A for statement includes the following:
 The for keyword
 A variable name
 The in keyword
 A call to the range() method with up to three integers passed to it.
 A colon
 Starting on the next line, an indented block of code (called the for
clause)
 Syntax:
for variable in range(n)

31
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

indented block of code/for clause


 Ex1:
print('My name is')
for i in range(5):
print('Jimmy Five Times ('+ str(i) +')')
 Explanation :

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

for num in range(101):

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.

 The Starting, Stopping, and Stepping Arguments to range()


 Range() function can be called with multiple arguments separated by a
comma.
 Range() function with 2 arguments:
 The first argument indicates the for loop‟s starts value,
 The second argument indicates the for loop‟s stop value,

Ex:

for i in range(12,16):

print(i)

12 13 14 15

 Range() function with 3 arguments:


 The first argument indicates the for loop‟s starts value,
 The second argument indicates the for loop‟s stop value
 The third argument indicates step argument. The step is the
amount that the variable is increased for each iteration.

for i in range(0,10,2):

print(i)

Explanation :

range(0,10,2) will count from zero to eight by intervals of two.

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

Comparison between if and while statement

 At the end of an if clause, the program execution continues after the if


statement.
 But at the end of a while clause, the program execution jumps back to the
start of the while statement. The while clause is often called the while
loop or just the loop.
 Example

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

 These statements are similar


 In if statement, the output is simply "Hello, world.". But for the while
statement, it‟s "Hello, world." repeated five times `
 The code with the if statement checks the condition, and it prints Hello,
world. only once if that condition is true.
 The code with the while loop, on the other hand, will print it five
times. It stops after five prints because the integer in spam is incremented
by one at the end of each loop iteration, which means that the loop will
execute five times before spam < 5 is False.
 In the while loop, the condition is always checked at the start of each
iteration
 If the condition is True, then the clause is executed, and afterward, the
condition is checked again. The first time the condition is found to be
False, the while clause is skipped.

An Annoying while Loop

 Example:
name = „‟
while name ! = „your name‟
print(„Please type your name‟)
name = input()
print(„Thank you !‟)

First, the program sets the name variable to an empty string.

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

 Transfer Statements/function calls

 It is used to break the infinite loop when certain condition is met.


 It is categorised into following types:

 break
 If the execution reaches a break statement, it immediately exits the
while loop‟s clause.
 Syntax:

break

 Example :

while True:

print('Please type your name.')


name = input()

if name == 'your name':


break

print('Thank you!')

 Flow chart

 continue

36
Prepared By: TEJASHWINI P S
BANGALORE INSTITUTE OF TECHNOLOGY APPLICATION DEVELOPMENT USING PYTHON

 The continue statement in Python returns the control to the


beginning of the current loop. When encountered, the loop starts
next iteration without executing the remaining statements in the
current iteration.
 The continue statement can be used in both while and for loops.
 Syntax
continue

 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

 A function is a group of related statements that performs a specific tasks.


 Function helps to break the larger programs into smaller modules and provide the higher
degree of modularity.
 Syntax
def function_name(parameter list):
indented block of code/function body

The above syntax consists of the following component:


 Keyword def indicates the start of the header.
 function_name uniquely identifies the function and follow the identifier rules.
 Parameter list through which we pass the arguments/values to a function and are
optional.
 A colon to mark the end of the function header.
 Function body includes one or more python statements having the same
indentation level upto 4 spaces
 An optional return statement to return a value from a function.

 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:

 In python return statements can return multiple values simultaneously.


 The default return value from function is None.
Example1
def demo1():
print(“hello”)
print(demo1())

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

cal(b=50,100) //invalid: keyword follows positional argument


cal(50,a=100) //invalid: multiple values for variable a.

 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)

myFun('Hello', 'Welcome', 'to', 'BIT')

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

Example: from random import randomint(1,10)


from keyword, followed by module name, followed by import keyword followed
by star.
Example: from random import*

Local and Global Scope

 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.

 Local Variables Cannot Be Used in the Global Scope


Example :

def spam():
eggs = 31337
spam()
print(eggs)

output: NameError: name 'eggs' is not defined

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.

 Local Scopes Cannot Use Variables in Other Local Scopes


Example :
def spam():
eggs = 99
bacon()
print(eggs)

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.

The global Statement

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

 Handling above error using try and except keywords:


 Example:
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print(„Error: Invalid argument. „)

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.

A Short Program: Guess the Number


 Example:
# This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')

# Ask the player to guess 6 times.


for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!

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

You might also like