0% found this document useful (0 votes)
4 views129 pages

Module I

The document provides an introduction to Python programming, covering essential topics such as the Python character set, tokens, keywords, identifiers, literals, operators, and flow control statements. It explains the basic elements of a Python program, including input and output, expressions, and various data types. Additionally, it details conditional statements and their syntax, demonstrating how to implement decision-making in Python.

Uploaded by

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

Module I

The document provides an introduction to Python programming, covering essential topics such as the Python character set, tokens, keywords, identifiers, literals, operators, and flow control statements. It explains the basic elements of a Python program, including input and output, expressions, and various data types. Additionally, it details conditional statements and their syntax, demonstrating how to implement decision-making in Python.

Uploaded by

harshitha hc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Python

Programming
BPLCK105B/205B
Module I

PYTHON BASICS
AGENDA

Python Character Set


Tokens
Types of Tokens
Demo
Python Character set

What is Character Set?


❖Character Set- is the set of characters and symbols which can be
determined by any programming language
❖Character set basically consists of alphabets, digits, symbols or
any other special symbolic characters.
Python Character set

PYTHON
CHARACTER
SET

• Letters:- A-Z, a-z


• Digits:- 0 to 9
• Special Symbols:- + - / ( ) [ ] = ! = < > , ‘ “ $ # ; : ? &
• White Spaces:- Blank Space , Horizontal Tab, Vertical tab,
Carriage Return.
• Other Characters:- Python can process all ASCII and
Unicode Characters.
Python Character set

✔ASCII Set is the most well-known standard which defines numeric codes for characters.
✔The numeric values only define 255 characters , which contains control codes, digits,
lowercase letters, uppercase letters, symbols etc.
✔However, it is not enough for us to represent characters such as accented characters,
Chinese characters, or emoji existed around the world.
✔Therefore, UNICODE was developed to solve this issue. It defines the code point to
represent various characters like ASCII but the number of characters is up to 1,111,998.
Python Character set
Practice Session

How to obtain ASCII Values of Characters??


Usage of UNICODE Characters….
TOKENS

❖The smallest individual unit in a program is known as a token.


❖There are total 5 types of tokens in Python.
KEYWORDS

✔ Keywords are also called as reserved words these are having special meaning in
python language.
✔ The words are defined in the python interpreter hence these can’t be used as
programming identifiers.
KEYWORDS
Practice Session

How to obtain keywords of python???


identifiers

✔A Python Identifier are the names given to the fundamental building blocks of a
program
✔Names used to identify a function, class, variable, module, or other objects.
✔There are rules to be followed, for formation of identifiers
Identifiers naming conventions

Every identifier must begin with a letter or underscore, which may be followed by
any sequence of letters, digits, or underscores
Some valid names are:
myVar, var_3, this_works_too, _9lives, lives9

An identifier cannot begin with a digit.


An invalid name:
9lives
Identifiers naming conventions

We cannot use special symbols in the identifier name except underscore.


Some invalid names are:
myVar@3
We cannot use a keyword as an identifier. Keywords are reserved names in Python
and using one of those as a name for an identifier will result in a SyntaxError.
An identifier can be of infinite length.
Python is a case sensitive language
Var is different from var
LITERALS

✔Literals are often called Constant Values.


✔Examples:
‘Hello’, 23, 23.6, 0o12, 0xA2, 3+4j
TYPES OF LITERALS
operatorS

✔Operators are
special symbols in
Python that carry
out some
computation.

✔The value that the


operator operates
on is called the
operand.
punctuators

✔A punctuator is a token that


has syntactic and semantic
meaning to the interpreter,
but the exact significance
depends on the context
agenda

Bare-bones of a python program


Variables
Input and Output Statements
Bare-bones of a python program

✔ Barebones : Basic Elements


✔ Barebones of a Python Program : Basic Elements in a Python Program
✔ Barebones of a Python Program are:
❖ Expressions
❖ Statements
❖ Comments
❖ Functions
❖ Indentation
Bare-bones of a python program
Bare-bones of a python program
Reading Input From the Keyboard

