Unit - I
Unit - I
Section A
Computational Thinking & Programming – 2
Python
It is a widely used general purpose, high level programming language. Developed by Guido
van Rossum in 1991. It is used for: software development, web development (server-side),
system scripting, Mathematics.
Features of Python
1. Easy to use – Due to simple syntax rule
2. Interpreted language – Code execution & interpretation line by line
3. Cross-platform language – It can run on Windows, Linux, Macintosh etc. equally
4. Expressive language – Less code to be written as it itself express the purpose of the
code.
5. Completeness – Support wide range of library
6. Free & Open Source – Can be downloaded freely and source code can be modify for
improvement
Shortcomings of Python
1. Lesser libraries – as compared to other programming languages like C++, Java,.net
2. Slow language – as it is interpreted languages, it executes the program slowly.
3. Weak on Type-binding – It not pin point on use of a single variable for different data
type.
Data Handling
Most of the computer programming language support data type, variables,operator and
expression
like fundamentals. Python also support these.
Data Types: Data Type specifies which type of value a variable can store. The type( )
function is used to determine a variable's type in Python.
e.g.:
>>> x = 2
>>> type(x)
<class ‘int’>
Datatypes in Python
1. Number: It is used to store numeric values Python has three numeric types:
i. Integers: Integers or int are positive or negative numbers with no decimal point.
Integers in Python 3 are of unlimited size.
e.g.:
>>> a = 10
>>> b = 22 * 2
>>> print(a)
10
>>> print(b)
44
Type Conversion of Integer: The int( ) function converts any data type to integer.
e.g.
>>>a = "101" # This is a string. Since it is enclosed with inverted commas.
>>>b = int(a) # It converts string data type to integer.
>>>c = int(122.4) # It converts float data type to integer.
>>>print(b)
101
>>>print(c)
122
ii. Floating point numbers: It is a positive or negative real number with a decimal
point.
e.g.
>>>a = 101.2
>>>b = -101.4
>>>print(a)
101.2
>>>print(b)
-101.4
Type Conversion of Floating point numbers: The float( ) function converts any
data type to floating point number.
e.g.
>>>a = '301.4' #This is a string
>>>print(a)
‘301.4’
>>>b = float(a) #converts string data type to floating point number.
>>>print(b)
301.4
iii. Complex numbers: Complex numbers are combination of a real and imaginary
part. Complex numbers are in the form of X+Yj, where X is a real part and Y is
imaginary part.
e.g.
>>>a = complex(5) # convert 5 to a real part value and zero imaginary part
>>>print(a)
(5+0j)
>>>b=complex(101,23) #convert 101 with real part and 23 as imaginary part
>>>print(b)
(101+23j)
4. List: Lists are used to store multiple items in a single variable. Lists are created using
square brackets. E.g.:
>>>thislist = ["apple", "banana", "cherry"]
List items are ordered, changeable, and allow duplicate values. List items are
indexed, the first item has index [0], the second item has index [1] and so on.
When we say that lists are ordered, it means that the items have a defined order, and
that order will not change. If you add new items to a list, the new items will be placed
at the end of the list.
The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Since lists are indexed, lists can have items with the same value.
e.g.:
>>>lst = [5,99]
>>>print(lst)
[5,99]
>>>lst[0] = 34
>>>print(lst)
[34,99]
5. Tuple: List and tuple, both are same except ,a list is mutable python objects and tuple
is immutable Python objects. Immutable Python objects mean you cannot modify the
contents of a tuple once it is assigned. In order to change the values we have to
redefine the Tple.
e.g.
>>>tup = (66,99)
>>>tup[0] = 3 # error message will be displayed since tuple is unchangable
>>>print(tup[0])
66
>>>print(tup[1])
99
7. Dictionary: It is an unordered collection of items and each item consist of a key and
a value.
e.g.
>>>dict = {'Subject': 'Comp Sc', 'class': 12}
>>>print(dict)
{'sub': 'Comp Sc', 'class': 12}
Operators
Operators (symbols/keywords) are used to perform arithmetic/logical operations on
variables and values. Python divides the operators in the following groups:
Arithmetic operators: Arithmetic operators are used with numeric values to perform
common mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Identity operators: Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same memory location.
Operator Description Example
is Returns True if both variables are the same object x is y
Returns True if both variables are not the same
is not x is not y
object
Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion. Python has two types of type conversion: Implicit Type
Conversion & Explicit Type Conversion.
OUTPUT
('datatype of num_int:', <type 'int'>)
('datatype of num_flo:', <type 'float'>)
('Value of num_new:', 22.23)
('datatype of num_new:', <type 'float'>)
Explicit Type Conversion: In Explicit Type Conversion, users convert the data type
of an object to required data type. We use the predefined functions like
int(),float(),str() etc. e.g.
num_int = 12
num_str = "45"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
OUTPUT
('Data type of num_int:', <type 'int'>)
('Data type of num_str before Type Casting:', <type 'str'>)
('Data type of num_str after Type Casting:', <type 'int'>)
Python math Module
Python has a built-in module that you can use for mathematical tasks.
Math Methods
Method Description
math.acos() Returns the arc cosine of a number
math.acosh() Returns the inverse hyperbolic cosine of a number
math.asin() Returns the arc sine of a number
math.asinh() Returns the inverse hyperbolic sine of a number
math.atan() Returns the arc tangent of a number in radians
math.atan2() Returns the arc tangent of y/x in radians
math.atanh() Returns the inverse hyperbolic tangent of a number
math.ceil() Rounds a number up to the nearest integer
Returns the number of ways to choose k items from n items without
math.comb()
repetition and order
math.cos() Returns the cosine of a number
math.cosh() Returns the hyperbolic cosine of a number
math.degrees() Converts an angle from radians to degrees
Returns the Euclidean distance between two points (p and q), where p
math.dist()
and q are the coordinates of that point
math.erf() Returns the error function of a number
math.erfc() Returns the complementary error function of a number
math.exp() Returns E raised to the power of x
math.expm1() Returns Ex - 1
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.fmod() Returns the remainder of x/y
math.frexp() Returns the mantissa and the exponent, of a specified number
math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
math.gamma() Returns the gamma function at x
math.gcd() Returns the greatest common divisor of two integers
math.hypot() Returns the Euclidean norm
math.isclose() Checks whether two values are close to each other, or not
math.isfinite() Checks whether a number is finite or not
math.isinf() Checks whether a number is infinite or not
math.isnan() Checks whether a value is NaN (not a number) or not
math.isqrt() Rounds a square root number downwards to the nearest integer
Returns the inverse of math.frexp() which is x * (2**i) of the given
math.ldexp()
numbers x and i
math.lgamma() Returns the log gamma value of x
Returns the natural logarithm of a number, or the logarithm of number to
math.log()
base
math.log10() Returns the base-10 logarithm of x
math.log1p() Returns the natural logarithm of 1+x
math.log2() Returns the base-2 logarithm of x
Returns the number of ways to choose k items from n items with order
math.perm()
and without repetition
math.pow() Returns the value of x to the power of y
math.prod() Returns the product of all the elements in an iterable
math.radians() Converts a degree value into radians
Returns the closest value that can make numerator completely divisible
math.remainder()
by the denominator
math.sin() Returns the sine of a number
math.sinh() Returns the hyperbolic sine of a number
math.sqrt() Returns the square root of a number
math.tan() Returns the tangent of a number
math.tanh() Returns the hyperbolic tangent of a number
math.trunc() Returns the truncated integer parts of a number
Control Statements
Control statements are used to control the flow of execution depending upon the specified
condition/logic. There are three types of control statements: Decision Making Statements,
Iteration Statements (Loops) & Jump Statements (break, continue, pass).
i. Decision making statements: used to control the flow of execution of a program
depending upon condition. There are three types of decision making statements.
a) if statements: An if statement is a programming conditional statement that, if
proved true, performs a function or displays information.
Syntax:
if(condition):
[statements]
b) if-else statements: This statement executes some code if the test expression is
true (nonzero) and some other code if the test expression is false.
Syntax:
if(condition):
statements
else:
statements
c) Nested if-else statement: The nested if...else statement allows you to check for
multiple test expressions and execute different codes for more than two
conditions.
Syntax
if (condition):
statements
elif (condition):
statements
else:
statements
ii. Iteration statements(loop): used to execute a block of statements as long as the
condition is true. Loops statements are used when we need to run the same code again
and again. Python Iteration (Loops) statements are of three type :-
a) While Loop: It is used to execute a block of statement as long as a given
condition is true. And when the condition becomes false, the control will come
out of the loop. The condition is checked every time at the beginning of the loop.
Syntax:
while (condition):
statement/[statements]
b) For Loop: It is used to iterate over items of any sequence, such as a list or a
string.
Syntax:
for val in sequence:
statements
iii. Jump Statements (break, continue, pass): Jump statements are used to transfer the
program's control from one location to another. Means these are used to alter the flow
of a loop like – to skip a part of a loop or terminate a loop There are three types of
python.
a) break
b) continue
c) pass
Function
A function is a programming block of codes which is used to perform a single, related task.
It only runs when it is called. We can pass data, known as parameters, into a function. A
function can return data as a result.
We have already used some python built-in functions like print(),etc. But we can also create
our own functions. These functions are called user-defined functions.
a = 12
b = 10
print(my_function(a,b)) # a, b are called actual parameters. Holds the actual value
that is sent to my_function and processed.
OTPUT: Using a function is called Function call/invoke
22
Variable’s Scope in function
There are three types of variables with the view of scope.
1. Local variable – accessible only inside the functional block where it is declared.
2. Global variable – variable which is accessible among the whole program using global
keyword.
3. Non local variable – accessible in nesting of functions,using nonlocal keywords.
Output:
I love India!
I love World!
Output:
I love world!
I love India!
I love India!
x=50
fun1()
print("x in main: " + str(x))
OUTPUT:
Before calling fun2: 100
Calling fun2 now:
After calling fun2: 200
x in main: 50
x,y = 4,5
r = sum(x,y) #x, y are actual arguments
print(r)
Note :-
1. Function Prototype is a declaration of function with name ,argument and return type.
2. A formal parameter, i.e. a parameter, is in the function definition. An actual
parameter, i.e. an argument, is in a function call.
Function Arguments
Functions can be called using following types of formal arguments −
• Required arguments - arguments passed to a function in correct positional order
• Keyword arguments - the caller identifies the arguments by the parameter name
• Default arguments - that assumes a default value if a value is not provided to arguments.
• Variable-length arguments – pass multiple values with a single argument name.
#Required arguments
def square(x):
z=x*x
return z
r=square()
print(r)
#In above function square() we have to definitely need to pass some value to argument x.
#Keyword arguments
def fun( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;
# value 15 and mohak is being passed to relevant arguments based on keywords used for
them.
#Default arguments
def sum(x=3,y=4):
z=x+y
return z
r=sum()
print(r)
r=sum(x=4)
print(r)
r=sum(y=45)
print(r)
#default value of x and y is being used when it is not passed
#Pass by reference
def updateList(list1):
print(id(list1))
list1 += [10]
print(id(list1))
n = [50, 60]
print(id(n))
updateList(n)
print(n)
print(id(n))
OUTPUT
34122928
34122928
34122928
[50, 60, 10]
34122928
#In above function list1 an object is being passed and its contents are changing because it is
mutable that’s why it is behaving like pass by reference
#Pass by value
def updateNumber(n):
print(id(n))
n += 10
print(id(n))
b=5
print(id(b))
updateNumber(b)
print(b)
print(id(b))
OUTPUT
1691040064
1691040064
1691040224
5
1691040064
#In above function value of variable b is not being changed because it is immutable that’s
why it is behaving like pass by value.
UNIT – I
Section B
Computational Thinking & Programming – 2
File Handling
A file is a sequence of bytes on the disk/permanent storage where a group of related data is
stored. File is created for permanent storage of data.
In programming, Sometimes, it is not enough to only display the data on the console. Those
data are to be retrieved later on, then the concept of file handling comes. It is impossible to
recover the programmatically generated data again and again. However, if we need to do so,
we may store it onto the file system which is not volatile and can be accessed every time.
Here, comes the need of file handling in Python.
File handling in Python enables us to create, update, read, and delete the files stored on the
file system through our python program. The following operations can be performed on a
file. In Python, File Handling consists of following three steps:
Open the file
Process file
Close the file
Types of File
There are two types of files:
Text Files- A file whose contents can be viewed using a text editor is called a text
file. A text file is simply a sequence of ASCII or Unicode characters. Python
programs, contents written in text editors are some of the example of text files.
Binary Files- A binary file stores the data in the same way as stored 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.
E.g. :
f = open(“MyFile.txt”, “w”)
OUTPUT
False
Name of the file is a.txt
True
OUTPUT
Welcome to LFS
Regularly visit LFS
Another way to read a file is to call a certain number of characters like in the following
code the interpreter will read the first five characters of stored data and return it as a
string:
# Python code to illustrate read() mode character wise
file = open("myFile.txt", "r")
print (file.read(5))
OUTPUT
Welcome to LFS
Regularly visit LFS
OUTPUT
Welcome
to
LFS
Regularly
visit
LFS
The OS module in Python provides functions for creating and removing a directory
(folder), fetching its contents, changing and identifying the current directory, etc.
Parameters:-
Offset: Number of positions to move forward
from_what: It defines point of reference.
Returns: Return the new absolute position.
# Second parameter is by default 0, sets Reference point to twentieth, index position from
the beginning
f.seek(20)
print(f.readline())
f.close()