0% found this document useful (0 votes)
95 views32 pages

Python Input, Output, and Control Statements

This document provides an overview of creating Python programs, focusing on input and output statements, control statements, and looping constructs. It explains the usage of functions like print() and input(), along with various control structures such as if statements, loops, and jump statements. Additionally, it covers the creation and manipulation of arrays in Python, including built-in array methods.

Uploaded by

P Shashidhar
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)
95 views32 pages

Python Input, Output, and Control Statements

This document provides an overview of creating Python programs, focusing on input and output statements, control statements, and looping constructs. It explains the usage of functions like print() and input(), along with various control structures such as if statements, loops, and jump statements. Additionally, it covers the creation and manipulation of arrays in Python, including built-in array methods.

Uploaded by

P Shashidhar
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

PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

Chapter 2

CREATING PYTHON PROGRAMS


INPUT AND OUTPUT STATEMENTS
Python provides functions like input() and print() are widely used for standard
input and output operations respectively.

Python Output statement Using print() function:


▪ The print() function prints the specified message to the screen.
▪ The message can be a string, or any other object, the object will be converted into
a string before written to the screen.

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

Python input statement Using input() function:


The input() function read values for a particular variable.

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 1


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

Python supports four types of control statements.


1. Sequence.
2. Selection or branching.
3. Looping or iteration.
4. Jumping.

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

– The condition / expression must be enclosed within parentheses.


– The expression / condition is evaluated true, to perform the statement-1,
otherwise skip the statement-1 and perform next statement followed by if
structure.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 2


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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

– The condition within the parenthesis is evaluated to true then statement-block-1


is executed otherwise statement-block-2 is executed.
– The condition may be simple, compound or complex.
– Blocks can have multiple lines.
– As long as they are all indented with the same amount of spaces, they constitute
one block.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 3


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

Example program Check if the given year is leap year or not.

year = int(input("Enter the year: "))


if (year % 4):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")

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

Example program Check if the given number is positive, negative or zero.

n = float(input("Enter any number: "))


print()
if n > 0:
print(n, "is a positive number.")
elif n == 0:
print("The entered value is ZERO.")
else:
print(n, "is a negative number.")
– When variable num is positive, Positive number is printed.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 4


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

– If num is equal to 0, Zero is printed.


– If num is negative, Negative number is printed.
---------------------------------------
Nested if statement
▪ In this construct introduce new condition only if the pervious condition is true.
▪ The second if is nested in the first if condition.
▪ When the first condition is true, then second if condition is tested.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 5


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

A loop statement allows us to execute a statement or group of statements


multiple times.

WHILE LOOP STATEMENT


A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true.

Syntax:
while expression:
statements

– Here, the statements can be a single statement or a group of statements.


– The expression should be any valid Python expression resulting in true or false.
– The true is any non-zero value and false is 0.

While loop Flowchart

Example program,
n = int(input("Enter a number: "))
while i <= n:
fact *= i
i += 1
print("\nFactorial of", n, "is:", fact)

Using else with while loop


Python allows us to use the else statement with the while loop also. The else
block is executed when the condition given in the while statement becomes false.

Consider the following example.


i=1
n = int(input("Enter a number: "))
while(i<=5):
print(i)
i=i+1
else:
print("The while loop exhausted")
FOR LOOP STATEMENT

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 6


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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)

For loop Using range() function


The range() function
▪ The range() function is used to generate the sequence of the numbers.
▪ If we pass the range(10), it will generate the numbers from 0 to 9.
The syntax of the range() function is given below,

Syntax:
range(start,stop,step size)

– The start represents the beginning of the iteration.


– The stop represents that the loop will iterate till stop-1.
– The range(1,5) will generate numbers 1 to 4 iterations.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 7


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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

# Python program to illustrate nested for loops in Python


for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()

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

The break statement:


▪ The break statement is used to terminate loops.
▪ When a break statement is encountered inside a loop, the loop is immediately
terminated and next statement immediately following the loop is executed.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 8


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

▪ 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”

The continue statement:


▪ The name implies that loop to be continued with next iteration.
▪ The continue statement tells the python interpreter to skip the following statements
and continue with next iteration i.e. control automatically passes to the beginning of
the loop.
▪ In while loop, continue causes control to transfer directly to the conditional part and
continue the iteration.
▪ In case of for loop, update section of the loop will execute before test condition is
evaluated.

Syntax:
Continue

