Python Input, Output, and Control Statements
Python Input, Output, and Control Statements
Chapter 2
Syntax:
print(“expression”/constant/variable)
Example:
print(“hello”) # it display hello
print(10) # it display 10
a=5
print('The value of a is', a) # it display The value of a is 5
Syntax:
▪ If prompt is present, it is displayed on monitor, after which the user can provide
data from keyboard.
▪ Input takes whatever is typed from the keyboard and evaluates it.
▪ As the input provided is evaluated, it expects valid python expression.
▪ If the input provided is not correct then either syntax error or exception is raised by
python.
Example
x=input(“Enter data‟)
-------------------------------------------------------------------------------------------
CONTROL STATEMENTS
▪ Generally execution of program takes place sequentially sometimes we need to skip
some statements and repeat some statements, that time we switch to the control
statement.
▪ Control statements define the direction or flow in which execution of a program
should take place.
SEQUENCE:
▪ It is the order in which the statements are executed one after the other from top to
bottom direction or left to right direction.
▪ By default all programming logics are sequence.
Example:
p = int(input("Enter the principle amount: "))
r = float(input("Enter the rate of interest: "))
t = int(input("Enter the time period: "))
si = (p * r * t) / 100
print("\nSimple interest:", si)
-----------------------
SELECTION OR BRANCHING.
Branching statements are decision making statement, are used to select one path
based on the result of the evaluated expression.
Python If Statements
▪ The Python if statement is a statement which is used to test specified condition.
▪ We can use if statement to perform conditional operations in our Python application.
▪ The if statement executes only when specified condition is true.
▪ We can pass any valid expression into the if parentheses.
There are various types of if statements in Python:
➢ If statement
➢ If-else statement
➢ Elif statement
➢ Nested if statement
if statement:
▪ The if statement is the simplest form of selection statement.
▪ It is very frequently used in decision making and altering the flow of execution of
the program.
Syntax:
if (condition) :
Statement-1
Example:
a=10
if (a==10):
print("the value of a is 10")
If the values of the variable a is 10 then only the print statement gets executed.
Otherwise, it is skipped.
If Else Statements
▪ The If statement is used to test specified condition and if the condition is true, if
block executes, otherwise else block executes.
▪ The else statement executes when the if statement is false.
Syntax:
if (condition) :
Statement-block-1
else :
Statement-block-2
ELIF statement
▪ The elif is short for else if. It allows us to check for multiple expressions.
▪ If the condition for if is False, it checks the condition of the next elif block and so on.
▪ If all the conditions are False, the body of else is executed.
▪ Only one block among the several if...elif...else blocks is executed according to the
condition.
▪ The if block can have only one else block. But it can have multiple elif blocks.
Syntax:
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example program
'''In this program, we input a number check if the number is positive or negative or zero
and display an appropriate message This time we use nested if statement'''
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
--------------------------------------------
3. LOOPING OR ITERATION
Syntax:
while expression:
statements
Example program,
n = int(input("Enter a number: "))
while i <= n:
fact *= i
i += 1
print("\nFactorial of", n, "is:", fact)
The for loop in Python is used to iterate the statements or a part of the program
several times.
It is frequently used to traverse the data structures like list, tuple, or dictionary.
Syntax
for iterating_var in sequence:
statement(s)
Example 1
str = "Python"
for i in str:
print(i)
Example 2
list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)
Syntax:
range(start,stop,step size)
– The step size is used to skip the specific numbers from the iteration. It is optional
to use.
– By default, the step size is 1.
– range(5) It generates a sequence is [0,1, 2, 3, 4 ]
– range(2,9) It generates a sequence is [ 2, 3, 4, 5, 6, 7, 8]
– range(2,10,2) It generates a sequence is [ 2, 4, 6, 8]
Example
n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
NESTED LOOPS:
Python programming language allows to use one loop inside another loop.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
Output:
1
22
333
4444
------------------------------------------------
4. JUMPING
▪ The statements which are unconditionally transferring the program control within a
program are called jump statement.
▪ Loop control statements change execution from its normal sequence.
▪ When execution leaves a scope, all automatic objects that were created in that
scope are destroyed.
▪ The jump statements are
o break
o continue
o pass
▪ When the loops are nested, the break statement only exits from the loop containing
it. That means the break will exit only single loop.
Syntax:
break
Example
i=1
while(i<=10):
print i if(i==4):
break
i=i+1
print “Out of loop”
Syntax:
Continue
Example
i=0
while(i<=9):
i=i+1
if(i==4):
continue
print i
print “Out of loop”
Syntax:
pass
Example
i=0
while(i<=5):
i=i+1
if(i==4):
pass print i
print "Out of loop"
-------------------------------------------------------------------------------------------
PYTHON ARRAYS
▪ Array is a collection of homogeneous elements or array is a collection of similar data
elements under single name.
▪ In python array can increase or decrease their size dynamically. It means, we need
not declare the size of the array.
▪ When the elements are added, it will increase its size and when the elements are
removed, it will automatically decrease its size in memory.
Creating an Array:
▪ In python, there is a standard module by the name ‘array’ the helps to create and
process the arrays.
▪ The array module is import to python program by using import statement.
Syntax:
import array
arrayName = array(typecode, [elements])
– ‘array’ is the standard module in python, which helps to create and process the
arrays.
– where typecode represents the type of array.
– In other words type of data stored in an array.
– The typecode should be enclosed in single quote(‘ ‘).
Minimum
TypeCode Type Description size
in bytes
b Signed integer 1
B Unsigned integer 1
i Signed integer 2
I Unsigned integer 2
l Signed integer 4
L Unsigned integer 4
f Floating point 4
Double precession floating
d 8
point
u Unicode character 2
Example
X=array(‘i’ ,[4, 6, 3, 8])
– This is creating an integer array with the name X and store whole number each
taking 2 bytes memory.
Example program 1
import array as arr
a=[Link]('d', [1.1 , 2.1 ,3.1] )
print(a)
output:
enter araay limit 3
enter array elements
20
30
10
array('i', [20, 30, 10])
2. Remove():
Remove any array element using remove() method
output
array('i', [1, 2, 3, 5])
3. Pop():
Remove last array element using pop() method, pop removes the last element
from the array.
output
array('i', [1, 2, 3, 4])
So we see that the last element (5) was popped out of array.
4. Index():
Fetch any element through its index using index(), this methis returns first index
of the matching value. Remember that arrays are zero-indexed.
output:
5
5. reverse()
The reverse() method reverses the given data.
output
array('i', [5, 4, 3, 2, 1])
----------------------------------------------------------------------------------------------
MULTI-DIMENSIONAL ARRAY
▪ An array containing more than one row and column is called multidimensional array.
Matrix in Numpy
▪ In python we can show matrices as 2D array using Numpy.
▪ NumPy is a general-purpose array-processing package.
▪ It provides a high-performance multidimensional array object, and tools for
working with these arrays.
Example:
import numpy as np
a=[Link]([[1,2,3],[4,5,6]])
print(a)
Example:
a=[Link]([[1,2,3],[4,5,6]])
print(a)
print([Link])
Example 2:
2. itemsize()
The itemsize() is used to calculate the byte size of each element.
Example:
3. Shape()
Example
This means the array has two dimensions, and each dimension contains two elements.
4. reshape()
The reshape() function is used to reshape the array.
Example
Now the array has three dimensions, with two elements in each dimension.
5. append()
The append() function is used to add new values to an existing array.
Example:
Example: Matrix_Operation.py
import numpy as np
a=[Link]([[1,2,3],[4,5,6]])
b=[Link]([[1,2,3],[4,5,6]])
c=a+b
print(c)
c=a*b
print(c)
c=a-b
print(c)
OUTPUT:
[[ 2 4 6]
[ 8 10 12]]
[[ 1 4 9]
[16 25 36]]
[[0 0 0]
[0 0 0]]
----------------------------------------------------------------------------------------------
FUNCTIONS-
▪ Function is a group of statements and perform a specific task
▪ When a function is written inside a class, it becomes a method, A method can be
called using object / class name
– The def keyword, along with the function name is used to define the function.
– The identifier rule must follow the function name.
– A function accepts the parameter (argument), and they can be optional.
– The function block is started with the colon (:), and block statements must be at
the same indentation.
– The return statement is used to return the value. A function can have only
one return
Example
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())
Types of function:
Functions are three types, There are:
➢ Built-in function
➢ Module
➢ User-defined function.
➢ Built-in Functions:
▪ Built-in functions are the functions that are built into Python and can be accessed by
programmer any time without importing any module.
Example,
X= abs(-34)
Y=min(5,2,7,19)
Z=max(2,20,4,33,21)
Pirnt(range(1,5))
➢ Module:
▪ A module is a file that contains a collection of related functions and other definitions.
▪ Modules are extensions that can be imported into Python programs.
▪ Module are user-defined modules or built in module.
Built in module:
Python has a math module that includes a number of specialized mathematical
tools. To include math module into your program by importing it.
Example:
File name : [Link]
def sum1(a,b):
c = a+b
return c
def mul1(a,b):
c = a*b
return c
Filename: Test_module1.py
import module1
x = 12
y = 34
➢ User-Defined Functions:
A user defined function represents a function which is named and provided by user to
produce the desired and certain output.
Syntax:
def function-Name(argument-list) : #Function header
St-1 St-2
: # Function body
St-n return()
Example:
def printname(str):
print str
return
printname("Python")
----------------------------------------------------------------------------------------
Types of Parameters or Formal Arguments:
The user defined functions can be call by using the following types of formal arguments.
➢ Required arguments
➢ Keyword arguments
➢ Default arguments
➢ Variable –length arguments
Required Arguments:
▪ Required arguments are the arguments passed to a function in correct positional
order.
▪ The number of arguments in the function call should match exactly with the function
definition.
Example:
def printinfo(name,sem)
print name
print sem
return
printinfo(“aaa”,6)
In the above example, we have passed two arguments. The function definition contains
two arguments to receive those values.
Keyword Arguments:
▪ Keyword arguments are the arguments with assigned values passed in the function
call statement, i.e., when you use keyword argument in a function call, the caller
identifies the arguments by the parameter name.
▪ The Python interpreter is able to use the keywords provided to match the values
with parameters.
Example:
def printinfo(name,sem)
print name
print sem
return
printinfo(sem=6,name=“aaa”)
In the above example, we passed arguments with different order and then the caller
identifies the arguments by the parameter name.
Default Arguments:
▪ A default argument is an argument that assumes a default values if a value is not
provided in the function call for that argument.
▪ A parameter having default value in the function header is known as a default
parameter.
Example:
def printinfo(name=”bbb”,sem=6)
print name
print sem
return
printinfo()
printinfo(sem=6)
printinfo(name=“aaa”,sem=2)
In the above example, first call, we missing both the arguments and then function take
default values. In second time call, we missing one argument and then take name
values as the default value. In third time call, we r not missing any arguments and then
function takes both the arguments provided by the user.
Variable-length arguments:
➢ To process a function for more arguments than you specified while defining the
function. These arguments are called variable length arguments and are not named
in the function definition, unlike required and default arguments.
➢ A asterisk (*) is placed before the variable name that will hold the values of all non-
keyword variable arguments. This tuple remains empty if not additional arguments
are specified during the function call.
Example:
def printinfo(arg1, *vartuple)
print arg1
for k in vartuple :
print k
return
printinfo(10)
printinfo(1,2,3,4,5)
----------------------------------------------------------------------------------------
RECURSION
A recursive function is one that invokes itself. Or A recursive function is a function
that calls itself in its definition.
Example:
def factorial(n):
if n == 0:
return( 1)
else:
return (n*factorial(n-1)) # Recursive call
Syntax:
List-var =[ele1,ele2, …,elen]
Example,
k=[1,2,3,4,5,”python”]
List Operations:
Let us consider the list k=[1,2,3,4,5,”PYTHON”]
1. Indexing:
▪ For accessing an element of the list, indexing is used.
▪ List index starts from 0 in left to right method.
▪ Working from right to left, the first element has the index -1, the next one -2
and so on, but left most element is still 0.
Example:
print k[2] # output is 3
2. Slicing:
▪ A slice of a list is sub-list.
▪ Slicing using to access range of elements.
▪ This operation using two indices, separated by colon(:).
▪ First index is the starting point to extraction starts and second index is the last
point to be stop.
Example
Print k[2:5] #output is 3,4,5
4. Repeating list:
▪ Multiplying a list by an integer n creates a new list that repeats the original list n
times.
▪ The operator * is used to repeating the list by n times.
Example
a=[1,2,3]
print (a*3) # It produce [1,2,3,1,2,3,1,2,3]
------------------------------------------
List functions and methods:
1. len(): It is used to get the length of a list.
Example:
k=[]
for i in range(0,3):
el=input("enter value")
[Link](el)
print(k)
print(len(k))
Example
k=[]
for i in range(0,3):
el=input("enter value")
[Link](el)
print(k)
Example
k=[]
for i in range(0,3):
el=input("enter value")
[Link](el)
print(k)
[Link](5,30)
print(k)
4. remove(value):
To remove the first occurrence of the specified element from the list.
Example
k=[]
for i in range(0,3):
el=input("enter value")
[Link](el)
print(k)
[Link](20)
print(k)
5. sort(): This function used to sort/arrange the list item.
Example
k=[]
for i in range(0,3):
el=input("enter value")
[Link](el)
print(k)
[Link]()
print(k)
Example
k=[]
for i in range(0,3):
el=input("enter value")
[Link](el)
print(k)
print([Link]())
Characteristics of a Dictionary:
▪ A dictionary is an unordered collection of objects.
▪ Values are accessed using a key
▪ A dictionary can shrink or grow as needed
▪ The contents of dictionaries can be modified.
▪ Dictionaries can be nested.
▪ Sequence operations, such as slice cannot be used with dictionary
Example
OUTPUT:
{}
{1: 'apple', 2: 'ball'}
{'name': 'John', 1: [2, 4, 3]}
Example
my_dict = {'name': 'aaa', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
OUTPUT:
Jack
26
Example
d = {1: "one", 2: "two"}
[Link]()
print('d =', d)
Output
d = {}
Example
original = {1:'one', 2:'two'}
new = [Link]()
print('Orignal: ', original)
print('New: ', new)
Output
Orignal: {1: 'one', 2: 'two'}
New: {1: 'one', 2: 'two'}
Example
person = {'name': 'Phill', 'age': 22}
print('Name: ', [Link]('name'))
print('Age: ', [Link]('age'))
print('Salary: ', [Link]('salary'))
print('Salary: ', [Link]('salary', 0.0))
Output
Name: Phill
Age: 22
Salary: None
Salary: 0.0
Example
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print([Link](4))
Example
person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}
print([Link]())
empty_dict = {}
print(empty_dict.keys())
Output
dict_keys(['name', 'salary', 'age'])
dict_keys([])
Example
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print([Link]())
Output
dict_values([2, 4, 3])
Example
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print([Link]())
Output
dict_items([('apple', 2), ('orange', 3), ('grapes', 4)])
----------------------------------------------------------------------------------------
SET
▪ A set is an unordered collection of items.
▪ Every set element is unique (no duplicates) and must be immutable (cannot be
changed).
▪ However, a set itself is mutable. We can add or remove items from it.
▪ Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.
# set of integers
my_set = {1, 2, 3}
print(my_set)
Output
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}
Set Operations
Set Operations
Python provides the methods for performing set union, intersection, difference,
and symmetric difference operations.
Example:
s1 = {1, 4, 5, 6}
s2 = {1, 3, 6, 7}
print([Link](s2))
print(s1 | s2)
print([Link](s2))
print(s1 & s2)
print([Link](s2))
print(s1 - s2)
print(s1.symmetric_difference(s2))
print(s1 ^ s2)
---------------------------------------------------------------------------------------
TUPLE
▪ A tuple is similar to list.
▪ A tuple contains group of elements which can be different types.
▪ Thes elements in the tuple are separated by commas and enclosed in parentheses
(). The only difference is that tuple are immutable.
▪ Tuples once created cannot be modified.
▪ The tuple cannot change dynamically. That means a tuple can be treated as read-
only list.
Syntax:
file_object = open(file_name ,access_mode)
– The first argument file_name is specifies the name of the filename that is to be
opened.
– The second argument access_mode is determines in which mode the file has to
be opened, that is, read, write and append.
Examples:
1. f = open (‘[Link]', 'r')
This statement creates a file object as f, it opens the [Link] file as read
only purpose if the file is exists.
This statement creates a file object as f, it creates new file [Link] for write
purpose if the file is does not exists. If the file is exists overwrite the file.
Examples:
f = open("[Link]",'a')
[Link]("100, maya,6 sem")
[Link]()
Reading Data
▪ After a file is opened for reading data, you can use the read() method to read a
specified number of characters or all characters from the file and return them as a
string, the readline() method to read the next line, and the readlines() method
to read all the lines into a list of strings.
Examples:
f = open ("[Link]", "a")
[Link]("abc 100 fg 50.3")
for i in range(1,10):
[Link]("%d" %i)
[Link]()
f = open ("[Link]", "r")
c=[Link]()
print(c)
------------------------------------------------------------------------------------------
EXCEPTION HANDLING:
▪ An Exception is a condition that is caused by a run-time error in the program.
▪ When the Python interpreter encounters an error such as dividing an integer by zero,
it creates an Exception object and throws it [i.e., informs us that, an error has
occurred].
▪ If the Exception object is not caught and handled property, the interpreter will
display an error message and will terminate the program.
▪ If we want the program to continue with the execution of the remaining code, then
we should try to catch the Exception object thrown by the error condition and then
display an appropriate message for taking corrective actions. This task is known as
Exception handling.
▪ The purpose of Exception handling mechanism is to provide a means to detect and
report an “Exceptional circumstance”, So that appropriate action can be taken, the
mechanism performs the following task:
o Find the error/ detect the error [hit the Exception].
o Inform that an error has occurred [throw the Exception].
o Receive the error information [catch the Exception].
o Take corrective actions / appropriate actions [handle the Exception].
Syntax:
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
If the Python program contains suspicious code that may throw the exception, we must
place that code in the try block.
The try block must be followed with the except statement, which contains a block of
code that will be executed if there is some exception in the try block.
Examples:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
We can also use the else statement with the try-except statement in which, we can
place the code which will be executed in the scenario if no exception occurs in the try
block.
The syntax to use the else statement with the try-except statement is given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
Example:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
Common Exceptions
▪ Python provides the number of built-in exceptions, but here we are describing the
common standard exceptions.
▪ A list of common exceptions that can be thrown from a standard Python program is
given below,
o ZeroDivisionError: Occurs when a number is divided by zero.
o NameError: It occurs when a name is not found. It may be local or global.
o IndentationError: If incorrect indentation is given.
o IOError: It occurs when Input Output operation fails.
o EOFError: It occurs when the end of the file is reached, and yet operations
are being performed.
finally block:
▪ This can be used to handle an exception that is not caught by any of the previous
except statements.
▪ Finally block can be used to handle any exception generated within a try block.
▪ It may be added immediately after the try block or after the last except block.
▪ When a finally block is defined, this is guaranteed to execute, regardless of whether
or not an exception is thrown.
▪ As a result, we can use it to perform certain housekeeping operations such as closing
files and releasing system resources.
Syntax
try:
<body>
except <ExceptionType-1>:
<handler>
except <ExceptionType-2>:
<handler>
:
except <ExceptionType-n>:
<handler>
finally :
<handler>
-------------------------------------------------------------------------------------------
MULTI THREADING
▪ Multithreading is a conceptual programming paradigm where a program (process) is
divided into two or more subprograms (process), which can be implemented at the
same time in parallel.
▪ A Thread is similar to a program that has a single flow of control.
▪ It has beginning, a body and an end, and executes command sequentially.
▪ Every java program will have at least one thread called main thread.
Runnable
As the newly born thread is started, the thread becomes runnable i.e. waiting to run.
In this state, it has all the resources but still task scheduler have not scheduled it to
run.
Running
In this state, the thread makes progress and executes the task, which has been chosen
by task scheduler to run. Now, the thread can go to either the dead state or the non-
runnable/ waiting state.
Non-running/waiting
In this state, the thread is paused because it is either waiting for the response of some
I/O request or waiting for the completion of the execution of other thread.
Dead
A runnable thread enters the terminated state when it completes its task or otherwise
terminates.