✔Programs often need to obtain data from the user, usually by way of input from the keyboard.
✔The simplest way to accomplish this in Python is with input().
input([<prompt>])
✔Reads a line of input from the keyboard.
✔input() pauses program execution to allow the user to type in a line of input from the keyboard.
✔ Once the user presses the Enter key, all characters typed are read and returned as a string
Reading Input From the Keyboard

✔Note that the newline generated when the user presses the Enter key isn’t included as part of
the return string.
✔If you include the optional <prompt> argument, input() displays it as a prompt to the user
before pausing to read input
✔input() always returns a string.
✔ If you want a numeric type, then need to convert the string to the appropriate type using
type conversion functions int(), float(), or complex() [built-in functions]
Writing Output to the Console

❖Unformatted Console Output


✔ To display objects to the console, pass them as a comma-separated list of argument
to print().
print(<obj>, ..., <obj>)
✔Displays a string representation of each <obj> to the console.
✔By default, print() separates each object by a single space and appends a newline to the end
of the output
✔Any type of object can be specified as an argument to print(). If an object isn’t a string,
then print() converts it to an appropriate string representation displaying it
Writing Output to the Console

Syntax:
print(*objects, sep=' ', end='\n', file=[Link])
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one .
Default is ’ ‘ (space)
end=’end’: (Optional) Specify what to print at the end. Default is new line
file=[Link] : to print the message on File/standard output stream
Writing Output to the Console

❖ Keyword Arguments to print()

✔ print() takes a few additional arguments that provide modest control over the format of
the output.
✔ Each of these is a special type of argument called a keyword argument
✔ Keyword arguments have the form <keyword>=<value>.
✔ Any keyword arguments passed to print() must come at the end, after the list of objects
to display.
Writing Output to the Console

❖ The sep = Keyword Argument


Adding the keyword argument sep = <str> causes objects to be separated by the
string <str> instead of the default single space
❖The end= Keyword Argument
The keyword argument end = <str> causes output to be terminated by <str> instead of the
default newline
Chart : Python Data Types
What are an object’s identity, type, and value

All the data in a Python code is treated as objects. Every object has an identity,
a type, and a value.
1. IDENTITY : (object’s address in memory) identity never
changes once it has been created
• Can be known by using id()
2. TYPE : An object type is unchangeable like the identity.
• Can be known by using type()
3. VALUE : An Object
Lets understand through an example
A=“GWALIOR”
B=25

A GWALIOR
Objects/
<2002> Values
reference
variables
B 25
Identity/
< 1001> Address
Creation and deletion of a Variable
>>> Age=24
>>> del Age

Dynamic typing
>>> A=12
>>> A=“hello”

Multiple assignment
>>> A=B=C=D=24
>>> A,B,C=1,2,3
agenda

Expressions
Arithmetic Operators
Modulus Operator - Working
String Concatenation and Replication
Boolean Values
Comparison Operators
Boolean Operators
expressions

✔An expression is a combination of values, variables, and operators

Example : x + 17

✔If you type an expression in interactive mode, the interpreter evaluates it and displays the
result:

>>> 1 + 1

2
Arithmetic operators in python
Let a=10 and b =20

Operator Description Example


+ Addition - Adds values on either side of the operator a + b will give 30
- Subtraction - Subtracts right hand operand from left hand a - b will give -10
operand
* Multiplication - Multiplies values on either side of the a * b will give 200
operator
/ Division - Divides left hand operand by right hand operand b / a will give 2

% Modulus - Divides left hand operand by right hand operand b % a will give 0
and returns remainder
** Exponent - Performs exponential (power) calculation on a**b will give 10 to the power
operators 20
// Floor Division - The division of operands where the result 9//2 is equal to 4 and 9.0//2.0
is the quotient in which the digits after the decimal point is equal to 4.0
are removed.
Operator Precedence Rules

Highest precedence rule to lowest precedence rule


