0% found this document useful (0 votes)
22 views23 pages

Introduction to Python Programming

Python is a high-level programming language known for its readability and efficiency, developed by Guido van Rossum in 1991. It supports two major versions, Python 2 and Python 3, and offers features like object-oriented programming, dynamic typing, and a variety of data types. The document also covers Python's execution modes, data types, variables, operators, comments, modules, and functions, providing a comprehensive introduction to the language.
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)
22 views23 pages

Introduction to Python Programming

Python is a high-level programming language known for its readability and efficiency, developed by Guido van Rossum in 1991. It supports two major versions, Python 2 and Python 3, and offers features like object-oriented programming, dynamic typing, and a variety of data types. The document also covers Python's execution modes, data types, variables, operators, comments, modules, and functions, providing a comprehensive introduction to the language.
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

Python is a widely used general-purpose, high level programming language. It was initially designed
by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly
developed for emphasis on code readability, and its syntax allows programmers to express concepts
in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.

There are two major Python versions- Python 2 and Python 3.

Beginning with Python programming:


1) Finding an Interpreter: Before we start Python programming, we need to have an interpreter
to interpret and run our programs. There are many interpreters available freely to run Python
scripts like IDE (Integrated Development Environment) which is installed when you install
the python software from [Link]
2) Writing first program:
# Script Begins
Statement1
Statement2
Statement3
# Script Ends

Differences between scripting language and programming language


Scripting Language Programming Language
1 A PL that supports scripts: programs written A formal language, which comprises a set of
for a special run-time environment that instructions used to produce various kinds of
automate the execution of tasks. output
2 Execution is slow Compiler-based languages are executed much
faster while interpreter-based languages are
executed slower
3 Can be divided into client-side scripting Can be divided into high-level, low-level
language and server-side scripting languages languages or compile-based or interpreter-based
languages
4 Easier to learn Not as easy to learn
5 Examples are: JavaScript, Perl, PHP, Python Examples are: C, C++, Assembly etc.
and Ruby
6 Mostly used for web development Used to develop various applications such
desktop, web, mobile, etc.

Why to use Python:


The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented: Structure supports such concepts as polymorphism, operation
overloading and multiple inheritance.
2. Indentation: Indentation is one of the greatest feature in python
3. It’s free (open source): Downloading python and installing python is free and easy
4. It’s Powerful: Dynamic typing, Built-in types and tools, Library utilities, Third party utilities
(e.g. Numeric, NumPy, sciPy), Automatic memory management
5. It’s Portable: Python runs virtually on every major platform used today. As long as you have
a compaitable python interpreter installed, python programs will run in exactly the same
manner, irrespective of platform.
6. It’s easy to use and learn: No intermediate compile; Python Programs are compiled
automatically to an intermediate form called byte code, which the interpreter then reads;
Structure and syntax are pretty intuitive and easy to grasp.
2
7. Interpreted Language: Python is processed at runtime by python Interpreter
8. Interactive Programming Language: Users can interact with the python interpreter directly
for writing the programs
9. Straight forward syntax: The formation of python syntax is simple and straight forward
which also makes it popular.

Python Code Execution


Python’s traditional runtime execution model: Source code you type is translated to byte code, which
is then run by the Python Virtual Machine (PVM). Your code is automatically compiled, but then it
is interpreted.

There are two modes for using the Python interpreter:


 Interactive Mode
 Script Mode

Running Python in interactive mode:


Without passing python script file to the interpreter, directly execute code to Python prompt.
Once you’re inside the python interpreter, then you can start.
>>> print("hello world")
hello world
# Relevant output is displayed on subsequent lines without the >>> symbol
>>> x=[0,1,2]
# Quantities stored in memory are not displayed by default.
>>> x
#If a quantity is stored in memory, typing its name will display it.
[0, 1, 2]
>>> 2+3
5

The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python interpreter
uses to indicate that it is ready. If the programmer types 2+6, the interpreter replies 8.

Running Python in script mode:


Alternatively, programmers can store Python script source code in a file with the .py extension, and
use the interpreter to execute the contents of the file. To execute the script by the interpreter, you
have to tell the interpreter the name of the file. For example, if you have a script name [Link] and
you're working on Unix, to run the script you have to type: python [Link]
Working with the interactive mode is better when Python programmers deal with small pieces of
code as you can type and execute them immediately, but when the code is more than 2-4 lines, using
the script for coding can help to modify and use the code in future.

3
DATA TYPES
The data stored in memory can be of many types. Python has various standard data types that are
used to define the operations possible on them and the storage method for each of them.

1) Int: Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
>>> print(357654+2) >>> print(20) >>> print(0b10) # To verify the type of any object in
357656 20 2 Python, use the type() function:
>>> a=10 >>> print(0X20) >>> type(10) >>> a=11
>>> print(a) 32 <class 'int'> >>> print(type(a))
10 <class 'int'>

2) Float: Float, or "floating point number" is a number, positive or negative, containing one or more
decimals. Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8 >>> y=2.8 >>> type(.4)
>>> y >>> print(type(y)) <class 'float'>
2.8 <class 'float'>

3) Boolean: Objects of Boolean type may have one of two values, True or False:
>>> type(True) >>> type(False)
<class 'bool'> <class 'bool'>

