0% found this document useful (0 votes)
4 views54 pages

UNIT I

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 54

Unit-I Computational Thinking and Programming – 2

Revision of Python topics covered in class XI


PYTHON BASICS

Python is a simple, general purpose, high level, and object-oriented programming


language.Python is an interpreted scripting language also. Guido Van Rossum is the founder of
Python programming language.Guido was a fan of the popular BBC comedy show of that time,
"Monty Python's Flying Circus". So he decided to pick the name Python for his newly created
programming language.

Features of Python
● Python is a general purpose, dynamic, high-level, and interpreted programming language.
It supports Object Oriented programming approach to develop applications. It is simple
and easy to learn and provides lots of high-level data structures.
● Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
● Python's syntax and dynamic typing with its interpreted nature make it an ideal language
for scripting and rapid application development.
● Python supports multiple programming pattern, including object-oriented, imperative,
and functional or procedural programming styles.
● Python is not intended to work in a particular area, such as web programming. That is
why it is known as multipurpose programming language because it can be used with web,
enterprise, 3D CAD, etc.
● We don't need to use data types to declare variable because it is dynamically typed so we
can write a=10 to assign an integer value in an integer variable.
● Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.

Applications of Python Programming Language


● Data Science
● Date Mining
● Desktop Applications
● Console-based Applications
● Mobile Applications
● Software Development
● Artificial Intelligence
● Web Applications
● Enterprise Applications
● 3D CAD Applications
● Machine Learning

23
● Computer Vision or Image Processing Applications.
● Speech Recognitions

How To Use Python?


Python can be downloaded from www.python.org. (Standard Installation)
It is available in two versions-
• Python 2.x
• Python 3.x (It is in Syllabus)
Apart from above standard Python. We have various Python IDEs and Code Editors. Some of them
are as under:
(i) Anaconda Distribution: free and open-source distribution of the Python, having various inbuilt
libraries and tools like Jupyter Notebook, Spyder etc
(ii) PyCharm (iii) Canopy (iv) Thonny (v) Visual Studio Code (vi) Eclipse + PyDev
(vii) Sublime Text (viii) Atom (ix) GNU Emacs (x) Vim (xi) Spyder and many
more . .

Python Interpreter - Interactive And Script Mode:


We can work in Python in Two Ways:
(i) Interactive Mode: It works like a command interpreter as shell prompt works in DOS Prompt or
Linux. On each (>>>) symbol we can execute one by one command.
(ii) Script Mode: It used to execute the multiple instruction (complete program) at once.

Python Character Set:


Character Set is a group of letters or signs which are specific to a language. Character set includes
letter, sign, number and symbol.
● Letters: A-Z, a-z
● Digits: 0-9
● Special Symbols: _, +, -, *, /, (, #,@, {, } etc.
● White Spaces: blank space, tab, carriage return, newline, form feed etc.
● Other characters: Python can process all characters of ASCII and UNICODE.
Tokens
A token is the smallest individual unit in a python program. All statements and instructions in a
program are built with tokens.It is also known as Lexical Unit.
Types of token are
● Keywords
● Identifiers (Names)
● Literals
● Operators
● Punctuators

24
Keywords
Python keywords are unique words reserved with defined meanings and functions that we can only
apply for those functions.Python contains thirty-five keywords in the version, Python 3.9.
Identifiers
In programming languages, identifiers are names used to identify a variable, function, or other
entities in a program. The rules for naming an identifier in Python are as follows:
● The name should begin with an uppercase or lowercase alphabet or an underscore sign (_).
● This may be followed by any combination of characters a-z, A-Z, 0-9 or underscore (_).
Thus, an identifier cannot start with a digit.
● It can be of any length. (However, it is preferred to keep it short and meaningful).
● It should not be a keyword or reserved word.
● We cannot use special symbols like !, @, #, $, %, etc. in identifiers.
Legal Identifier Names Example:
Myvar my_var _my_var myVar myvar2
Illegal Identifier Names Example:-
2myvar my-var my var= 9salary

Literals or Values:
Literals are the fixed values or data items used in a source code. Python supports different types
of literals such as:
a. String literals - “Rishaan”
b. Numeric literals – 10, 13.5, 3+5i
c. Boolean literals – True or False
d. Special Literal None
e. Literal collections
Literal collections
Literals collections in python includes list, tuple, dictionary, and sets.
● List: It is a list of elements represented in square brackets with commas in between.
These variables can be of any data type and can be changed as well.
● Tuple: It is also a list of comma-separated elements or values in round brackets. The
values can be of any data type but can’t be changed.
● Dictionary: It is the unordered set of key-value pairs.
● Set: It is the unordered collection of elements in curly braces ‘{}’.

Operators
An operator is used to perform specific mathematical or logical operation on values. The values
that the operator works on are called operands.
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators

25
● Identity operators
● Membership operators
● Bitwise operators

Arithmetic operators: used with numeric values to perform common mathematical operations.
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y

Assignment operators: used to assign values to variables


= x=5 x=5
+= x += 3 x=x+
3
-= x -= 3 x=x-3
*= x *= 3 x=x*
3
/= x /= 3 x=x/3
%= x %= 3 x=x%
3
//= x //= 3 x = x //
3
** x **= 3 x = x **
= 3
&= x &= 3 x=x&
3
|= x |= 3 x=x|3
^= x ^= 3 x=x^
3
>> x >>= 3 x = x >>
= 3
<< x <<= 3 x = x <<
= 3

Comparison Operators: Comparison operators are used to compare two values.


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y

26
<= Less than or equal to x <= y

Logical Operators: Logical operators are used to combine conditional statements


an Returns True if both statements are true x < 5 and x <
d 10
or Returns True if one of the statements is true x < 5 or x < 4
no Reverse the result, returns False if the result is not(x < 5 and x < 10)
t true

Identity Operators: used to compare the objects, not if they are equal, but if they are actually the

27
same object, with the same memory location.
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y

Membership operators: used to test if a sequence is present in an object.


in Returns True if a sequence with the specified x in y
value is present in the object
not in Returns True if a sequence with the specified x not in y
value is not present in the object

Punctuators
Punctuators are symbols that are used in programming languages to organize sentence
structure, and indicate the rhythm and emphasis of expressions, statements, and program
structure. Common punctuators are: „ “ # $ @ []{}=:;(),

Python 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 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.
● Variables are containers for storing data values.
● Unlike other programming languages, Python has no command for declaring a variable.
● A variable is created the moment you first assign a value to it.
Example:
x=5
y = "John"
print(x)
print(y)
● Variables do not need to be declared with any particular type and can even change
type after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
● String variables can be declared either by using single or double quotes:
x = "John"
# is the same as
x = 'John'
Output Variable:
The Python print statement is often used to output variables. To combine both text and a
variable, Python uses the, character:
x = "awesome"
28
print("Python is " , x)
Display Multiple variable:-
x = "awesome“
y=56
print(“Value of x and y is=" , x, y)

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables. Also Python allows you to assign a single value to several variables
simultaneously.
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
counter = 100 # An integer
assignment miles = 1000.0 # A floating
point
name = "John" # A string

print
(counter)
print (miles)
print (name)
a=b=c=
1
a,b,c = 1,2,"john"

Data Types
The data stored in memory can be of many types, i.e., Every value belongs to a specific data type
in Python. Data type identifies the type of data which a variable can hold and the operations that
can be performed on those data.Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.

29
The different standard data types −
● Numbers

30
● String
● List
● Tuple
● Dictionary
● Boolean
● Set
Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them. For example −
var1 = 1
var2 = 10

Python supports four different numerical types


● int (signed integers)
● long (long integers, they can also be represented in octal and hexadecimal)
● float (floating point real values)
● complex (complex numbers)
in long floa complex
t t
10 51924361L 0.0 3.14j
1 -0x19323L 15. 45.j
0 20
0
-786 0122L -21.9 9.322e -36j
0 0xDEFABCECBDAE 32.3+e18 .87
8 6j
0
-0490 535633629843L - -.6545+
9 0J
0.
- -052318172735L - 3e+26J
0x260 32.54e100
0x -4721885298529L 70.2-E12 4.53e-7j
69

You can also delete the reference to a number object by using the del statement. The syntax
of the del statement is −

del var1[,var2[,var3[ ,varN]]]]


e.g. del var
del var_a, var_b

Strings
31
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. Subsets of strings can be taken
using the slice operator ([ ] and [:] ).
str = 'Hello World!'

print str # Prints complete string Hello World!


print str[0] # Prints first character of the string H

32
print str[2:5] # Prints characters starting from 3rd to 5th llo
print str[2:] # Prints string starting from 3rd character llo World!
print str * 2 # Prints string two times Hello World!Hello World!
print str + "TEST" # Prints concatenated string Hello World!TEST

Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]).
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting
at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list ['abcd', 786, 2.23, 'john', 70.2]
print list[0] # Prints first element of the list- abcd
print list[1:3] # Prints elements starting from 2nd till 3rd - [786, 2.23]
print list[2:] # Prints elements starting from 3rd element -[2.23, 'john', 70.2]
print tinylist * 2 # Prints list two times-[123, 'john', 123, 'john']
print list + tinylist # Prints concatenated lists-['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Lists are enclosed in brackets ( [ ] ) and their elements and size can
be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print tuple # Prints the complete tuple--('abcd', 786, 2.23, 'john', 70.2)
print tuple[0] # Prints first element of the tuple-- abcd
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd--(786, 2.23)
print tuple[2:] # Prints elements of the tuple starting from 3rd element--(2.23, 'john', 70.2)
print tinytuple * 2 # Prints the contents of the tuple twice--(123, 'john', 123, 'john')
print tuple + tinytuple # Prints concatenated tuples-- ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

Dictionary
Python's dictionaries are kind of hash table type. They consist of key-value pairs. A dictionary
key can be almost any Python type, but are usually numbers or strings. Values, on the other
hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]). For example −

33
dict = {}

34
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key This is one
print dict[2] # Prints value for 2 key This is two
print tinydict # Prints complete dictionary {'dept': 'sales', 'code': 6734, 'name': 'john'}
print tinydict.keys() # Prints all the keys ['dept', 'code', 'name']
print tinydict.values() # Prints all the values ['sales', 6734, 'john']

Boolean
Boolean represent one of two values: True or False. When you compare two values, the
expression is evaluated and Python returns the Boolean answer.Also, almost any value is
evaluated to True if it has some sort of content.
print(10 > 9) True bool(None) Fal
se
print(10 == 9) False bool(0) Fals
e
print(10 < 9) False bool("") False
bool("abc") True bool(()) False
bool(123) True bool([]) False
bool(["apple", "cherry"])True bool({}) False
bool(False) False

Mutable and Immutable Objects in Python


Everything in Python is an object. So, every variable holds an object instance. All objects in
Python can be either mutable or immutable. When an object is initiated, it is assigned a unique
object id. Its type is defined at runtime and once set can never change, however its state can be
changed if it is mutable. Generally, a mutable object can be changed after it is created, and an
immutable object can’t.

Mutable objects
Mutability means the ability to modify or edit a value. Mutable objects in Python enable the
programmers to have objects that can change their values. They generally are utilized to store
a collection of data. It can be regarded as something that has mutated, and the internal state
applicable within an object has changed.