•Parenthesis are always respected
•Exponentiation (raise to a power) Parenthesis
Exponentiation
•Multiplication, Division, and Remainder Multiplication and Division
•Addition and Subtraction Addition and Subtraction

• PEMDAS Rule
1 + 2 ** 3 / 4 * 5

1+8/4*5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print x Note 8/4 goes before 4*5 because of the
1+2*5
11 left-right rule.

>>> 1 + 10

11
string Concatenation and Replication….

✔The meaning of an operator may change based on the data types of the values next to it.
✔For example, + is the addition operator when it operates on two integers or floating-point values.
✔ However, when + is used on two string values, it joins the strings as the string concatenation
operator.
✔The * operator is used for multiplication when it operates on two integer or floating-point values.
✔ But when the * operator is used on one string value and one integer value, it becomes the string
replication operator.
MODULUS Operator WORKING….

✔In Python, the below formula is used by modulus operator, to compute remainder
Remainder= a-(⎣a/b⎦*b)
✔Example:
(-10)-(⎣-10/3⎦*3)
(-10)-(⎣-3.33⎦*3)
(-10)-(-4*3)
(-10)-(-12)
-10+12
2
Boolean values

❖In Python, integer, floating-point, and string data types have an unlimited number of
possible values, the Boolean data type has only two values: True and False.
❖When typed as Python code, the Boolean values True and False lack the quotes you
place around strings, and they always start with a capital T or F, with the rest of the
word in lowercase.
Comparison Operators

❖Comparison operators compare two values and evaluate down to a single Boolean value.
Boolean Operators

✔The three Boolean operators (and, or, and not) are used to compare Boolean values.
✔Like comparison operators, they evaluate these expressions down to a Boolean value.
✔Binary Boolean Operators : The and and or operators always take two Boolean values (or expressions), so they’re
considered binary operators.
✔The and operator evaluates an expression to True if both Boolean values are True; otherwise, it evaluates to False.
✔The or operator evaluates an expression to True if either of the two Boolean values is True. If both are False, it
evaluates to False.
✔The not operator operates on only one Boolean value (or expression). The not operator simply evaluates to the
opposite Boolean value.
agenda

Flow Control Statements


Elements of Flow Control Statements
Types of Flow Control Statements
Flow Control statements

A program is just a series of instructions which will be executed sequentially.

But the real strength of programming isn’t just running (or executing) one instruction after
another

Based on how the expressions evaluate, the program can decide to skip instructions, repeat
them, or choose one of several instructions to run.

A Flow Control Statement defines the flow of the execution of the Program

Flow control statements can decide which Python instructions to execute under which
conditions.
Elements of Flow Control statements

Flow control statements


- start with a part called the condition, and
-followed by a block of code called the clause.
• Conditions are boolean expressions that evaluate down to a Boolean value, True or
False.
•A flow control statement decides what to do based on whether its condition is True or
False, and almost every flow control statement uses a condition.
Elements of Flow Control statements

❑ Lines of Python code can be grouped together in blocks.


❑ We can tell when a block begins and ends from the indentation of the lines of code.
❑ There are three rules for blocks.
1. Blocks begin when the indentation increases.
2. Blocks can contain other blocks.
3. Blocks end when the indentation decreases to zero or to a containing block’s
indentation.
example

Condition –
Boolean
Expression

Block of code

Flow chart
Types of flow control statements

In Python
✔ Conditional Statements
✔ Looping Statements
✔ Break, Continue and Pass Statements
Types of flow control statements
CONDITIONAL STATEMENTS (Decision Making)

❖ Python language provide the following conditional (Decision making) statements.

if statement
if...else statement
if...elif...else staement
Nested if..else statement
The if statement

❖ The if statement is a decision making statement.


❖ An if statement’s clause (that is, the block following
the if statement) will execute if the statement’s
condition is True. The clause is skipped if the
condition is False.
Syntax

if test expression:
statement(s)
53
Example program:

i=int(input(“Enter the number:”))


if (i<=10):
print(“ Condition is true”)
print(“End”)