4) String: Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Ex: 'hello' is the same as
"hello". Strings can be output to screen using the print function. For example: print("hello").
>>> print("Hello") >>> type("Hello") >>> " " >>>x = 35
Hello <class 'str'> '' >>>print(f “x = {x}”)
If you want to include either type of quote character within the string, the simplest way is to delimit
the string with the other type. If a string is to contain a single quote, delimit it with double quotes and
vice versa:
>>> print("It's good") >>> print('It"s good')
It's good It"s good

Suppressing Special Character i.e. using Escape Sequence:


Specifying a backslash (\) in front of the quote character in a string “escapes” it and causes Python to
suppress its usual special meaning. It is then interpreted simply as a literal single quote character:
Others are: \n = newline, \t = tab, \' = single quote, \" = double quote, etc.
>>> print("Hello \n World") >>> print("a\tb")
Hello a b
World

5) List: It is a general purpose most widely used in data structures. List is a collection which is
ordered and changeable and allows duplicate members. (Grow and shrink as needed, sequence
type, sortable). To use a list, you must declare it first. Do this using square brackets and separate
values with commas. We can construct / create list in many ways.
>>> list1=[1,2,3,'A','B',7,8,[10,11]] >>> x=list() >>> tuple1=(1,2,3,4)
>>> print(list1) >>> x >>> x=list(tuple1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]] [] >>> x
[1, 2, 3, 4]

Variables
Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory. Based on the data type of a variable, the

4
interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by
assigning different data types to variables, you can store integers, decimals or characters in these
variables.

Rules for Python variables:


i) A variable name must start with a letter or the underscore character
ii) A variable name cannot start with a number
iii) A variable name can only contain alphanumeric characters and underscores (A-z, 0-9, and _ )
iv) Variable names are case-sensitive (age, Age and AGE are three different variables)

Assigning Values to Variables:


The equal sign (=) is used to assign values to variables. The operand to the left of the = operator is
the name of the variable and the operand to the right of the = operator is the value stored in the
variable. For example:
a= 100 # An integer assignment This produces the following result:
print (a) 100
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.
For example:
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same
memory location. You can also assign multiple objects to multiple variables.
For example:
a,b,c = 1,2,"mrcet“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one
string object with the value "john" is assigned to the variable c.

Output Variables:
The Python print statement is often used to output variables.
Variables do not need to be declared with any particular type and can even change type after they
have been set.
x = 5 # x is of type int print(x)
x = "mrcet " # x is now of type str Output: mrcet

To combine both text and a variable, Python uses the “+” character:
x = "awesome" Output x = "Python is " Output:
print("Python is " + x) Python is awesome y = "awesome" Python is awesome
z=x+y
print(z)
Expressions
An expression is a combination of values, variables, and operators. An expression is evaluated using
assignment operator. Examples: Y = x + 17
>>> x=10 >>> z
>>> z=x+20 30
A value all by itself is a simple expression, and so is a variable.
>>> y=20 20
>>> y
Python also defines expressions that only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or object is an
identifier.
Literals: These are language-independent terms in Python and should exist independently in any
programming language. In Python, there are the string literals, byte literals, integer literals, floating
point literals, and imaginary literals.
5
OPERATORS
In Python you can implement the following operations using the corresponding tokens.
Operator Token Operator Token Logical Operators Assigment
add + Bitwise NOT ~ and Operators
subtract - Binary left shift << or = , +=, - =
multiply * Binary right shift >> not *=, /=, %=
Integer Division / Less than < //=, **=, &=
remainder % Greater than > This is allowed |=, ^=, >>=
Exponentiation ** Less than or equal to <= E.g: 60 <= x >= 100. <<=
Bitwise AND & Greater than or equal to >= It means:
Bitwise OR | Check equality == x>=60 and x<=100 ++ and - - are
Bitwise XOR ^ Check not equal != not allowed.

Precedence of Operators:
Operator precedence affects how an expression is evaluated. For example, x = 7 + 3 * 2; here, x is
assigned 13, not 20 because operator * has higher precedence than +, so it first multiplies 3*2 and
then adds into 7. However, parentheses () overrides the precedence of the arithmetic operators. For
example, x = (7 + 3) * 2; here, x is 20 because of the parentheses.

Comments
i) Single-line comment begins with a hash (#) symbol and is useful in mentioning that the
whole line should be considered as a comment until the end of line.
ii) A Multi line comment is useful when we need to comment on many lines. In python, triple
double quote (“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.
Example: Output:
30

Modules
Python module can be defined as a python program file which contains a python code including
python functions, class, or variables. In other words, we can say that our python code file saved with
the extension (.py) is treated as the module. We may have a runnable code inside the python module.
A module in Python provides us the flexibility to organize the code in a logical way. To use the
functionality of one module into another, we must have to import the specific module.
Syntax:
import <module-name>
Every module has its own functions, those that can be accessed with . (dot)
Note: In python we have help (). Enter the name of any module, keyword, or topic to get help on
writing Python programs and using Python modules. To quit this help utility and return to the
interpreter, just type "quit".

Some of the modules like math, os, date, and calendar so on……
>>> import sys >>>import calendar
>>> print([Link]) or print(sys.version_info) >>> print([Link](2020))
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, True
[Link]) [MSC v.1916 32 bit (Intel)] >>> print([Link](2021,5))

6
>>>import math
>>>[Link](9)
3.0
>>>[Link](2,5) #discuss the output

FUNCTIONS AND ITS USE


