Module I
Module I
Programming
BPLCK105B/205B
Module I
PYTHON BASICS
AGENDA
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
✔ 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
✔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
✔Operators are
special symbols in
Python that carry
out some
computation.
✔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
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
✔ 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
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
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
% 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
• 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
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
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)
if statement
if...else statement
if...elif...else staement
Nested if..else statement
The if statement
if test expression:
statement(s)
53
Example program:
OUTPUT OUTPUT
Enter the number: 9 Enter the number: 19
Condition is true End
End
The if..else statement
OUTPUT OUTPUT
Enter the number: 9 Enter the number: 12
Given number is Odd Given number is Even
Elif statements
Syntax
✔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
✔Constructs that are available in python are : while and for loop
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
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
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
✔Write a short program that prints the numbers 1 to 10 using a for loop. Then write an
✔Program to find sum of ‘n’ numbers, where n is read from the user
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.
✔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
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
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..
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
for i in range(1,6): *
for j in range(i): **
print("*",end=' ') ***
****
print()
*****
Recap..
Functions
User Defined Functions
Programs
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
print("Example of function")
myfun() # function call
print("Example over")
User-Defined Functions
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..
✔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
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
✔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??
Exception
Exception Handling
Types of Exceptions
Program Demo
Exception handling
✔When you run the above code, one of the possible situations would be –
Enter a:12
Enter b:0
❑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
”
ANY QUESTIONS?
Fibonacci number