35
In mutable data types, we can modify the already existing values of the data types (such as lists,
dictionaries, etc.). Or, we may add new values or remove the existing values from our data types.
Basically, we may perform any operation with our data without having to create a new copy of
our data type. Hence, the value assigned to any variable can be changed.
e.g.color = ["red", "blue", "green"]
print(color) color[0] = Output:
"pink" ['red', 'blue', 'green']
color[-1] = "orange" print(color) ['pink', 'blue', 'orange']

Immutable Objects
Immutable objects in Python are objects wherein the instances do not change over the period.
Immutable instances of a specific type, once created, do not change, and this can be verified
using the id method of Python
e.g.message = "Welcome to GeeksforGeeks"
message[0] = 'p'
print(message)
Output
Traceback (most recent call last):
File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3,
in message[0] = 'p'
TypeError: 'str' object does not support item assignment

❖ Exception: However, there is an exception in immutability as well.Tuple in python is


immutable. But the tuple consists of a sequence of names with unchangeable bindings to
objects.

36
Consider a tuple
tup = ([3, 4, 5], 'myname')
The tuple consists of a string and a list. Strings are immutable so we can’t change its value. But the
contents of the list can change. The tuple itself isn’t mutable but contain items that are mutable.

Expression in python:
A combination of constants, operands and operators is called an expression. The expression in
Python produces some value or result after being interpreted by the Python interpreter. The
expression in Python can be considered as a logical line of code that is evaluated to obtain some
result. If there are various operators in an expression then the operators are resolved based on
their precedence.
E.g. Expression 6-3*2+7-1 evaluated as 6

Types of Expression in Python


Constant Expressions x = 10 + 15
Arithmetic Expressions y=x**3+x-2+5/2
Integral Expressions x=10 y=5.00 result = x + int(y)
Floating Expressions result = float(x) + y
Relational Expressions 10+15>20
Logical Expressions r=x and y
Combinational Expressions result = x + (y << 1)

Type Casting in Python


Type Casting is the method to convert the variable data type into a certain data type in order to
the operation required to be performed by users.
There can be two types of Type Casting in Python –
● Implicit Type Casting
● Explicit Type Casting

Implicit Type Conversion


In this, methods, Python converts data type into another data type automatically, where users
don’t have to involve.

37
# Python automatically converts
# a to int
a=7
print(type(a))
# Python automatically converts
# b to float
b = 3.0
print(type(b))
# Python automatically converts
# c to float as it is a float addition
c=a+b
print(c)
print(type(c))
# Python automatically converts
# d to float as it is a float multiplication
d=a*b
print(d)
print(type(d))

Explicit Type Casting


In this method, Python need user involvement to convert the variable data type into certain data
type in order to the operation required.Mainly in type casting can be done with these data type
function:

int() : int() function take float or string as an argument and return int type object.
float() : float() function take int or string as an argument and return float type object.
str() : str() function take float or int as an argument and return string type object.

E,g, # int variable


a=5
# typecast to float
n = float(a)
print(n)
print(type(n))

Precedence and Associativity of Operators


Operator Precedence: This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.

38
Operator Associativity: If an expression contains two or more operators with the same precedence
then Operator Associativity is used to determine. It can either be Left to Right or from Right to
Left.