Function is a group of related statements that perform a specific task. Functions help break our
program into smaller and modular chunks. As our program grows larger and larger, functions make it
more organized and manageable. It avoids repetition and makes code reusable. Basically, we can
divide functions into the following two types:
1. Built-in functions - Functions that are built 2. User-defined functions - Functions defined by
into Python. the users themselves.
Ex: abs(), all(), ascii(), bool()………so on…. def add_numbers(x,y):
integer = -20 sum = x + y
print('Absolute value of -20 is:', abs(integer)) return sum
Output: print("The sum is", add_numbers(5, 20))
Absolute value of -20 is: 20 Output:
The sum is 25

Flow of Execution when working with functions:


1) The order in which statements are executed is called the flow of execution
2) Execution always begins at the first statement of the program.
3) Statements are executed one at a time, in order, from top to bottom.
4) Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called.
5) Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the statements
there, and then comes back to pick up where it left off.

Output:
#example for flow of execution welcome
print("welcome") 0
for x in range(3): 1
print(x) 2
print("Good morning college") Good morning college
#The flow/order of execution is: 2,3,4,3,4,3,4,5

Parameters and arguments:


Parameters are passed during the definition of function while Arguments are passed during the
function call.
Syntax: Example: #12 and 13 are arguments Output:
def #here a and b are parameters #function call 25
functionname(): >>>def add(a,b): #//function definition
statements ... return a+b >>>result=add(12,13)
... >>>print(result)
functionname()

Function definition consists of following components:


(a) Keyword def indicates the start of function header.
(b) A function name to uniquely identify it. Function naming follows the same rules of writing
identifiers in Python.

7
(c) Parameters (arguments) through which we pass values to a function. They are optional.
(d) A colon (:) to mark the end of function header.
(e) Optional documentation string (docstring) to describe what the function does.
(f) One or more valid python statements that make up the function body. Statements must have
same indentation level (usually 4 spaces).
(g) An optional return statement to return a value from the function. Any function that returns a
value is called Fruitful function. A function that does not return a value is called a Void
function.

There are three types of Python function arguments using which we can call a function.
1) Default Arguments
2) Keyword Arguments
3) Variable-length Arguments

#calling function in python:


>>>def hf(): >>>def add(x,y): >>>def add(x,y): >>>def add_sub(x,y):
… print("hello world") … c=x+y … c=x+y … c=x+y
>>>hf() … print(c) … return c … d=x-y
>>>add(5,4) >>>print(add(5,4)) … return c,d
Output: Output: Output: >>>print(add_sub(10,5))
hello world 9 9 Output:
(15, 5)

The return statement is used to exit a function and go back to the place from where it was called.
This statement can contain expression which gets evaluated and the value is returned. If there is no
expression in the statement or the return statement itself is not present inside a function, then the
function will return the None object.

#Keyword Arguments
When we call a function with some values, these values get assigned to the arguments according to
their position. Python allows functions to be called using keyword arguments. When we call
functions in this way, the order (position) of the arguments can be changed. (Or)
If you have some functions with many parameters and you want to specify only some of them, then
you can give values for such parameters by naming them - this is called keyword arguments - we use
the name (keyword) instead of the position to specify the arguments to the function.
There are two advantages – (1) Using the function is easier since we do not need to worry about the
order of the arguments. (2) we can give values to only those parameters which we want, provided
that the other parameters have default argument values.
>>>def func(a, b=5, c=10): Output:
… print 'a is', a, 'and b is', b, 'and c is', c a is 3 and b is 7 and c is 10
>>>func(3, 7) a is 25 and b is 5 and c is 24
>>>func(25, c=24) a is 100 and b is 5 and c is 50
>>>func(c=50, a=100)
>>>def print_name(name1, name2): Output:
… """ This function prints the name """ B and A are friends
…. print (name1 + " and " + name2 + " are friends")
>>>#calling the function
>>>print_name(name2 = 'A',name1 = 'B')

#Default Arguments
Function arguments can have default values in Python. We can provide a default value to an
argument by using the assignment operator (=).

8
>>>def hello(wish,name='you'): Output:
… return '{},{}'.format(wish,name) good morning,you
>>>print(hello("good morning"))

Note: Any number of arguments in a function can have a default value. But once we have a default
argument, all the arguments to its right must also have default values. This means to say, non-default
arguments cannot follow default arguments. For example, if we had defined the function header
above as:
def hello(name='you', wish):
Syntax Error: non-default argument follows default argument
>>>def sum(a=4, b=2): #2 is supplied as default argument >>>sum(1,2) #calling with args
… """ This function will print sum of two numbers if >>>sum( ) #calling without args
… the arguments are not supplied. it will add the default Output:
… value """ 3
… print (a+b) 6

#Variable-length arguments
Sometimes you may need more arguments to process function then you mentioned in the definition.
If we don’t know in advance about the arguments needed in function, we can use variable-length
arguments also called arbitrary arguments.
For this an asterisk (*) is placed before a parameter in function definition which can hold non-
keyworded variable-length arguments and a double asterisk (**) is placed before a parameter in
function which can hold keyworded variable-length arguments. If we use one asterisk (*) like *var,
then all the positional arguments from that point till the end are collected as a tuple called ‘var’ and if
we use two asterisks (**) before a variable like **var, then all the positional arguments from that
point till the end are collected as a dictionary called ‘var’.
>>>def wish(*names): Output:
… """This function greets all Hello MRCET
… the person in the names tuple.""" Hello CSE
… # names is a tuple with arguments Hello SIR
… for name in names: Hello MADAM
… print("Hello",name)
>>>wish("MRCET","CSE","SIR","MADAM")

Program Examples on Functions