Example
i=0
while(i<=9):
i=i+1
if(i==4):
continue
print i
print “Out of loop”

The pass statement:


▪ The pass statement does not do anything.
▪ It is used with “if statement” or inside a loop to represent no operation.
▪ We use pass statement when we need a statement syntactically but we do not want
to do any operation.
▪ Pass is also used for empty control statement, function and classes.

Syntax:
pass

Example
i=0

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 9


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

while(i<=5):
i=i+1
if(i==4):
pass print i
print "Out of loop"

Difference between break and continue statement:

-------------------------------------------------------------------------------------------

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 10


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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)

Example program 2 (to read n number and display)


import array as arr
n=int(input("enter araay limit"))
a=[Link]('i',[])
print("enter array elements")
for i in range(0, n):
ele = int(input())
[Link](ele)
print(a)

output:
enter araay limit 3
enter array elements
20
30
10
array('i', [20, 30, 10])

BUILT-IN ARRAY METHODS:


1. append()
Append any value to the array using append()

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 11


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

my_array = array('i', [1,2,3,4,5])


my_array.append(6)

2. Remove():
Remove any array element using remove() method

my_array = array('i', [1,2,3,4,5])


my_array.remove(4)

output
array('i', [1, 2, 3, 5])

We see that the element 4 was removed from the array.

3. Pop():
Remove last array element using pop() method, pop removes the last element
from the array.

my_array = array('i', [1,2,3,4,5])


my_array.pop()

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.

my_array = [Link]('i', [1, 2, 3, 4, 5])


print(my_array.index(2))

output:
5

5. reverse()
The reverse() method reverses the given data.

my_array = [Link]('i', [1, 2, 3, 4, 5])


[Link]()
print(a)

output
array('i', [5, 4, 3, 2, 1])
----------------------------------------------------------------------------------------------

MULTI-DIMENSIONAL ARRAY
▪ An array containing more than one row and column is called multidimensional array.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 12


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

▪ It is also called combination of several 1D arrays.


▪ 2D array is also considered as matrix.

A=array([1,2,3,4]) # Represents 1D array with 1 row


B=array([1,2,3,4],[5,6,7,8]) # Represents 2D array with 2 row

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)

NumPy Array build in functions:


1. Ndim():
The ndim() attribute can be used to find the dimensions of the array,

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:

Each item occupies four bytes in the above array.

3. Shape()

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 13


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

This array attribute returns a tuple consisting of array dimensions.

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:

NumPy Mathematical Operation


▪ In NumPy, basic mathematical functions operate elementwise on an array.
▪ Matrix addition and multiplication.
▪ We can use arithmetic operators like +, -,* ,/ to perform different operations on
matrices.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 14


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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

Creating a Function / Defining Functions


Python provides the def keyword to define the function.

The syntax of the define function is given below.


def my_function(parameters):
function_block
return expression

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 15


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

▪ These functions are also called as standard functions.


▪ These functions are available in all versions of Python.

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.

WAP to illustrate math module


import math
print "Absolute value of -34.45 is ",[Link](-34.45)
print "Absolute value of 56.34 is ",[Link](56.34)
print "ceil of 100.12 is ",[Link](100.12)
print "ceil of 100.67 is ",[Link](100.67)
print "floor of 50.34 is ",[Link](50.34)
print "floor of 50.89 is ",[Link](50.89)
print "E rise to 2 is ",[Link](1)
print "squre root of 25 is ",[Link](25)

Create your own Module / Construct the user defined module:


▪ Module contain set of user defined function and regular expressions.
▪ In order to create user defined module, first create module description/user defined
functions and save with the module name along with extension py.
▪ We can those modules using other python programs my importing those module
name.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 16


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

print("Sum is ", module1.sum1(x,y))


print("Multiple is ", module1.mul1(x,y))

➢ User-Defined Functions:
A user defined function represents a function which is named and provided by user to
produce the desired and certain output.

Simple rules to defined user defined function are:


▪ A function blocks begins with the keyword def followed by function name followed
by parenthesized parameter list and the colon
▪ Any input parameters or arguments should be placed within these parentheses.
▪ The body of the function followed by colon and is indented.
▪ The return statement exits a function. The return statement contain zero or with an
argument.
▪ Calling / invoking a function by its function-name.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 17


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 18


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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

Any recursive function can be divided into two parts.