Comments in python:
Comments are non-executable statements of python. It increases the readability and
understandability of code.
Types of comment:
i. Single line comment (#) – comments only single line.
e.g. a=7 # 7 is assigned to variable ‘a’
print(a) # displaying the value stored in ‘a’

ii. Multi-line comment (‘‘‘ ’’’) – Comments multiple line.


e.g. ‘‘‘Program -1
A program in python to store a value invariable ‘a’ and display the value stored in it.’’’
a=7
print(a)

Python Input and Output


Python executes code top to bottom, when written in the correct syntax.Once the interpreter is running
you can start typing in commands to get the result.

Input using the input( ) function


input (): This function first takes the input from the user and converts it into a string. The type of
the returned object always will be <type ‘str’>. It does not evaluate the expression it just returns the
complete statement as String. Python provides a built-in function called input which takes the input
from the user. When the input function is called it stops the program and waits for the user’s input.
When the user presses enter, the program resumes and returns what the user typed.
name = input('What is your name?\n')
What is your name?
Ram

39
Taking multiple inputs from user

40
Using split() method
Using List comprehension
split() method :
This function helps in getting multiple inputs from users. It breaks the given input by the specified
separator. If a separator is not provided then any white space is a separator. Generally, users use a
split() method to split a Python string but one can use it in taking multiple inputs.
input().split(separator, maxsplit)
List comprehension is an elegant way to define and create list in Python. We can create lists just like
mathematical statements in one line only. It is also used in getting multiple inputs from a user.
x, y, z = [int(x) for x in input("Enter three values: ").split()]

Output using print() function


print() : function prints the message on the screen or any other standard output device.

print(value(s), sep= ' ', end = '\n', file=file, flush=flush)

value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False

Debugging:-
Debugging is a process of locating and removing errors from program.
Errors in a program
An error or exception refers to an interruption in the execution of code due to which we cannot
attain the expected outcome to the end-users. These errors are classified on the basis of the event
when the program generate the error. The two types of errors are Compile Time Errors and
Runtime Errors and Logical errors

Compile Time Errors


These errors occur when we violate the rules present in a syntax. The compile-time error indicates
something that we need to fix before compiling the code. A compiler can easily detect these errors.
Eg Syntax error and Semantic Error.
Logic errors
These errors are not always easy to recognize immediately. This is due to the fact that such errors,
unlike that of syntax errors, are valid when considered in the language, but do not produce the
intended behavior. These can occur in both interpreted and compiled languages. It may occur due
41
to the logic of the program.

42
Runtime Errors
These errors occur during the run-time program execution after a successful compilation. Division
error is one of the most common errors (runtime). It occurs due to the division by zero. It is very
difficult for a compiler to find out a runtime error because it cannot point out the exact line at
which this particular error occurs.

Control flow statements


The control flow of a Python program is regulated by conditional statements, loops, and function
calls. In order to control the flow of execution of a program there are three categories of statements
in python. They are:
1. Selection statements
2. Iteration statements
3. Jump statements / Transfer statements

Selection Statements
Decision making is valuable when something we want to do depends on some user input or some
other value that is not known when we write our program. This is quite often the case and Python,
along with all interesting programming languages, has the ability to compare values and then take
one action or another depending on that outcome.
Python have following types of selection statements
1. if statement
2. if else statement
3. Ladder if else statement (if-elif-else)
4. Nested if statement

if statements
This construct of python program consist of one if condition with one block of statements. When
condition becomes true then executes the block.

43
Syntax:

44
if ( condition):
Statement(s)
Example:
age=int(input(“Enter Age: “))
if ( age>=18):
print(“You are eligible for vote”)
if(age<0):
print(“You entered Negative Number”)

if - else statements
This construct of python program consist of one if condition with two blocks. When condition
becomes true then executes the block given below
Syntax:
if ( condition):
Statement(s)
else:
Statement(s)
Example
x = int(input("Please enter an integer: "))
y = int(input("Please enter another integer: "))
i f x > y:
print(x,"is greater than",y)
else:
print(y,"is greater than or equal to",x)

Ladder if else statements (if-elif-else)


The Python compound statement if, which uses if, elif, and else clauses, lets you
conditionally execute blocks of statements. Here’s the syntax for the if statement:
if expression:
statement(s)
elif expression:
statement(s)
elif expression:
statement(s)
...
else:
statement(s)
Example

i = 20
if (i == 10):
45
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")

Nested-if
Nested if statements mean an if statement inside another if statement.
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

num=int(input(“Enter Number: “))


if ( num<=0):
if ( num<0):
print(“You entered Negative number”)
else:
print(“You entered Zero ”)
else:
print(“You entered Positive number”)

Python Iteration Statements

The iteration (Looping) constructs mean to execute the block of statements again and again
depending upon the result of condition. This repetition of statements continues till condition meets
True result. As soon as condition meets false result, the iteration stops.
Python supports following types of iteration statements
1. while
2. for
Four Essential parts of Looping:
i. Initialization of control variable
ii. Condition testing with control variable
iii. Body of loop Construct
iv. Increment / decrement in control variable
46
for loop
For loops are useful when you need to do something for every element of a sequence
<statements before for loop>
for <variable> in <sequence>:
<body of for loop>
<statements after for loop>
Example
s = input("Please type some characters and press enter:")
for c in s:
print(c)
print("Done")

while Loop
Python's while statement is its most general iteration construct. In simple terms, it repeatedly
executes a block of indented statements, as long as a test at the top keeps evaluating to a true value.
When the test becomes false, control continues after all the statements in the while, and the body
never runs if the test is false to begin with.
while <test>: # loop test
<statements1> # loop body
else: # optional else
<statements2> # run if didn't exit loop with b
Example
count = 0
while (count < 9):
print ('The count is:', count )
count = count + 1
print ("Good bye!" )

Python supports to have an else statement associated with a loop statement. If the else statement is
used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If
the else statement is used with a while loop, the else statement is executed when the condition
becomes false
Example:
count = 0
while count < 5:
print (count, " is less than 5" )
count = count + 1
else:
print( count, " is not less than 5”)

Single Statement Suites: If there is only one executable statement in while loop, then we can use this
47
format.
Example:
flag = 1
while (flag): print ('Given flag is really true!' )
print( "Good bye!" )

Jump Statements
Now that we‘ve seen a few Python loops in action, it‘s time to take a look at two simple statements that
have a purpose only when nested inside loops—the break and continue statements.

In Python:
pass
Does nothing at all: it‘s an empty statement placeholder
break
Jumps out of the closest enclosing loop (past the entire loop statement)
continue
Jumps to the top of the closest enclosing loop (to the loop‘s header line)

Python range( ) Function


The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number.
Syntax:
range( start value, stop value, step value )
Where all 3 parameters are of integer type
● Start value is Lower Limit
● Stop value is Upper Limit
● Step value is Increment / Decrement
Note: The Lower Limit is included but Upper Limit is not included in result.

Example
range(5) => sequence of 0,1,2,3,4
range(2,5) => sequence of 2,3,4
range(1,10,2) => sequence of 1,3,5,7,9
range(5,0,-1) => sequence of 5,4,3,2,1
range(0,-5) => sequence of [ ] blank
list (default Step is +1)
range(0,-5,-1) => sequence of 0, -1, -2, -3, -4
range(-5,0,1) => sequence of -5, -4, -3, -2, -1
48
range(-5,1,1) => sequence of -5, -4, -3, -2, -1, 0

WORKING WITH FUNCTIONS


Function Definition:
A function is a programming block of codes which is used to perform a single, related,
specific task. It only works when it is called. We can pass data, known as parameters, into a
function. A function can return data as a result.
Python treats functions like a first-class member. It implies that in Python, functions and
other objects are of same significance.Functions can be assigned to variables, stored in collections,
or passed as arguments. This brings additional flexibility to the language.

Advantages of Functions
● Reducing duplication of code
● Decomposing complex problems into simpler pieces
● Improving clarity of the code
● Reuse of code
● Information hiding
Python function types
There are three categories of functions:
● Built-in functions

49
● Function defined in modules
● User defined functions.
Built-in functions
The functions whose functionality is predefined in Python are referred to as built-in functions.
The python interpreter has several such functions that are always available for use.
E.g. len(), type(), int(), input()
Function defined in modules
These functions are pre-defined in particular modules and can only be used after the specific
module is imported.
E.g. All mathematical functions are defined in the module math.
User-defined functions
Python User Defined Functions allow users to write unique logic that the user defines. It is
the most important feature in Python that consists of custom-defined logics with a set of rules and
regulations that can be passed over the data frame and used for specific purposes.

Structure of functions in Python

Internally Python names the segment with top-level statements (no indentation) as
_main_ Python begins execution of a program from top-level statements.
Defining a Function
A function in Python is defined as given below:
def< function name >(parameters):
[“ ” ”<function’s docstring>” “ “]
<statements>
[<statements>
]
……………………..
50
● 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.

Function header:
The Header of a function specifies the name of the function and the name of each
of its parameters. It begins with the keyword def.
Parameters:

Variables that are listed within the parenthesis of a function header.


Function Body:
The block of statements to be carried out, ie the action performed by the function.
Indentation:
The blank space needed for the python statements. (four spaces convention)

Flow of execution in a function call


The flow refers to the order in which statements are executed during a program run. The
function body is a block of statements and python executes every block in an execution frame.
An execution frame contains:
● Some internal information (used for debugging)
● Name of the function
● Values passed to the function
● Variables created within the function
51
● Information about the next instruction to be executed

Whenever a function call statement is encountered, an execution frame for the function is
created and the control is transferred to it. The statements are then executed and if there is
return statement in the program, it will be executed and returns to the function call
statement block.

def message():
print('Hello I am learning how to create function in python.')

def
sum(a,b):
c=a+b
print('Sum of %d and %d is %d' %(a,b,c))

# main program
# calling the function
message() message()
# calling the function
sum() sum(10,20)
In the above program, two functions message() and sum() is declared. The message()
function does not accept any argument but displays a text on the screen whenever we call it. On the
other hand, the sum() function accept two arguments and display their sum on the screen. when the
main program calls the function message(), the program flow goes to the body of the function
message() and execute its codes. After that, it returns to the main program and then calls the second
function sum() by sending it two arguments (10,20), the program flow goes to the body of the
function sum(), and execute its code and again returns to the main program. At last, the main
programs end.
The function calling another function is called the caller and the functions being
called is the called function or callee.

Parameters and Arguments


The parameters are the variables that we can define in the function declaration. In fact, we
utilized these variables within the function. Also, the programming language in the function
description determines the data type specification. These variables facilitate the function’s entire
execution. In addition, they are known as local variables because they are only available within the
function.
The arguments are the variables given to the function for execution. Besides, the local
variables of the function take the values of the arguments and therefore can process these
52
parameters for the final output.

53
Passing parameters:-
Python support three types of formal arguments/parameters:
1. Positional argument (required arguments):-
When the functions call statement must match the number and order of arguments as
define in the functions definition this is called the positional arguments.
Example:-
def check(a,b,c):
:
Then possible functions call for this can be:-
check(x,y,z)#3values(allvariables)passed
check(2,x,y)#3values(literal+variables)passed
check ( 2 , 3 , 4 ) # 3 values ( all literal ) passed.
Thus through such function calls-
• The argument must be provided for all parameters (required)
• The values of argument are matched with parameters, position(order)wise(positional)

2. Default arguments:-
A parameter having defined value in the function header is known as a default parameter.
Example:-
def interest(principal,time,rate=10):
si=interest(5400,2) #third argument missing
So the parameter principal get value 5400,time get 2 and since the third argument rate is missing, so
default value 0.10 is used for rate.
• Default argument are useful in situations where some parameters always have same
value.
Some advantages of the default parameters are listed below:-

54
• They can be used to add new parameters to the existing functions.
• They can be used to combine similar function in to one.

3. Keyword(or named)arguments:-
Keyword arguments are the named arguments with assigned values being passed in the
function call statement.
Example:-
def interest(prin,time,rate):
return prin * time * rate
print (interest ( prin = 2000 , time = 2 , rate 0.10 ))
print (interest ( time = 4 , prin = 2600 , rate = 0.09 ))
print(interest(time=2,rate=0.12,prin=2000))
All the above functions call are valid now, even if the order of arguments does not match.
4. Using multiple argument type together:-
Python allows you to combine multiple argument types in a function call.
Rules for combining all three types of arguments:-
 And argument list must first contain positional(required) arguments followed by any
keyword argument.
• Keyword arguments should be taken from the required arguments preferably.
• You cannot specify a value for an argument more than once.
Example:-
def interest(prin,cc,time=2,rate=0.09):
return prin * time * rate
Types of user defined function
1. No Argument No return
2. With Argument No return
3. No Argument with return
4. With Argument with return

1. No Argument No return
def Add():
a= int (input(“Enter First Number”)) b=
int (input(“Enter Second Number”))
c=a+b
print (“The Sum of inputted Numbers is:”, c)
Add()
print(“ Executed”)

2. With Argument No return


def Add(a,b):
c=a+b
55
print(“The Sum of inputted Numbers is:”, c)
num1=int (input(“Enter First Number”)) num2= int
(input(“Enter Second Number”)) add(num1,num2)

Remember: The variable in main program are differ from the variable in function definition i.e. a
and b should be x and y. In this scenario the variable passed (num1,num2)will be called argument,
and when it replace with the variable defined in the function will be called as parameter.
3. No Argument with return
def Add():
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
return c
x= add()
print (“The Sum of inputted Numbers is:”, x)

Note: { As return does not show the result we have to store the returned value on another
variable x}
4. With Argument with return
def Add (a,b):
c=a+b return
c
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”)) x=
add(a,b)
print (“The Sum of inputted Numbers is:”, x)