OUTPUT OUTPUT
Enter the number: 9 Enter the number: 19
Condition is true End
End
The if..else statement

❖ 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.
❖ The if…else statement is called alternative execution, in which
there are two possibilities and the condition determines wich
one gets executed.
❖ Syntax if test expression:
statements
else:
statements
Example: Write a program to check if a number is Odd or Even

num = int(input(“Enter the number:”))


if (num % 2)== 0:
print (“Given number is Even”) else:
print(“ Given number is Odd”)

OUTPUT OUTPUT
Enter the number: 9 Enter the number: 12
Given number is Odd Given number is Even
Elif statements

✔The elif statement always follows an if or another elif statement.


✔It provides another condition that is checked only if any of the previous conditions were False.
✔In code, an elif is a keyword in Python in replacement of else if to place another condition in
the program. This is called chained conditional.
✔Elif statement always consists of the following:
• A condition (that is, an expression that evaluates to True or False)
•A colon
• Starting on the next line, an indented block of code (called the elif clause)
Elif statements

Syntax

✔ The conditions are checked one by one sequentially.


✔If any condition is satisfied, the respective statement block will be executed and further conditions are not checked.
✔Note that, the last else block is not necessary always.
Example: Program to find largest among three numbers

a = int(input(“Enter 1st number:”))


b= int(input(“Enter 2nd number:”))
c= int(input(“Enter 3rd number:”))
if (a > b) and (a > c): OUTPUT

print(a, “is greater”) Enter 1st number:10

elif (b > a) and (b > c): Enter 2nd number:25


print(b,“is greater") Enter 3rd number:15
25 is greater
else:
print(c,“is greater")
Nested if..else statements

✔We can write an entire if… else statement in another if… else statement called nesting, and
the conditional statement is called nested conditional statements.
Example program

gender=input("Enter gender:")
age=int(input("Enter age:"))
if gender == "M" :
if age >= 21:
print("Boy, Eligible for Marriage")
else:
print("Boy, Not Eligible for Marriage")
elif gender == "F":
if age >= 18:
print("Girl, Eligible for Marriage")
else:
print("Girl, Not Eligible for Marriage")
else:
print(“Invalid Gender”)
PROGRAMS

✔Write a Python Program that checks whether the number entered by the user is negative, positive or equal to zero
✔Write a Python Program to determine whether the person is eligible to vote or not, If not eligible, display how many
years are left to be eligible
✔Write a Python Program to check whether the given year is leap year or not
✔Write a Python Program to calculate the roots of a quadratic equation
✔Write a Python Program to simulate simple calculator
✔Write a Python Program to find the best of two tests average marks out of three test marks accepted from the user.
✔Write a Python Program to read two points in a co-ordinate and check in which quadrant it lies
✔Write a Python Program to find the type of triangle
✔Write a Python Program to check whether the character entered is vowel or not
Looping/iteration statements

✔Iteration is a processing of repeating some task.

✔In a real time programming, we require a set of statements to be repeated


certain number of times and/or till a condition is met.

✔Constructs that are available in python are : while and for loop
While loop

We can make a block of code to execute repeatedly with a while statement.


The code in a while clause will be executed as long as the while statement’s condition is True.
In code, a while statement always consists of the following:
• The while keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the while clause)
While loop

Syntax:
while condition: Program:
statement 1
n=1
... While n<=5:
statement n print(n)
statements_after_while n=n+1
print(“over”)
PROGRAMS

✔Program to print first 10 numbers


✔Program that asks the user for a number and prints countdown from that number to zero
✔Program to calculate sum and average of first 10 numbers
✔Program to find sum of numbers from m to n
✔Program to calculate the sum of digits of a number
✔Program to find reverse of a number
✔Program to check whether the given number is an Armstrong number or not
agenda

For Loop
Range() Function
Programs
For lo op

The while loop keeps looping while its condition is True, but what if programmer wants to execute a
block of code only a certain number of times? We can do this with a for loop statement and the range()
function.
In code, a for statement looks something like for i in range(5): and always 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)
For loop