#Program to find area of a circle using function
r=int(input("Enter radius of circle"))
use single return value function with argument.
print(areaOfCircle(r))
pi=3.14 Output:
def areaOfCircle(r): Enter radius of circle 3
return pi*r*r 28.259999999999998
#Program to write sum, difference, product anda=int(input("Enter a value"))
others using arguments with return value b=int(input("Enter b value"))
function. #function call
def calculete(a,b): s,d,p,q,m = calculete(a,b)
total=a+b print("Sum= ",s,", diff= ",d,", mul= ",p,", div=
diff=a-b ",q,", mod= ",m)
prod=a*b Output:
div=a/b Enter a value 5
mod=a%b Enter b value 6
return total,diff,prod,div,mod Sum= 11, diff= -1, mul= 30, div=
0.8333333333333334, mod= 5
#Program to find biggest of two numbers using a=int(input("Enter a value "))
functions. b=int(input("Enter b value "))
9
def biggest(a,b): #function call
if a>b : big= biggest(a,b)
return a print("big number= ",big)
else : Output:
return b Enter a value 5
Enter b value -2
big number= 5
#Program to find biggest of three numbers using a=int(input("Enter a value"))
functions. (nested if) b=int(input("Enter b value"))
def biggest(a,b,c): c=int(input("Enter c value"))
if a>b : Alternative code (using elif) #function call
if a>c : if a>b: big= biggest(a,b,c)
return a print("a is greater") print("big number= ",big)
else : elif b>c:
return c print("b is greater") Output:
else : else: Enter a value 5
if b>c : print("c is greater") Enter b value -6
return b Enter c value 7
else : big number= 7
return c
#Program to read one subject mark and print a=int(input("Enter one subject marks"))
pass or fail; use single return values function print(result(a))
with argument.
def result(a): Output:
if a>40: Enter one subject marks 35
return "pass" Fail
else:
return "fail"
#Program to display FSS dept 4 times on the usingFunctions()
screen. (while loop)
def usingFunctions(): Output:
count =1 FSS dept 1
while count<5: FSS dept 2
print("FSS dept",count) FSS dept 3
count=count+1 FSS dept 4

CONTROL FLOW, LOOPS


Conditionals: conditional (if), alternative (if-else), chained conditional (if-elif-else);
Iteration: while, for, break, continue.

Conditional (if):
The if statement contains a logical expression using
which data is compared and a decision is made based on
the result of the comparison.
Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the
block of statement(s) inside the if statement is executed.
If boolean expression evaluates to FALSE, then the first
set of code after the end of the if statement(s) is
executed.

10
Alternative if (If-Else):
An else statement can be combined with an if statement. If - else Flowchart :
An else statement contains the block of code (false
block) that executes if the conditional expression in the
if statement resolves to 0 or a FALSE value. The else
statement is an optional statement and there could be at
most only one else Statement following if.
Syntax of if - else :
if test expression:
Body of if stmts
else:
Body of else stmts

Chained Conditional: (If-elif-else):


The elif statement allows us to check multiple
expressions for TRUE and execute a block of code as
soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional.
However, unlike else, for which there can be at most one
statement, there can be an arbitrary number of elif
statements following an if.
Syntax of if – elif - else :
If test expression:
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts

ITERATION
A loop statement allows us to execute a statement or group of statements multiple times as long as
the condition is true. Repeated execution of a set of statements with the help of loops is called
iteration. Loops statements are used when we need to run same code again and again, each time with
a different value.
In Python Iteration (Loops) statements are of three types: While Loop, For Loop and Nested For
Loops

While loop:
 Loops are either infinite or conditional. Python while
loop keeps reiterating a block of code defined inside it
until the desired condition is met.
 The while loop contains a boolean expression and the
code inside the loop is repeatedly executed as long as
the boolean expression is true.
 The statements that are executed inside while can be a
single line of code or a block of multiple statements.
Syntax:
while(expression):
Statement(s)
i=1 Output a=1 Output
while (i < 7): 1 while (a<10): 1
print (i) 2 print (a) 2
11
i = i+1 3 a=a+1 3
4 if (a == 4): While loop
5 print ('While loop terminated') terminated
6 break
For loop:
Python for loop is used for repeated execution of a group of statements for the desired number of
times. It iterates over the items of lists, tuples, strings, the dictionaries and other iterable objects

Sample Program:
Iterating over a Output #list of items
List: 1 list = ['FSS','Sasa','Ibadan']
num = [1, 2, 4, 6] 4 i=1
seq=0 16 #Iterating over the list
for val in num: 36 for item in list:
seq=val*val print ('Item ',i,' is ',item)
print(seq) i = i+1
Output
Item 1 is FSS
Item 2 is Sasa
Item 3 is Ibadan
Iterating over a Tuple: Iterating over a Dictionary: Iterating over a String:
tuple = (2,3,5,7) #creating a dictionary #declare a string to iterate over
print ('These are the first college = x = 'MOWEMI'
four prime numbers ') {"csc":"4flat","bam":"Ykale",
#Iterating over the tuple "lib":"ccblock"} #Iterating over the string
for a in tuple: for leta in x:
#Iterating over the dictionary to print
print (a) keys… print (leta)
Output: print ('Keys are:')
These are the first four for keys in college: Output:
prime numbers print(keys) M
2 O
3 #Iterating over the dictionary to print W
5 values… E
7 print ('Values are:') M
for blocks in [Link](): I
print(blocks)

Output:
Keys are: Values are:
csc 4flat
bam Ykale
lib ccblock

Nested For loop:


When one Loop defined within another Loop is called Nested Loops.
Syntax:
for val in sequence:
for val in sequence:
statements
statements
12
Discuss the outputs of the following: 2) for i in range(1,6): 3) for x in range(1,6):
1) for i in range(2,6,2): for j in range(5,i-1,-1): print(x, end=" ")
for j in range(i,0,-1) print(i, end=" ")
print(i) print("")
print("")
Break and continue:
In Python, break and continue statements can alter the flow of a normal loop. Sometimes we wish to
terminate the current iteration or even the whole loop without checking test expression. The break
and continue statements are used in these cases.
Break Continue
The break statement terminates the loop The continue statement is used to skip the rest of
containing it and control of the program flows to the code inside a loop for the current iteration
the statement immediately after the body of the only. Loop does not terminate but continues on
loop. If break statement is inside a nested loop with the next iteration.
(loop inside another loop), break will terminate
the innermost loop.
Flowchart Flowchart