Calling function and Called function:


● Function which is called by another Function is called Called Function. The called
function contains the definition of the function and formal parameters are associated
with them.
● The Function which calls another Function is called Calling Function and
actual Paramaters are associated with them.
● In python, a function must be defined before the function call otherwise
python interpreter gives an error.

Difference between Arguments and parameters


These two terms are very interchangeable, so it is not so important to know the difference.
The terms they refer to are almost identical. However, in order to sound more professional, correct
terminology is important.
Function Parameters: Variables that are in brackets when defining the function. When a method

56
is called, the arguments are the data passed to the method’s parameters.

57
Function arguments : Arguments are used to pass information from the rest of the program to the
function. This information return a result. There is no limit to the number of arguments that can be
written. Depending on the type of function you’re performing, there might even be no argument.
Use commas to separate the arguments in a function. Take into account the number of
arguments you put in a function call. The number of arguments must be exactly the same as the
number of parameters.

In the example below, the variable name is the input parameter, where as the value, “Arnav”,
passed in the function call is the argument.

def welcome(name):
print("Hello! " + name + " Good Morning!!")
welcome("Arnav")
Output:
Hello! Arnav Good Morning!!

Returning a Function
If you wish to return some values from the function to the rest of the program, you can use
the return statement. As the name suggests, it returns a value without printing it. Executing this
statement will cause the Python function to end immediately and store the value being returned into
a variable.
Scope of variables
Scope means in which part(s) of the program, a particular piece of code or data is accessible
or known.
In python there are broadly 2 kinds of Scopes:
● Global Scope
● Local Scope
Global Scope:
● A name declared in top level segment(_main_) of a program is said to have global scope
and can be used in entire program.
● Variable defined outside of the all functions are global variables.
Local Scope :
● A name declared in a function body is said to have local scope i.e. it can be used only
within this function and the other block inside the function.
● The formal parameters are also having local scope.