for loop is known as a definite loop.


The for-loop iterates over a set of numbers, a set of words, lines in a file etc.

Syntax:
for variable in list/sequence/range()/string literal:
statement 1
……
statement n
Range() function

range() is a built-in function of Python. It is used when a user needs to perform an action for
a specific number of times.
The range() function is used to generate a sequence of numbers.
The range() allows user to generate a series of numbers within a given range.
Depending on how many arguments user is passing to the function, user can decide where
that series of numbers will begin and end as well as how big the difference will be between
one number and the next.
Range() function

range() takes mainly three arguments.


❖start: integer starting from which the sequence of integers is to be returned
❖stop: integer before which the sequence of integers is to be [Link] range of integers end
at stop – 1.
❖step: integer value which determines the increment between each integer in the sequence

range(stop) takes one argument.


range(start, stop) takes two arguments.
range(start, stop, step) takes three arguments.
Range() function examples
Range() function

Points to remember about Python range() function :


range() function only works with the integers i.e. whole numbers.
All argument must be integers. User can not pass a string or float number or any other type in
a start, stop and step argument of a range().
All three arguments can be positive or negative.
The step value must not be zero. If a step is zero python raises a ValueError exception.
range() is a type in Python
Programs on ‘for’ loop
PROGRAMS

✔Write a short program that prints the numbers 1 to 10 using a for loop. Then write an

equivalent program that prints the numbers 1 to 10 using a while loop.

✔Program to find sum of ‘n’ numbers, where n is read from the user

✔Program to find factorial of a number

✔Program to create the multiplication table (from 1 to 10) of a number.


agenda

Infinite Loops
Break Statement
Continue Statement
Programs
Infinite loops

✔A loop may execute infinite number of times when the condition is never going to
become false.
✔For example,
n=1 Output:
1
while True: 2
3
print(n) 4
.
n=n+1 .
.
.Continues
Break statement

✔In Programming, there is a shortcut to getting the program execution to break out of a while loop’s

clause early.

✔If the execution reaches a break statement, it immediately exits the while loop’s clause.

✔In code, a break statement simply contains the break keyword.


Break statement
Continue statement

✔Like break statements, continue statements are used inside loops.

✔When the program execution reaches a continue statement, the program execution immediately jumps

back to the start of the loop and reevaluates the loop’s condition and skipping the remaining statements

in the loop clause.


Continue statement
Break and Continue statement

✔ With the continue statement we can

stop the current iteration, and continue

with the next iteration

✔ Break terminates the loop execution


Break and Continue statement-programs

OUTPUT: Program: OUTPUT:


Program: 1 1
i=1 2 i=0
2
while i < 6: 3 while i < 6:
4
print(i) OVER i = i+1
5
if i == 3: if i == 3:
6
break continue
OVER
i = i+1 print(i)
print(“OVER”) print(“OVER”)
programs

Program that keeps reading a value from the user until the user enters a negative number
while True:
x=int(input("Enter a number:"))
if x>= 0:
print("You have entered ",x)
else:
print("You have entered a negative number!!")
break #terminates the loop
#end of while
programs

sum=0
count=0 Program to keeps reading
while True: numbers from the user and
x=int(input("Enter a number:"))
if x%2 !=0:
terminates when it
continue computes sum of 5 even
else: numbers
sum+=x
count+=1
if count==5:
break

print("Sum= ", sum)


programs

Write a program that reads ‘n’ numbers from the user and computes the sum of numbers that are
divisible by 3
Write a Program that keeps reading numbers from the user and terminates when it computes sum of
5 odd numbers
Write a Program to calculate the sum of 10 numbers read from the user. If the user enters a
negative number, it's not added to the result
Recap..

Infinite Loops
Break Statement
Continue Statement
Programs
agenda..

Else block with iteration statements


Pass Statement
Nested Loops
Programs
Else block with iteration statements

✔A while loop may have an else statement after it[optional].