First, there must be one or more base cases, to solve the simplest case, which is
referred to as the base case or the stopping condition
Next, recursive cases, here function is called with different arguments, which are
referred to as a recursive call. These are values that are handled by “reducing” the
problem to a “simpler” problem of the same form.

Example:
def factorial(n):
if n == 0:
return( 1)
else:
return (n*factorial(n-1)) # Recursive call

n=int(input("Enter a nonnegative integer: "))


print("Factorial of", n, "is", factorial(n))
---------------------------------------------------------------------------------------------

LIST DATA TYPE


▪ A List is a collection which is ordered and changeable / mutable.
▪ It allows duplicate members.
▪ A list is similar to array.
▪ Lists are represented by square brackets [] and the elements are separated by
comma.
▪ The main difference between a list and an array is that a list can store different data
type elements, but an array can store only one type of elements.
▪ List can grow dynamically in memory but the size of array is fixed and they cannot
grow dynamically.

The following are the characteristics of a Python list:

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 19


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

➢ Values are ordered


➢ Mutable
➢ A list can hold any number of values
➢ A list can add, remove, and modify the values

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

3. Joining two list:


▪ Concatenate two lists together.
▪ The plus(+) operator used to concatenate two list
Example
a= [1,2,3]
b=[4,5]
c=a+b
print c # it produce [1,2,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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 20


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

Example:
k=[]
for i in range(0,3):
el=input("enter value")
[Link](el)
print(k)

print(len(k))

2. append(): To add an item to the end of a list.

Example
k=[]
for i in range(0,3):
el=input("enter value")
[Link](el)
print(k)

3. insert(): To insert a new element at the specified location.

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=[]

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 21


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

for i in range(0,3):
el=input("enter value")
[Link](el)
print(k)

[Link]()
print(k)

6. reverse(): This function reverse the list elements.

Example
k=[]
for i in range(0,3):
el=input("enter value")
[Link](el)
print(k)

print([Link]())

7. count(value): To find the number of times a value occurs in a list.


8. extend(): To add the items in one list to an existing another list.
9. pop(): To returns and remove the rightmost element from the list.
-----------------------------------------------------------------------------------------
DICTIONARY
▪ A dictionary is an unordered collection, changeable and indexed.
▪ In Python dictionaries are written with curly brackets, and they have keys and
values.
▪ That means dictionary contains pair of elements such that first element represents
the key and the next one becomes its value.
▪ The key and value should be separated by a colon(:) and every pair should be
separated by comma.
▪ All the elements should be enclosed inside curly brackets.

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

Creating Python Dictionary


▪ Creating a dictionary is as simple as placing items inside curly braces {} separated
by commas.
▪ An item has a key and a corresponding value that is expressed as a pair (key:
value).

Example

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 22


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

my_dict = {} # empty dictionary

my_dict = {1: 'apple', 2: 'ball'} # dictionary with integer keys

my_dict = {'name': 'aaa', 1: [2, 4, 3]} # dictionary with mixed keys

OUTPUT:
{}
{1: 'apple', 2: 'ball'}
{'name': 'John', 1: [2, 4, 3]}

Accessing Elements from Dictionary


▪ While indexing is used with other data types to access values, a dictionary
uses keys.
▪ Keys can be used either inside square brackets [] or with the get() method.

Example
my_dict = {'name': 'aaa', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))

OUTPUT:
Jack
26

Dictionary functions and methods:


1. Python Dictionary clear():
▪ It removes all the items from the dictionary.
▪ The clear() method removes all items from the dictionary.

Example
d = {1: "one", 2: "two"}
[Link]()
print('d =', d)

Output
d = {}

2. Python Dictionary copy()


They copy() method returns a shallow copy of the dictionary.

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'}

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 23


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

3. Python Dictionary get()


▪ It returns the value from a dictionary associated with the name.
▪ The get() method returns the value for the specified key if key is in dictionary.

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

4. Python Dictionary pop():


It remove the last item in the dictionary.

Example
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print([Link](4))

5. Python Dictionary keys()


▪ It returns list of all the keys used in the dictionary, in arbitrary order.
▪ The keys() method returns a view object that displays a list of all the keys in the
dictionary

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

6. Python Dictionary values()


▪ It returns list of all values used in the dictionary.
▪ The values() method returns a view object that displays a list of all the values in
the dictionary.

Example
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print([Link]())

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 24


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

Output
dict_values([2, 4, 3])