for x in range(1, 10): for x in range(1, 10):


if (x == 4): if (x == 5):
break continue
print (x, end=" ") print (x, end=" ")
Output: Output:
123 12346789

Pass:
In Python programming, pass is a null statement. The difference between a comment and pass
statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored.
pass is just a placeholder for functionality to be added later.
Example:
>>>sequence = {'p', 'a', 's', 's'} Output:
>>>for val in sequence: #Nothing is printed.
… pass
Similarily we can also write,
def f(arg): pass # a function that does nothing (yet)
class C: pass # a class with no methods (yet

PRACTICE QUESTIONS:
Write python program (use function, as well) to compute the following:
1) Area of a circle
2) Absolute value of any number; don't use built-in function.
13
3) Write a Python function that takes two lists and returns True if they have at least one
common member.
MORE ON FUNCTIONS

Local and Global scope:


Local Scope:
A variable which is defined inside a function is local to that function. It is accessible from the point
at which it is defined until the end of the function, and exists for as long as the function is executing.

Global Scope:
A variable which is defined in the main body of a file is called a global variable. It will be visible
throughout the file, and also inside any file which imports that file.
 The variable defined inside a function can also be made global by using the global statement.

# use Global variable and Local variable with same name >>>f4()
>>>x = 5 >>>print("global x:", x)
>>>def f4(): Output:
… x = 10 local x: 10
… print("local x:", x) global x: 5

Recursion:
Recursion is the process of defining something in terms of itself. That is, function calling itself.
# Write a program to factorial using recursion print("zero factorial", fact(0))
def fact(x): print("five factorial", fact(5))
if x==0:
result = 1 Output:
else : zero factorial 1
result = x * fact(x-1) five factorial 120
return result

Strings:
A string is a group or a sequence of characters. Since Python has no provision for arrays, we simply
use strings. This is how we declare a string. We can use a pair of single or double quotes. Every
string object is of the type ‘str’.
>>> type("name") >>> a=str('mrcet') >>> a=str(mrcet) >>> fruit = 'banana'
<class 'str'> >>> a >>> a[2] >>> letter = fruit[1]
>>> name=str() 'mrcet' 'c' >>> letter
>>> name 'a'
‘’

The second statement selects character number 1 from fruit and assigns it to letter. The expression in
brackets is called an index. The index indicates which character in the sequence we want.

String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character: Subsets of
strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of
the string and working their way from -1 at the end.

Slice out substrings, sub lists, sub Tuples using index.


Syntax:[Start: stop: steps]
o Slicing will start from index and will go up to stop in step of steps.
o Default value of start is 0,
o Stop is last index of list
14
o And for step default is 1

Example 1: Output:
str = 'Hello World!'
print str # Prints complete string Hello World!
print str[0] # Prints first character of the string H
print str[2:5] # Prints characters starting from 3rd to 5th llo
print str[2:] # Prints string starting from 3rd character print llo World!
str * 2 # Prints string two times Hello World!Hello World!
print str + "TEST" # Prints concatenated string Hello World!TEST
Example 2: Output
>>> x='computer'
>>> x[1:4] 'omp'
>>> x[Link] 'opt'
>>> x[3:] 'puter'
>>> x[:5] 'compu'
>>> x[-1] 'r'
>>> x[-3:] 'ter'
>>> x[:-2] 'comput'
>>> x[::-2] 'rtpo'
>>> x[::-1] 'retupmoc'

Immutability:
It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a
character in a string.
For example:
>>> greeting='mrcet college!'
>>> greeting[0]='n'
TypeError: 'str' object does not support item assignment.
The reason for the error is that strings are immutable, which means we can’t change an existing
string. The best we can do is creating a new string that is a variation on the original:
>>> greeting = 'Hello, world!' >>> new_greeting
>>> new_greeting = 'J' + greeting[1:] 'Jello, world!'
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator.

String functions and methods:


There are many methods to operate on String.
[Link] Method name Description
1. isalnum() Returns true if string has at least 1 character and all
characters are alphanumeric and false otherwise.
2. isalpha() Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise.
3. isdigit() Returns true if string contains only digits and false
otherwise.
4. islower() Returns true if string has at least 1 cased character and
all cased characters are in lowercase and false
otherwise.
5. isnumeric() Returns true if a string contains only numeric
characters and false otherwise.
6. isspace() Returns true if string contains only whitespace
characters and false otherwise.
7. istitle() Returns true if string is properly “titlecased” and false
15
otherwise.
8. isupper() Returns true if string has at least one cased character
and all cased characters are in uppercase and false
otherwise.
9. replace(old, new[, max]) Replaces all occurrences of old in string with new or at
most max occurrences if max given.
10. split() Splits string according to delimiter str (space if not
provided) and returns list of substrings;
11. count() Occurrence of a string in another string
12. find() Finding the index of the first occurrence of a string in
another string.
13. swapcase() Converts lowercase letters in a string to uppercase and
viceversa
14. startswith(str,beg=0,end=len(string)) Determines if string or a substring of string (if starting
index beg and ending index end are given) starts with
15. endswith(str, beg=0,end=len(string)) substring str; returns true if so and false otherwise.
Note: All the string methods will be returning either true or false as the result.

String module:
This module contains a number of functions to process standard Python strings. In recent versions,
most functions are available as string methods as well. It’s a built-in module and we have to import it
before using any of its constants and classes.
Syntax: import string
Note: help(string) --- gives the information about all the variables ,functions, attributes and classes to
be used in string module.
Example: Output:
import string
print(string.ascii_letters) abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM…RSTUVWXYZ
print(string.ascii_lowercase) abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercase) ABCDEFGHIJKLMNOPQRSTUVWXYZ
print([Link]) 0123456789
print([Link]) 0123456789abcdefABCDEF
print([Link])
print([Link]) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

PYTHON ARRAYS
Array is a container which can hold a fix number of items and these items should be of the same
type. Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array.
 Element − Each item stored in an array is called an element.
 Index − Each location of an element in an array has a numerical index, which is used to
identify the element.
Array Representation
Arrays can be declared in various ways in different languages. Below is an illustration.

As per the above illustration, following are the important points to be considered.
 Index starts with 0.
 Array length is 10 which means it can store 10 elements.

16
 Each element can be accessed via its index. For example, we can fetch an element at index 6
as 70
Basic Operations
Following are the basic operations supported by an array.
i) Traverse − print all the array elements one by one.
ii) Insertion − Adds an element at the given index.
iii) Deletion − Deletes an element at the given index.
iv) Search − Searches an element using the given index or by the value.
v) Update − Updates an element at the given index.
Array is created in Python by importing array module to the python program. Then the array is
declared as shown below.
from array import *
arrayName=array(typecode, [initializers])
Typecode are the codes that are used to define the type of value the array will hold. Some common
typecodes used are:
Typecode Value
b Represents signed integer of size 1 byte
B Represents unsigned integer of size 1 byte
c Represents character of size 1 byte
i Represents signed integer of size 2 bytes
I Represents unsigned integer of size 2 bytes
f Represents floating point of size 4 bytes
d Represents floating point of size 8 bytes
Creating an array: Output:
from array import * 10
array1 = array('i', [10,20,30,40,50]) 20
for x in array1: 30
print(x) 40
50
Accessing Array Element Output:
We can access each element of an 10
array using the index of the element. 30
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])

Array methods:
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

17
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
Example:
>>> college=["mrcet","it","cse"] >>> [Link]("eee") >>> [Link]()
>>> [Link]("auto") >>> [Link]("ece") 'ece'
>>> college >>> college
['mrcet', 'it', 'cse', 'auto'] ['mrcet', 'it', 'cse', 'auto', 'eee', 'ece']
>>> college >>> [Link](4) >>> college
['mrcet', 'it', 'cse', 'auto', 'eee'] 'eee' ['mrcet', 'it', 'cse', 'auto']
>>> [Link]("it")
>>> college
['mrcet', 'cse', 'auto'] (Practice more)

MORE ON LISTS, TUPLES, DICTIONARIES:


List:
 It is a general purpose most widely used in data structures
 List is a collection which is ordered and changeable and allows duplicate members. (Grow
and shrink as needed, sequence type, sortable).
 To use a list, you must declare it first. Do this using square brackets and separate values with
commas.
 We can construct / create list in many ways.
Example:
>>>list1=[1,2,3,'A','B',7,8,[10,11]] >>> x=list() >>> tuple1=(1,2,3,4)
>>> print(list1) >>> x >>> x=list(tuple1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]] [] >>> x
[1, 2, 3, 4]

List operations:
These operations include indexing, slicing, adding, multiplying, and checking for membership.

Basic List Operations:


Lists respond to the + and * operators much like strings; they mean concatenation and repetition here
too, except that the result is a new list, not a string.
Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x 123 Iteration

Indexing, Slicing, and Matrixes


Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.
Assuming following input:
L = ['mr', 'col', 'fss']
Python Expression Results Description
L[2] fss Offsets start at zero
L[-2] col Negative: count from the right
L[1:] ['col', 'fss'] Slicing fetches section

18
>>> list1=[1,2,3,4,5,6,7,8,9,10] >>> list1[:6] >>> list1[Link]
>>> list1[1:] [1, 2, 3, 4, 5, 6] [2, 4, 6, 8]
[2, 3, 4, 5, 6, 7, 8, 9, 10]