✔ When the condition becomes false, the block under the else statement (clause) is
executed.
✔However, it doesn’t execute if you break out of the loop or if an exception is raised.
Else block with iteration statements
Else block with iteration statements

a=3
while(a>0): OUTPUT:
3
print(a)
2
a=a-1
1
else: Reached 0
print("Reached 0") OVER

print(“OVER”)
Else block with iteration statements
a=3
while (a>0):
print(a) OUTPUT:

a=a-1 3
2
if a==1:
OVER
break
else:
print("Reached 0")
print(“OVER”)
Else block with iteration statements

OUTPUT:
for i in range(10): 0
1
print(i)
2
if(i==7):
3
break 4
else: 5
print("Reached else") 6
7
print(“OVER”)
OVER
Else block with iteration statements

OUTPUT:
for i in range(10): 0
1
print(i)
2
else:
3
print("Reached else") 4
print(“OVER”) 5
6
7
OVER
Pass statement

✔When we need a particular loop, class, or function in our program, but don’t know what goes in
it, we place the pass statement in it.
✔It is a null statement.
✔The pass statement is useful when you don’t write the implementation of a function but you
want to implement it in the future.
✔The difference between a comment and a pass statement in Python is that while the interpreter
ignores a comment entirely, pass is not ignored.
✔The interpreter does not ignore it, but it performs a no-operation (NOP).
✔Empty code is not allowed in loops, function definitions, class definitions, or in if statements.
Pass statement

✔Syntax of pass:
pass
✔Example:
for x in [0, 1, 2]:
pass
Nested loops

✔We can also nest a loop inside another.


✔We can put a for loop inside a while, or a while inside a for, or a for inside a for, or a
while inside a while.
✔Example: OUTPUT:

for i in range(1,6): *
for j in range(i): **
print("*",end=' ') ***
****
print()
*****
Recap..

Else block with iteration statements


Pass Statement
Nested Loops
ProgramS
agenda..

Functions
User Defined Functions
Programs
Functions

✔A function is a block of code which is designed to


perform a specific task.
✔A Function executes only when it is being called.
✔We can pass data, known as parameters, into a
function.
✔A function can return data as a result.
User-Defined Functions

The syntax of user-defined function would be –


def fname(arg_list):
Statement_1
Statement_2
……………
Statement_n
return value
User-Defined Functions

Here
✔def is a keyword indicating it as a function definition.
✔fname is any valid name given to the function
✔arg_list is list of arguments taken by a function. These are treated as inputs to the function from the
position of function call. There may be zero or more arguments to a function.
✔statements are the list of instructions to perform required task.
✔return is a keyword used to return the output value. This statement is optional
User-Defined Functions - EXAMPLE

def myfun(): # function definition


print("Hello")
print("Inside the function")

print("Example of function")
myfun() # function call
print("Example over")
User-Defined Functions

✔ The function definition creates an object of type function.


✔In the above example, myfun is internally an object.
✔This can be verified by using the statement –
>>>print(myfun) # myfun without parenthesis
<function myfun at 0x0219BFA8>
>>> type(myfun) # myfun without parenthesis
<class 'function'>
✔ Here, the first output indicates that myfun is an object which is being stored at the memory address 0x0219BFA8 (0x
indicates octal number).
✔The second output clearly shows myfun is of type function.
User-Defined Functions

To understand the flow of execution of the program.


User-Defined Functions programs

✔Program to add two numbers using functions


✔Write a function that finds a square of a number
✔Write a function that find area of rectangle.
✔Write a function that finds area of circle.
✔Write a function that finds whether a number is odd or even.
✔Write a function named solve that returns reminder and quotient of two numbers on
division.
Importing Modules

In code, 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 with the random module, which will give us access to the [Link]() function.

import random
for i in range(5): 4
print([Link](1, 10)) 1
8
4
•When we run this program, the output will look something like this: 1
Importing Modules

All Python programs can call a basic set of functions called built-in functions, including the
print(),input(), and len() functions

Python also comes with a set of modules called the standard library.

Each module is a Python program that contains a related group of functions that can be
embedded in the programs.

