Python Book
Python Book
O/P : e
Slicing
You can return a range of characters by using the slice
syntax.[start index : end index]
Specify the start index and the end index, separated by
a colon, to return a part of the string.
Default value of start index is 0(zero).
Default value of end index is until end it display.
Get the characters from position 2 to position 5 (not
included):
b = "Hello, World!“
print(b[2:5])
O/P : llo
print(b[:9])
print(b[4:])
print(b[:])
Negative Indexing
b = "Hello, World!"
print(b[-5:-2])
O/P :
String Length
a = "Hello, World!"
print(len(a))
O/P : 13
The strip() method removes any whitespace from the
beginning or the end:
a = “ Hello, World! "
print(a.strip())
O/P : "Hello, World!"
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
O/P : hello, world!
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
O/P : HELLO, WORLD!
thistuple = ("apple",)
print(type(thistuple))
Tuple
Tuple items can be of any data type.
A tuple can contain different data types.
You can access tuple items by referring to the index
number, inside square brackets.
Tuples are unchangeable, meaing that you cannot
change, add, or remove items once the tuple is created.
But there is a workaround. You can convert the tuple
into a list, change the list, and convert the list back
into a tuple.
Example
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
For conversion use list() and tuple() method.
Tuple
Once a tuple is created, you cannot add items to it.
You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove
items from it, but you can use the same workaround as
we used for changing and adding tuple items.
you can delete the tuple completely.
The del keyword can delete the tuple completely.
List Vs.Tuple
Syntax Differences
Lists are surrounded by square brackets [] and Tuples are
surrounded by parenthesis ().
list_num = [1,2,3,4]
tup_num = (1,2,3,4)
List has mutable nature i.e., list can be changed or
modified after its creation according to needs whereas
tuple has immutable nature i.e., tuple can’t be changed or
modified after its creation.
As the tuple is immutable these are fixed in size and list are
variable in size.
Lists has more builtin function than that of tuple.
Set
Sets are used to store multiple items in a single
variable.
A set is a collection which is both unordered
and unindexed.
Sets are written with curly brackets
Sets are unordered, so you cannot be sure in which
order the items will appear.
Example
thisset = {"a", "b", "c"}
print(thisset)
Set
Set items are unordered, unchangeable, and do not
allow duplicate values.
Unordered means that the items in a set do not have a
defined order.
Set items can appear in a different order every time you
use them, and cannot be refferred to by index or key.
Once a set is created, you cannot change its items, but
you can add new items.
Set items can be of any data type.
A set can contain different data types.
Set
You cannot access items in a set by referring to an
index or a key.
But you can loop through the set items using
a for loop, or ask if a specified value is present in a set,
by using the in keyword.
Here, the for loop prints items of the list until the loop
exhausts. When the for loop exhausts, it executes the
block of code in the else and prints No items left.
Priti Patel
Department of Computer Applications
Topics
Function
Functions
A function is a group of related statements that performs a
specific task.
A function is a block of code which only runs when it is
called.
Functions help break our program into smaller and
modular chunks.
As our program grows larger and larger, functions make it
more organized and manageable.
Furthermore, it avoids repetition and makes the code
reusable.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
Syntax :
def function_name(parameters):
"""docstring"""
statement(s)
Example
def greet(name):
""" This function greets to the person passed in as a parameter ""“
print("Hello, " + name + ". Good morning!")
Function Components
Keyword def that marks the start of the function header.
A function name to uniquely identify the function. Function
naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a
function. They are optional.
A colon (:) to mark the end of the function header.
Optional documentation string (docstring) to describe what the
function does.
One or more valid python statements that make up the function
body. Statements must have the same indentation level (usually
4 spaces).
An optional return statement to return a value from the
function.
Calling a Function
Once we have defined a function, we can call it from
another function, program or even the Python prompt.
To call a function we simply type the function name
with appropriate parameters.
Example
def greet(name):
""" This function greets to the person passed in as a parameter ""“
print("Hello, " + name + ". Good morning!")
greet(“priti”)
Hello, Priti. Good morning!
How Function works in Python?
Types of Functions
Basically, we can divide functions into the following
two types:
Built-in functions - Functions that are built into
Python.
User-defined functions - Functions defined by the
users themselves.
Arguments
Information can be passed into functions as
arguments.
Arguments are specified after the function name,
inside the parentheses. You can add as many
arguments as you want, just separate them with a
comma.
By default, a function must be called with the correct
number of arguments. Meaning that if your function
expects 2 arguments, you have to call the function with
2 arguments, not more, and not less.
Arguments
If you do not know how many arguments that will be
passed into your function, add a * before the
parameter name in the function definition.
This way the function will receive a tuple of arguments,
and can access the items accordingly:
If the number of arguments is unknown, add a * before
the parameter name:
def my_function(*subjects):
print("The most elected subject is " + subject[2])
my_function(“sub1", “sub2", “sub3")
Keyword Arguments
You can also send arguments with
the key = value syntax.
This way the order of the arguments does not matter.
def my_function(sub3, sub2, sub1):
print(" The most elected subject is " + sub3)
my_function(sub1 = “Hardware", sub2 = “Desktop
Publishing", sub3= “Accounting")
Keyword Arguments
If you do not know how many keyword arguments that
will be passed into your function, add two
asterisk: ** before the parameter name in the function
definition.
This way the function will receive a dictionary of
arguments, and can access the items accordingly:
If the number of keyword arguments is unknown, add
a double ** before the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Default Parameter Value
The following example shows how to use a default
parameter value.
If we call the function without argument, it uses the
default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
You can send any data types of argument to a function
(string, number, list, dictionary etc.), and it will be
treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a
List when it reaches the function:
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
To let a function return a value, use
the return statement:
def my(x):
return 5 * x
my(3)
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.
Scope and Lifetime of variables
Scope of a variable is the portion of a program where
the variable is recognized. Parameters and variables
defined inside a function are not visible from outside
the function. Hence, they have a local scope.
The lifetime of a variable is the period throughout
which the variable exits in the memory. The lifetime of
variables inside a function is as long as the function
executes.
They are destroyed once we return from the function.
Hence, a function does not remember the value of a
variable from its previous calls.
Scope and Lifetime of variables
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
The pass Statement
function definitions cannot be empty, but if you for
some reason have a function definition with no
content, put in the pass statement to avoid getting an
error.
def myfunction():
pass
Recursion
Python also accepts function recursion, which means a
defined function can call itself.
Recursion is a common mathematical and
programming concept. It means that a function calls
itself. This has the benefit of meaning that you can
loop through data to reach a result.
The developer should be very careful with recursion as
it can be quite easy to slip into writing a function
which never terminates, or one that uses excess
amounts of memory or processor power.
However, when written correctly recursion can be a
very efficient and mathematically-elegant approach to
programming.
Recursion
Recursion Example
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Recursion Example
Recursion Example
Python Anonymous/Lambda
Function
In Python, an anonymous function is a function that is
defined without a name.
While normal functions are defined using
the def keyword in Python, anonymous functions are
defined using the lambda keyword.
Hence, anonymous functions are also called lambda
functions.
Python Anonymous/Lambda
Function
Syntax of Lambda Function in python
lambda arguments: expression
Lambda functions can have any number of arguments
but only one expression.
The expression is evaluated and returned.
Lambda functions can be used wherever function
objects are required.
Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))
Python Anonymous/Lambda
Function
We can now call it as a normal function. The
statement
double = lambda x: x * 2
is nearly the same as:
def double(x):
return x * 2
Priti Patel
Department of Computer Applications
Topics
Module
Built in module
Module
A module is a file containing Python definitions and
statements.
we can use the module , by using
the import statement:
import module_name
When using a function from a module, use the syntax:
module_name.function_name
The module can contain functions, as already
described, but also variables of all types (arrays,
dictionaries, objects etc).
There are several built-in modules in Python, which
you can import whenever you like.
There are several built-in modules in Python, which
you can import whenever you like.
Module
import platform
x = platform.system()
print(x)
There is a built-in function to list all the function
names (or variable names) in a module.
The dir() function.
List all the defined names belonging to the platform
module:
import platform
x = dir(platform)
print(x)
Python Math
Python has a set of built-in math functions, including
an extensive math module, that allows you to perform
mathematical tasks on numbers.
The min() and max() functions can be used to find the
lowest or highest value in an iterable.
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
The pow(x, y) function returns the value of x to the
power of y (xy).
The Math Module
Python has also a built-in module called math, which
extends the list of mathematical functions.
To use it, you must import the math module.
import math
When you have imported the math module, you can
start using methods and constants of the module.
The math.sqrt() method for example, returns the
square root of a number.
import math
x = math.sqrt(64)
print(x)
The Math Module
The math.ceil() method rounds a number upwards to
its nearest integer, and the math.floor() method
rounds a number downwards to its nearest integer, and
returns the result.
The math.pi constant, returns the value of PI (3.14...).
Priti Patel
Department of Computer Applications
Topics
Array
Array
An array is a collection of items stored at contiguous
memory locations.
The idea is to store multiple items of the same type
together.
Arrays are sequence types and behave very much like
lists, except that the type of objects stored in them is
constrained.
Array Module
The array module allows us to store a collection of
numeric values.
In a way, this is like a Python list, but we specify a
type at the time of creation.
To create an array of numeric values, we need to
import the array module.
import array
class array.array(typecode[,initializer])
For example:
arr=array.array('i',[1,3,4])
Array Module
Type Code C Type Python Type
b signed char int
B unsigned char int
h signed short int
H unsigned short int
i signed int int
I unsigned int int
l signed long int
L unsigned long int
q signed long long int
Q unsigned long long int
f float float
d double float
Array Module
array.typecode
The typecode character used to create the array.
from array import *
array_num = array('i', [1,3,5,7,9])
array_num.typecode
array.itemsize
The length in bytes of one array item in the internal
representation.
array_num = array('i', [1,3,5,7,9,10,15])
array_num.itemsize
Array Module
array.append(x)
Append a new item with value x to the end of the array.
array_num = array('i', [1,3,5,7,9,10,15])
array_num.append(100)
array.count(x)
Return the number of occurrences of x in the array.
# How to count the number of occurrences of an
element in an array?
array_num = array('i', [1,3,5,7,9,10,15,10])
array_num.count(10)
Array Module
array.extend(iterable)
Append items from iterable to the end of the array. If
iterable is another array, it must have exactly the same
type code; if not, TypeError will be raised.
# How to extend an array with values from a list?
from array import *
array_num = array('i', [1, 3, 5, 7, 9])
print("Original array: "+str(array_num))
array_num.extend(array_num)
print("Extended array: "+str(array_num))
Array Module
array.index(x)
Return the smallest i such that i is the index of the first
occurrence of x in the array.
array.insert(i, x)
Insert a new item with value x in the array before
position i. Negative values are treated as being relative
to the end of the array.
array.pop([i])
Removes the item with the index i from the array and
returns it. The optional argument defaults to -1,
so that by default the last item is removed and
returned.
Array Module
array.remove(x)
Remove the first occurrence of x from the array.
array.reverse()
Reverse the order of the items in the array.
array.tolist()
Convert the array to an ordinary list with the same
items.
Concatenate two arrays in Python
arr+arr
Multiply an array by a constant
arr*2
Priti Patel
Department of Computer Applications
Flow Chart
A flowchart is a diagrammatic representation of an
algorithm.
A flowchart can be helpful for both writing programs and
explaining the program to others.
A flowchart is a diagram that depicts a process, system or
computer algorithm
Flowchart is a diagrammatic representation of sequence of
logical steps of a program.
Flowcharts use simple geometric shapes to depict processes
and arrows to show relationships and process/data flow.
Symbols Used In Flowchart
Symbols Used In Flowchart
Guidelines for Developing
Flowcharts
Flowchart can have only one start and one stop symbol
On-page connectors are referenced using numbers
Off-page connectors are referenced using alphabets
General flow of processes is top to bottom or left to
right
Arrows should not cross each other
Flowchart for going to the market
to purchase a pen.
Examples of flowcharts in programming
Add two numbers entered by the user.