7. Python Dictionary items()


▪ It returns list of tuple(key : value) used in the dictionary.
▪ The items() method returns a view object that displays a list of dictionary's (key,
value) tuple pairs.

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.

Creating Python Sets


A set is created by placing all the items (elements) inside curly braces {},
separated by comma, or by using the built-in set() function.

# Different types of sets in Python

# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Output
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}

Set Operations

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 25


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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.

Difference between list and tuple


LIST TUPLE

List are enclosed in square brackets [] Tuple are enclosed in parentheses ()

Element and size can be changed Can’t be changed.

Is a mutable object Is a Immutable object


It can grow and shrink as needed It is read only list
-----------------------------------------------------------------------------------------
FILES

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 26


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

▪ Files are used to store data permanently.


▪ Data used in a program is temporary; unless the data is specifically saved, it is lost
when the program terminates.
▪ To permanently store the data created in a program, you need to save it in a file on
a disk or some other permanent storage device. The file can be transported and can
be read later by other programs.
▪ Python’s standard library has a file class that makes it easy for programmers to
make objects that can store data to the disk and retrieves data from the disk.

In Python, a file operation takes place in the following order:


➢ Open a file
➢ Read or write (perform operation)
➢ Close the file

Opening Files in Python


▪ Python has a built-in open() function to open a file.
▪ In order to read and write into a file, we will use the open() as built-in function
to open the file in specified mode of operations. The open() function creates an
file_object object.

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.

The File open modes are:


Mode Description

"r" Opens a file for reading.


Opens a new file for writing. If the file already exists, it hold contents are
"w"
destroyed
"a" Opens a file for appending data from the end of the file.

"rb" Opens a file for reading binary data.

"wb" Opens a file for writing binary data.

"r+" Opens a file for reading and writing.


Opens a file for reading and writing. If the file doesn't exist, then a new
"w+"
file is created.

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.

2. f = open ('[Link]', 'w')

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 27


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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.

3. f = open ('[Link]', 'a')


This statement creates a file object as f, it opens file [Link] for append
mode if the file is exists. That means add new content to the end of existing file.

Writing to Files in Python


▪ In order to write into a file in Python, we need to open it in write w, append a
▪ Writing text to a file.
▪ The 'w' mode creates a new file. If the file already exists, then the file would be
overwritten. We will use the write() function.

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.

Closing Files in Python


▪ When we are done with performing operations on the file, we need to properly close
the file.
▪ Closing a file will free up the resources that were tied with the file. It is done using
the close() method available in Python.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 28


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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

▪ The error handling code basically consists of two segments,


o To detect the errors and throw Exception.
o To catch Exception and perform appropriate action.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 29


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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.

A try with multiple except clause and finally block:


▪ In some cases, more than one exception should be raised by a single piece of code.
▪ To handle this type of situation, you specify two or more except clauses, each
catching different types of exception.
▪ When an exception is thrown, each except statement is inspected in order, and the
first one whose type matches that of the exception is executed.
▪ After one except statement executes, the others are bypassed, and execution
continues after the try / except block.

Syntax # Multiple except


try:
<body>
except <ExceptionType-1>:
<handler>
except <ExceptionType-2>:
<handler>
:
except <ExceptionType-n>:
<handler>

finally block:

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 30


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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

Life Cycle of thread:


To understand the functionality of threads in depth, we need to learn about the
lifecycle of the threads or the different thread states.
Typically, a thread can exist in five distinct states.
The different states are shown below:
New Thread
A new thread begins its life cycle in the new state. But, at this stage, it has not yet
started and it has not been allocated any resources. We can say that it is just an instance
of an object.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 31


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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.

Example Program to illustrate multithreading.


import _thread
import time
def cal_sqre(num): # define the cal_sqre function
print(" Calculate the square root of the given number")
for n in num:
[Link](0.6) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)
def cal_cube(num): # define the cal_cube() function
print(" Calculate the cube of the given number")
for n in num:
[Link](0.3) # at each iteration it waits for 0.3 time
print(" Cube is : ", n * n * n)
arr = [4, 5, 6, 7, 2] # given array
t1 = [Link]() # get total time to execute the functions
cal_sqre(arr) # call cal_sqre() function
cal_cube(arr) # call cal_cube() function
print(" Total time taken by threads is :", [Link]() - t1)
# print the total time
--------------------------------------------------------------------------------------

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 32

You might also like