For example, the math module has mathematics-related functions, the random module has
random number–related functions, and so on. Before we can use the functions in a module,
we must import the module with an import statement.
Ending A Program Early With [Link]()

Program Termination happens when the program execution reaches the bottom of the
instructions.
However, we can cause the program to terminate, or exit, by calling the [Link]() function.
Since this function is in the sys module, we have to import sys before program uses it.

Example:

import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
[Link]()
print('You typed ' + response + '.')
• This program has an infinite loop with no break statement inside. The only way this
program will end is if the user enters exit, causing [Link]() to be called. When
response is equal to exit, the program ends.

• Since the response variable is set by the input() function, the user must enter exit in
order to stop the program.
Recap..

Functions
User Defined Functions
Programs
agenda..

Local and Global Scope


The global Statement
Advantages of Functions
Local and Global Scope

✔Parameters and variables that are assigned in a called function are said to exist in that
function’s 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.
Local and Global Scope
✔Scope - container for variables. When a scope is destroyed, all the values stored in the scope’s variables are forgotten.
✔The global scope is created when the program begins. When the program terminates, the global scope is destroyed, and all
its variables are forgotten.
✔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.
✔Points to be remembered are
▪ Local Variables Cannot Be Used in the Global Scope
▪ Local Scopes Cannot Use Variables in Other Local Scopes
▪Global Variables Can Be Read from a Local Scope
▪Local and Global Variables with the Same Name
Local Variables Cannot Be Used in the Global Scope

def spam():
eggs = 31337 #local variable

spam()
print(eggs) # local variable cannot be used in global scope

NameError: name 'eggs' is not defined-- ?????


Local Scopes Cannot Use Variables in Other Local Scopes

def spam():
eggs = 99
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
spam()

99 -- ?????
Global Variables Can Be Read from a Local Scope

def spam():
print(eggs)
eggs = 42 # global variable
spam()
print(eggs)

42-- ?????
Local and Global Variables with the Same Name

def spam():
eggs = 'spam local'
print(eggs) # local variable in spam bacon local
spam local
def bacon(): bacon local
eggs = 'bacon local' global

print(eggs) # local varible in bacon The variables are as follows:


spam()
A variable named eggs that exists in a local scope when
print(eggs) # local variablein bacon spam() is called.
eggs = 'global' A variable named eggs that exists in a local scope when
bacon() is called.
bacon() A variable named eggs that exists in the global scope.
print(eggs) # global variable
Global statement

✔If we need to modify a global variable from within a function, we can use the global statement.
✔Example;
def spam():
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs)
Why functions??

✔Functions makes the program easier to read, understand, and debug.


✔Repetitive code can be eliminated. if any modifications required it can be done only at one place
✔Debugging is easier.
✔Reusability.
✔To use function, we must know what are its inputs (the parameters) and output value; we don’t
always have to burden with how the function’s code actually works. In high-level way, it’s common
to say that functions are treated as a “black box.”
Recap..

Local and Global Scope


The global Statement
Advantages of Functions
agenda..

Exception
Exception Handling
Types of Exceptions
Program Demo
Exception handling

✔Consider the following code segment –


a=int(input("Enter a:"))
b=int(input("Enter b:"))
c=a/b
print(c)

✔When you run the above code, one of the possible situations would be –
Enter a:12
Enter b:0

✔ZeroDivisionError: division by zero


Exception handling

❑An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions.
❑In general, when a Python script encounters a situation that it cannot cope with,
it raises an exception.
❑An exception is a Python object that represents an runtime error.
❑When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
Exception handling

✔Exceptions can be handled with try and except statements.


✔The code that could potentially raise an exception is put in a try clause. The program execution moves to
the start of a following except clause if an exception happens.
Types of exceptions
Exception handling
“ Thank You!


ANY QUESTIONS?
Fibonacci number

nterms = int(input("How many terms? "))


n1 = 0 n1 = n2
n2 = 1 n2 = nextno
count = 0 count += 1
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nextno=n1 + n2

You might also like