List methods:
The list data type has some more methods. Here are all of the methods of list objects:
Del() Append() Extend() Insert()
>>> x=[5,3,8,6] >>> x=[1,5,8,4] >>> x=[1,2,3,4] >>> x=[1,3,4,6,7]
>>> del(x[1]) >>> [Link](10) >>> y=[3,6,9,1] >>> [Link](2,10)
>>> x >>> x >>> [Link](y) >>> x
[5, 8, 6] [1, 5, 8, 4, 10] >>> x [1, 3, 10, 4, 6, 7]
[1, 2, 3, 4, 3, 6, 9, 1]
Pop() Remove() Reverse() Sort()
>>> x=[1,2,10,4,6,7] >>> x=[1,33,2,10,4,6] >>> x=[1,2,3,4,5,6,7] >>> x=[10,1,5,3,8,7]
>>> [Link]() >>> [Link](33) >>> [Link]() >>> [Link]()
7 >>> x >>> x >>> x
>>> [Link](2) [1, 2, 10, 4, 6] [7, 6, 5, 4, 3, 2, 1] [1, 3, 5, 7, 8, 10]
10
More Program Examples
>>> x=[m for m in range(8)] >>>x=[z**2 for z in range(10) if z>4]
>>> print(x) >>> print(x)
[0, 1, 2, 3, 4, 5, 6, 7] [25, 36, 49, 64, 81]
>>>x=[x**2 for x in range (1,11) if x%2 == 1] >>> a=5
>>> print(x) >>> table = [[a, b, a * b] for b in range(1, 11)]
[1, 9, 25, 49, 81] >>> for i in table:
print(i) (Discuss the output)

Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round
brackets.
 Supports all operations for sequences.
 Immutable, but member objects may be mutable.
 If the contents of a list shouldn’t change, use a tuple to prevent items from accidently being
added, changed, or deleted.
 Tuples are more efficient than list due to python’s implementation.
We can construct tuple in many ways:
X=() #no item tuple
X=(1,2,3)
X=tuple(list1)
X=1,2,3,4
Some of the operations of tuple are:
Access tuple items Change tuple items Loop through a tuple
>>> x=('a','b','c','g') Once a tuple is created, you cannot >>> x=4,5,6,7,2,'aa'
>>> print(x[2]) change its values. Tuples are >>> for i in x:
c unchangeable. print(i)
x=(2,5,7,'4',8)
x[1]=1 (Check the output)
Count() Index() Len()
>>>x=(1,2,3,4,5,6,2,10,2,11,12,2) >>>x=(1,2,3,4,5,6,2,10,2,11,12,2) >>> x=(1,2,3,4,5,6,2,10,2)
>>>[Link](2) >>> [Link](2) >>> y=len(x)
4 1 >>> print(y)
9
19
Functions can return tuples as
return values. c = 2 * 3.14159 * r
def circleInfo(r): a = 3.14159 * r * r Output:
""" Return (circumference, return (c, a)
area) of a circle of radius r """ print(circleInfo(10)) (62.8318, 314.159)
Pop Quiz
Question: Answer:
Create a list of 2-tuples like >>> z=[(x, x**2) for x in range(6)]
(number, square). >>> z
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are
written with curly brackets, and they have keys and values.
 Key-value pairs
 Unordered
We can construct or create dictionary like:
X= {1:’A’,2:’B’,3:’c’} OR X= dict([(‘a’,3) (‘b’,4)]) OR X= dict(‘A’=1,’B’=2)

Operations and methods:


Methods that are available with dictionary are tabulated below. Some of them have already been
used in the above examples.
Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to v (defaults to
None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
pop(key[,d]) Remove the item with key and return its value or d if key is not found. If d is
not provided and key is not found, raises KeyError.
popitem() Remove and return an arbitary item (key,value). Raises KeyError if the
dictionary is empty.
setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key with a value of d
and return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from other, overwriting
existing keys.
values() Return a new view of the dictionary's values

Some Examples on Dictionaries


>>>dict1 = >>>dict1 = {"brand":"cet","model":"col","yr":2004}
{"brand":"cet","model":"col","yr":2004} >>> [Link]()
>>> x=dict1["brand"] dict_keys(['brand', 'model', 'yr'])
>>> x >>> [Link]()
'cet' dict_values(['cet', 'col', 2004])
>>> [Link]() >>> for items in [Link]():
dict_items([('brand', 'mrcet'), ('model', 'college'), >>>print(items)
('year', 2004)]) cet
col
2004
>>> for items in [Link](): >>> for i in [Link]():

20
>>>print(items) >>>print(i)
brand ('brand', 'mrcet')
model ('model', 'college')
year ('year', 2004)

Some more operations like:


1) Add/change: You can change the value of a 2) Remove():It removes or pop the specific item
specific item by referring to its key name. of dictionary.
>>>dict1=
>>>dict1 = {"brand":"cet","model":"col","yr":2004} {"brand":"cet","model":"col","yr":2004}
>>> dict1["yr"]=2005 >>> print([Link]("model"))
>>> dict1 college
{'brand': 'cet', 'model': 'col', 'yr': 2005} >>> dict1
{'brand': 'mrcet', 'year': 2005}
3) Length: we use len() method to get the length 4) Delete: Deletes a particular item.
of dictionary. >>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>>{1: 1, 2: 4, 3: 9, 4: 16} >>> del x[5]
{1: 1, 2: 4, 3: 9, 4: 16} >>> x
>>> y=len(x) {1: 1, 2: 4, 3: 9, 4: 16}
>>> y
4

FILES AND EXCEPTION:


A file is some information or data which stays in the computer storage devices. Python gives you
easy ways to manipulate these files. Generally files divide in two categories, text file and binary file.
Text files are simple text whereas the binary files contain binary data which is only readable by
computer
i) Text files: In this type of file, Each line of text is terminated with a special character called
EOL (End of Line), which is the new line character (‘\n’) in python by default.
ii) Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine understandable binary language.

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