When dealing with Python functions, you should also consider the scope of the variables.
The code in a function is in its own little world, separate from the rest of the program. Any variable
declared in the function is ignored by the rest of the function. This means that two variables with
the same name can exist, one inside the function and the other outside the function. However, this
is not a good practice. All variable names must be unique regardless of their scope.

58
Local variable: A variable that is defined within a function and can only be used within that
particular function. With respect to the local variable, the area in a function is called “local area”.
Global variable: A variable that is defined in the main part of the programming and, unlike local
variables, can be accessed via local and global areas.
Example:

Lifetime of Variables:
Lifetime is the time for which a variable lives in memory. For global variables the lifetime
is entire program run i.e. as long as program is executing. For local variable, lifetime is their
function’s run i.e. as long as function is executing.

Name Resolution(Scope Resolution)


For every name used within program, python follows name resolution rules
known as LEGB rule.
● Local Environment : first check whether name is in local environment, if yes
Python uses its value otherwise moves to (ii)
● Enclosing Environment:if not in local,Python checks whether name is in Enclosing
Environment, if yes Python uses its value otherwise moves to (iii)
● Global Environment:if not in above scope Python checks it in Global environment,
if yes Python uses it otherwise moves to (iv)
● Built-In Environment:if not in above scope, Python checks it in built-in
environment, if yes, Python uses its value otherwise Python would report the error:
name <variable> notdefined.
FILE HANDLING
Files are of bytes stored on storage devices such as hard-disks. Files help in storing
information permanently on a computer.
Data Files:

59
Data files are files that store data pertaining to a specific application. The data files
can be stored in following ways:
● Text files: These files store information in the form of a stream of ASCII or UNICODE
characters. Each line is terminated by an EOL character. Python programs, contents written
in text editors are some of the example of text files.
● Binary files: These files store information in the form of a stream of bytes. No EOL
character is used and binary files hold information in the same format in which it is held in
the memory. The .exe files, mp3 file, image files, word documents are some of the examples
of binary files.We can’t read a binary file using a text editor.
Difference Between Text File And Binary File
Text Binary
File File
Stores information in ASCII characters. Stores information in the same format which
the information is held in memory.
Less prone to get corrupt as change reflects Can easily get corrupted, corrupt on even
as single
soon as made and can be undone. bit change.
Store only plain text in a file. Can store different types of data.
Widely used file format and can be opened in Developed for an application and can be
any text editor. opened in that only.
Slower than binary files. Binary files are faster and easier for a
program to read and write the text files.
Opened in any text editor. Mostly .txt and .rtf Can have any application defined extensions.
are used as extensions of text files.

In Python, File Handling consists of following three steps:


● Open the file.
● Process file i.e.perform read or write operation.
● Close the file.