Text files:
We can create the text files by using the syntax:
Variable name=open (“[Link]”, file mode)
For ex: f= open ("[Link]","w+")
We declared the variable f to open a file named [Link]. Open takes 2 arguments, the file that we
want to open and a string that represents the kinds of permission or operation we want to do on the
file. Here we used "w" letter in our argument, which indicates write and the plus sign that means it
will create a file if it does not exist in library.

The available options beside "w" are:


Mode Description Mode Description
'r' This is the default mode. It Opens file 'w' This Mode Opens file for writing.
for reading. If file does not exist, it creates a new file.
If file exists it truncates the file.
'x' Creates a new file. If file already exists, 'a' Open file in append mode.
the operation fails. If file does not exist, it creates a new file.
21
't' This is the default mode. It opens in text 'b' This opens in binary mode.
mode.
'+' This will open a file for reading and
writing (updating)

Reading and Writing files:


The following image shows how to create and open a text file in notepad from command prompt.

# Write a python Output: # Write a python Output:


program to open welcome to python program to open and
and read a file programming write “hello world”
a=open(“[Link]”,”r into a file?
”) f=open("[Link]","a")
print([Link]()) [Link]("hello world")
[Link]() [Link]()
# Write a python Output: # Write a python Output:
program to write the program to open and
content “hi python write the content to Discuss the output!
programming” for file and read it.
the existing file. fo=open("[Link]","w+
f=open("[Link]",'w') ")
[Link]("hi python [Link]("Python

22
programming") Programming")
[Link]() print([Link]())
[Link]()

Errors and Exceptions:


Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions when it encounters
errors. When writing a program, we, more often than not, will encounter errors. Error caused by not
following the proper structure (syntax) of the language is called syntax error or parsing error.

ZeroDivisionError: ZeroDivisionError in Python OverflowError: OverflowError in Python


indicates that the second argument used in a indicates that an arithmetic operation has
division (or modulo) operation was zero. exceeded the limits of the current Python
runtime. This is typically due to excessively
ImportError: It is raised when you try to import large float values, as integer values that are too
a module which does not exist. This may happen big will opt to raise memory errors instead.
if you made a typing mistake in the module name
or the module doesn't exist in its standard path. TypeError: When two unrelated type of objects
IndexError: An IndexError exception is raised are combined, TypeErrorexception is raised. For
when you refer a sequence which is out of range. example, if an int and a string is added, it will
result in TypeError exception.
IndentationError: Unexpected indent. You are Syntax errors: These are the most basic type of
free to choose the number of spaces of error. They arise when the Python parser is
indentation to use, but you then need to stick unable to understand a line of code. Syntax errors
with it. are almost always fatal, i.e. there is almost never
Run-time error: A run-time error happens when a way to successfully execute a piece of code
Python understands what you are saying, but containing syntax errors.
runs into trouble when following your Key Error: Python raises a KeyError whenever a
instructions. dict() object is requested (using the format a =
adict[key]) and the key is not in the dictionary.
Value Error: In Python, a value is the information that is stored within a certain object. To encounter
a ValueError in Python means that is a problem with the content of the object you tried to assign the
value to.

Python has many built-in exceptions which forces your program to output an error when something
in it goes wrong. In Python, users can define such exceptions by creating a new class. This exception
class has to be derived, either directly or indirectly, from Exception class.
Different types of exceptions:
 ArrayIndexOutOfBoundException.
 ClassNotFoundException.
 FileNotFoundException.
 IOException.
 InterruptedException.
 NoSuchFieldException.
 NoSuchMethodException

Handling Exceptions:
The cause of an exception is often external to the program itself. For example, an incorrect input, a
malfunctioning IO device etc. Because the program abruptly terminates on encountering an
exception, it may cause damage to system resources, such as files. Hence, the exceptions should be
properly handled so that an abrupt termination of the program is prevented.
Python uses try and except keywords to handle exceptions. Both keywords are followed by indented
blocks.
23
Syntax:
try :
#statements in try block
except :
#executed when error in try block
Typically we see, most of the times
1. Syntactical errors (wrong spelling, colon ( : ) missing ….), At developer level and compile
level it gives errors.
2. Logical errors (2+2=4, instead if we get output as 3 i.e., wrong output …..,), As a developer
we test the application, during that time logical error may obtained.
3. Run time error (In this case, if the user doesn’t know to give input, 5/6 is ok but if the user
say 6 and 0 i.e.,6/0 (shows error a number cannot be divided by zero)). This is not easy
compared to the above two errors because it is not done by the system, it is (mistake) done by
the user.

For ex: a=5


a=5 b=0
b=2 print(a/b)
print(a/b) print("bye") #this has to be printed, but abnormal termination
print("Bye") Output (error occurred):
Output (no error): Traceback (most recent call last):
2.5 File “<stdin>”, line 1, in <module>
Bye ZeroDivisionError: division by zero
#To overcome this we handle exceptions using Output:
except keyword number can not be divided by zero
a=5
b=0 indivisible division by zero
try:
print(a/b) bye
except ZeroDivisionError as e:
print("number can not be divided by zero")
print("indivisible", e)
print("bye")
Note: Except block executes, only when try Output:
block has an error, but finally block executes,
even though you get an exception. indivisible division by zero
a=5
b=0 resource closed
try: bye
print(a/b)
except ZeroDivisionError as e:
print("indivisible", e)
finally:
print("resource closed")
print("bye")

24

You might also like