60
Opening Files :
To perform file operation, it must be opened first then after reading, writing,editing
operation can be performed.To create any new file then too it must be opened. On opening
of any file, a file relevant structure is created in memory as well as memory space is
created to store contents. Once we are done working with the file, we should close the file.
Itisdoneusing open() function as per one of the following syntax:
<fileobjectname>=open(<filename>)
<fileobjectname>=open(<filename>,<mode>)
For example:
stu=open("students.txt")
The above statement open file"students.txt" in file mode as read mode(defaultmode) and attaches it
to file object namely stu.
Consider one more file open statement: - stu=open ("e:\\main\\
students.txt","w")
The above statement open file"students.txt"(storedinfoldere:\main)in write
mode(because of"w"givenasmode)and attaches it to file object namely stu.

• Please note that when you open a file in read mode,the given file must exist in folder,
otherwise Python will raise error.

File Object/File Handle:-A file object is a reference to a file on disk.It opens and makes it
available for a number of different tasks.
FileAccessModes:-

T Bina
Description
ex ry
t File
fil Mode
e
mode
‘r’ ‘rb’ Read-Default value. Opens a file for reading, error if the
file does not exist.

‘w’ ‘wb’ Write- Opens a file for writing, creates the file if it does
not exist

61
‘a’ ‘ab’ Append- Opens a file for appending, creates the file if it
does not exist

‘r+’ ‘rb+’ Read and Write- File must exist, otherwise error is raised.

62
‘w+’ ‘wb+’ Read and Write-File is created if does not exist.

‘a+’ ‘ab+’ Read and write – Append new data

A file-mode governs the type of operations(e.g.,read/write/append) possible in the opened file i.e., it
refers to how the file will be used once it's opened.

Closing Files :

One must always close a file when the file is no longer required for any more
operations.The file can be closed by using the close( ) function which can be used w ith the
file pointer as follows:
<file_handle>.close()
Working with Text Files:
1. Read the data from a file
2. Write the data to a file
3. Append the data to a file

Reading from Text Files


Python provides three types of read functions to read from a data file.
 Filehandle.read([n]) : reads and return n bytes, if n is not specified it reads entire file.
 Filehandle.readline([n]) : reads a line of input. If n is specified reads at most n bytes. Read
bytes in the form of string ending with line character or blank string if no more bytes are
left for reading.
 Filehandle.readlines(): reads all lines and returns them in a list
Examples:
Let a text file “Book.txt” has the following text:

“Python is interactive language. It is case sensitive language.


It makes the difference between uppercase and lowercase letters. It is official language of
google.”

Example-1:Programusingread()function: OUTPUT:
fin=open("D:\\pythonprograms\\Boo Python is interactive language. It is case
k.txt",'r') sensitive language.
It makes the difference between uppercase
63
str=fin.read( ) and

64
print(st lowercase letters. It is official language of
r) google.
fin.clos
e()
Example-2:Programusingread()function: OUTPUT:
fin=open("D:\\python programs\\
Python is
Book.txt",'r') str=fin.read(10)
print(str)
fin.close()

Example-3:usingreadline()function: OUTPUT:

fin=open("D:\\python programs\\ Python is interactive language. It is case


Book.txt",'r') str=fin.readline( ) sensitive language.
print(str) fin.close( )
Example-4:usingreadlines()function: OUTPUT:

fin=open("D:\\python programs\\ ['Python is interactive language. It is case


Book.txt",'r') str=fin.readline( ) sensitive language.\n', 'It makes the
print(str) difference between uppercase and lowercase
fin.close( ) letters.\n', 'It is official language of google.']

Writing onto Text Files:


Like reading functions , the writing functions also work on open files.
 <filehandle>.write(str1): Wrties string str1 to file referenced by <file handle>.
 <filehandle>.writelines(L): Wrties all strings in list L as lines to file referenced by
<file handle>.

Myfile

m Peter.
w are you?

Example-1:Program using write()function: OUTPUT:


My name is Aarav.
f=open(r’MyFile.txt’,’w’)
data = ‘My name is
Aarav.’ f.write(data)
f.close( )

65
f=open(r’MyFile.txt’,’r’)
data = f.read( )

66
print(da
ta)
f.close(
)
Example-2:Program using OUTPUT:
writelines()function: #It will append the content.
f=open(r’Myfile.txt’,’a’)
data=[‘I have a dog., ‘\nI love my cat.’]
f.writelines(da My name is Aarav.I have a
ta) f.close( ) dog. I love my cat.
f=open(r’Myfile.txt’,’r’)
data = f.read( )
print(da
ta)
f.close( )

flush( ) function:
● When we write any data to file, python hold everything in buffer (temporary
memory) and pushes it onto actual file later. If you want to force Python to write the
content of buffer onto storage, you can use flush() function.
● Python automatically flushes the files when closing them i.e. it will be implicitly
called by the close(), but if you want to flush before closing any file you can use flush()
seek( ) function:
The seek( ) function allows us to change the position of the file pointer in the
opened file as follows:
f.seek(offset,mode)
where
offset - is a number specifying number of bytes.
mode - specifies the reference point from where the offset will be calculated to
place the file pointer. The mode argument is optional and has three possible values namely
0, 1 and 2. The default value of mode is 0.
0 - beginning of file
1 - current position in file
2 - end of file
tell( ) function:
The tell() method returns the current position of the file pointer in the opened file. It is used as
follows:
f.tell()
67
Example-1: tell()function: OUTPUT:
Example: 14
fout=open("story.txt","w")
fout.write("Welcome Python")
print(fout.tell( ))
fout.close( )

CSV Files
The CSV (Comma Separated Values) is a special text file format in which rows of data are present
and the individual data elements are separated by commas. The CSV format is the most common
import and export format for spreadsheets and databases. The csv files have the extension .csv
Example for data contained in csv file

Raghu,23,100
Tisha,45,230
Yatin,67,90

68
Advantages of csv files:
● CSV is human readable and easy to edit manually.
● CSV is simple to implement and parse.
● CSV is processed by almost all existing applications.
● CSV is smaller in size
● CSV is considered to be standard format
● CSV is compact. For XML you start tag and end tag for each column in each row. In CSV
you write the column headers only once.
● CSV can handle large unstructured data generated by social media effectively

Examples of some valid formats of CSV files are:

1. Each record is located on a separate line, delimited by a line break (CRLF). For example:
One,two,three CRLF four,five,six CRLF
2. The last record in the file may or may not have an ending line break. For example:
One,two,three CRLF four,five,six
3. There maybe an optional header line appearing as the first line of the file with the same
format as normal record lines. For example:
Name,Rollno,Marks CRLF  Header line Raghu,1011,56 CRLF
Swara,1012,78 CRLF
4. Each field may or may not be enclosed in double quotes. If fields are not enclosed with
double quotes, then double quotes may not appear inside the fields. For example:
"one","two","three" CRLF Eight,nine,ten

[Note:
1. CR stands for the character 'Carriage Return' with Integer ASCII code - 13
and C++/Python notation \r or '\r'.
2. LF stands for the character 'Line Feed' with Integer ASCII code - 10 and
C++/Python notation \n or '\n'.

69
3. In Windows platform the Enter Key / End of Line(EOL) / newline character is
represented by the character combination CRLF i.e. '\r\n' in python.
4. In Unix/Linux platforms the Enter Key /End of Line (EOL) / newline character
is represented by the character LF only i.e. '\n' in python.
5. In Macintosh platforms the Enter Key / End of Line (EOL) / newline character
is represented by the character CR only i.e. '\r' in python.
6. When opening a file for reading CSV file add the parameter, newline='EOL_character' to
process the End of Line correctly.
While opening a CSV file for reading on Windows platform, add the parameter, newline='\r\n'
in the open() method to avoid adding an extra blank line while processing/displaying output on
the screen ]
In CSV files there can be delimiters other than comma(,)
Tab separated values

Raghu 23 100
Tisha 45 230
Yatin 67 90

Semicolon separated values


Raghu ;23;100
Tisha;45;230
Yatin;67;90

Using CSV module to handle csv files


What is csv module?
The csv module implements classes to read and write tabular data in CSV format. The csv module
handles the different types of delimiters and quoting characters in CSV files and efficiently
manipulate such data, hiding the details of reading and writing the data from the programmer.
The module has to be imported in python program to handle csv files.

import csv as c
or
import csv
READING FROM A CSV FILE-READER OBJECT
Reading from a csv file is done using a reader object. The CSV file is opened as a text
file with Python’s built-in open() function, which returns a file object. This creates a
special type of object to access the CSV file (reader object), using the reader()
70
function.

71
The reader object is an iterable that gives us access to each line of the CSV file as a
list of fields. You can also use next() directly on it to read the next line of the CSV file,
or you can treat it like a list in a for loop to read all the lines of the file (as lists of the
file’s fields).
Syntax:
csv.reader(fileobject,delimiter=“ “)-> it returns a reader object

PROGRAM TO READ AND DISPLAY CONTENTS OF CSV FILE


#reading and displaying contents from a csv file

import csv as c
with open(‘12ACS.csv’,"r") as mycsv:
csvreader=c.reader(mycsv,delimiter=",")
for row in csvreader:
print (row)
CREATING A CSV FILE THROUGH A PYTHON PROGRAM FOR WRITING DATA
To write to a CSV file in Python, we can use the csv.writer() function. The
csv.writer() function returns a writer object that converts the user's data into a
delimited string.
This string can later be used to write into CSV files using the writerow() function.
In order to write to a CSV file, we create a special type of object to write to the CSV
file "writer object", which is defined in the CSV module, and which we create using
the writer() function.
The writerow() method allows us to write a list of fields to the file. The fields
can be strings or numbers or both. Also, while using writerow(), you do not need to
add a new line character (or other EOL indicator) to indicate the end of the line,
writerow() does it for you as necessary.

PROGRAM TO CREATE A CSV FILE AND WRITE DATA IN IT


def createcsv():
f=open("cricket.csv","w",newline='')
s=csv.writer(f,delimiter="-")
s.writerow(["playername","runsscored","Matchsplayed"])
while True:
c=eval(input("Enter the name ,runs,
matches")) s.writerow(c)
ch=input("Do you want to continue
(Y/N)") if ch.upper()!="Y":
break
f.close()

writerow() Vs writerows()
writerow() is used to write a single row to a csv file.
72
writerows() is used to write multiple rows/lines to csv file
To demonstrate writerow() and writerows()

import csv
f=open("one.csv","w",newline='')
csvwriter=csv.writer(f,delimiter=',')
csvwriter.writerow(['one','two','three'])
l=[(23,45,67),(34,56,78),(45,67,78)]
csvwriter.writerows(l)
f.close()
OUTPUT:
one,two,three
23,45,67
34,56,78
45,67,78

Data structures - Stacks

❖ Introduction to Python data structure stack


❖ Implementation of stack using List

❖ Push function

❖ Pop Function

❖ Display function

❖ Checking stack underflow

Introduction to Python data structure-Stack

A data structure is a way of store, organize, or manage data in efficient and productive manner.

The python data structure stack is a linear data structure. It follows the principle of LIFO (Last In
First Out). The representation of data is something like this:

73
By observing the above image you can understand the following:

1. The data can be inserted or deleted from the top only


2. Elements can be inserted or deleted any time
3. The insert operation is known as push
4. The delete operation is known as pop
5. When the top element is inspected, it is known as a peek or inspection
6. When we have a fixed-length list and we are trying to push an element in a list, it raises one
error that is known as overflow
7. When the list is empty and we are trying to pop an element, it will raise an error that
is known as underflow

Push function
A function to push an element. To push the element append() method is used as well as the
position of the top should be changed. Observe the following code:

def push(stk,e):
stk.append(e)

Pop Function
The pop function requires validation to check whether the stack is underflow or not if it is not then
use the logic to delete the element from the top. Have a look at this code:

def pop_stack(stk):
if stk==[]:
return "UnderFlow"
else:
e = stk.pop()
return e
Display function
Write a function to check the element is inserted or not, observe this code:

def
display(stk):
if stk==[]:
print("Stack Underflow") 74
else:
for i in (stk[::-
1]): print(i)
Applications of the stack:
• Infix to Postfix /Prefix conversion
• Redo-undo features at many places like editors, photoshop.
• Forward and backward features in web browsers
• Used in many algorithms like Tower of Hanoi, tree traversals, stock span problems, and
histogram problems.
• String reversal is also another application of stack. Here one by one each character gets
inserted into the stack. So the first character of the string is on the bottom of the stack and
the last element of a string is on the top of the stack. After performing the pop operations
on the stack we get a string in reverse order.

75
76

You might also like