Python Unit 1
Python Unit 1
com 1
GUJARAT TECHNOLOGICAL UNIVERSITY
MASTER OF COMPUTER APPLICATIONS (MCA)
SEMESTER: III
BipinRupadiya.com 2
Unit-1
Introduction to Python: Structured Types, Mutability and
The basic elements of Python, Higher-order Functions:
Objects, expressions and numerical Tuples,
Types, Lists and Mutability,
Variables and assignments, Functions as Objects,
IDLE, Strings,
Branching programs, Tuples and Lists,
Strings and Input, Dictionaries
Iteration
BipinRupadiya.com 3
Introduction
Python is an interpreted, high-level,
general-purpose programming language.
Created by Guido van Rossum and first
released in 1991,
Python's design philosophy emphasizes
code readability with its notable use of Guido van Rossum
significant whitespace.
Its language constructs and object-oriented approach aim to help programmers write
clear, logical code for small and large-scale projects.
Python is dynamically typed and garbage-collected.
It supports multiple programming paradigms, including procedural, object-oriented,
and functional programming.
Python is often described as a "batteries included" language due to its comprehensive
standard library.
BipinRupadiya.com 4
Python
Chapter-2
The basic elements of Python, Objects,
expressions and numerical Types, Variables and assignments,
IDLE, Branching programs, Strings and Input, Iteration
BipinRupadiya.com
The Basic Elements of Python
A Python program, sometimes called a script, is a sequence
of definitions and commands.
These definitions are evaluated and the commands are
executed by the Python interpreter in something called the
shell.
Typically, a new shell is created whenever execution of a
program begins.
In most cases, a window is associated with the shell
BipinRupadiya.com
The Basic Elements of Python
A command, often called a statement, instructs the interpreter to do
something.
For example, the statement print ‘Hello Word' instructs the interpreter to
output the string Hello Word to the window associated with the shell.
See the command written below:
>>> print(‘Hello World’)
The symbol >>> is a shell prompt indicating that the interpreter is
expecting the user to type some Python code into the shell
BipinRupadiya.com
Objects
BipinRupadiya.com
Numerical Types
Python has four types (Numerical types)of scalar objects:
1. int is used to represent integers
2. float is used to represent real numbers. Literals of type float always include a
decimal point (e.g., 3.0 or 3.17 or -28.72).
3. bool is used to represent the Boolean values True and False.
4. None is a type with a single value.
BipinRupadiya.com
Expressions
Objects and operators can be
combined to form expressions,
each of which evaluates to an
object of some type.
BipinRupadiya.com
Operator on Types int and float
i+j is the sum of i and j.
If i and j are both of type int, the result is an int. If either of them is a float, the result is a float.
i–j is i minus j.
If i and j are both of type int, the result is an int. If either of them is a float, the result is a float.
i/j is i divided by j.
In Python 2.7, when i and j are both of type int, the result is also an int, otherwise the result is a float.
In Python 3, the / operator, always returns a float. For example, in Python 3 the value of 6/4 is 1.5.
BipinRupadiya.com
Numerical Types
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6
BipinRupadiya.com
Numerical Types
>> 17 / 3 # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
BipinRupadiya.com
Variables and Assignment
Variables provide a way to associate names with objects.
Consider the code
pi = 3
radius = 11
area = pi * (radius**2)
radius = 14
BipinRupadiya.com
Variables and Assignment
BipinRupadiya.com
IDLE
BipinRupadiya.com
Branching Programs
The simplest branching statement is a conditional.
A conditional statement has three parts:
A test, i.e., an expression that evaluates to either True or False;
A block of code that is executed if the test evaluates to True;
An optional block of code that is executed if the test evaluates to
False
BipinRupadiya.com
2.2 Branching Programs
Syntax
if Boolean expression:
block of code
else:
block of code
Example
if x%2 == 0:
print ('Even' )
else:
print ('Odd‘)
BipinRupadiya.com
Branching Programs
Indentation is semantically meaningful in Python.
Python programs get structured through indentation.
BipinRupadiya.com
Strings and Input
Objects of type str are used to represent strings of characters.
Literals of type str can be written using either single or double quotes,
e.g., 'abc' or "abc".
BipinRupadiya.com
Strings and Input
type checking exists is a good thing.
It turns careless (and sometimes subtle) mistakes into errors that
stop execution, rather than errors that lead programs to behave in
mysterious ways.
BipinRupadiya.com
Strings and Input
The length of a string can be found using the len function.
BipinRupadiya.com
Strings and Input
Indexing can be used to extract individual characters from a string.
In Python, all indexing is zero-based.
BipinRupadiya.com
Strings and Input
Slicing is used to extract substrings of arbitrary length. If s is a string, the
expression s[start:end] denotes the substring of s that starts at index start and ends
at index end-1.
BipinRupadiya.com
Input
Python 2.7 has two functions (see Chapter 4 for a discussion of functions in Python)
that can be used to get input directly from a user, input and raw_input.
but in python 3.7.0 method raw_input() does not work.
BipinRupadiya.com
Iteration
A generic iteration (also called looping) mechanism is depicted in Figure 2.4.
Like a conditional statement it begins with it begins with a test.
If the test evaluates to True, program executes the loop body once, and then goes
back to reevaluate the test.
This process is repeated until the test evaluates to False, after which control passes to
the code following the iteration statement
BipinRupadiya.com
Iteration
BipinRupadiya.com
Python
Chapter-5
• Tuples, Lists and Mutability,
• Functions as Objects,
• Strings,
• Tuples and Lists,
• Dictionaries
BipinRupadiya.com
Tuples
Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
Like strings, tuples are ordered sequences of elements.
The difference is that the elements of a tuple need not be characters.
The individual elements can be of any type, and need not be of the same type
as each other.
BipinRupadiya.com
Tuples
Like strings, tuples can be concatenated, indexed, and sliced.
BipinRupadiya.com
Lists and Mutability
List is a collection which is ordered and changeable. Allows duplicate
members.
Like a tuple, a list is an ordered sequence of values, where each
value is identified by an index.
The syntax for expressing literals of type list is similar to that used
for tuples;
The difference is that we use square brackets rather than
parentheses.
The empty list is written as [],
BipinRupadiya.com
Lists and Mutability
BipinRupadiya.com
Lists and Mutability
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
BipinRupadiya.com
Lists and Mutability
Lists differ from tuples in one hugely important way:
lists are mutable.
In contrast, tuples and strings are immutable.
This means we can change an item in a list by accessing it
directly as part of the assignment statement.
Using the indexing operator (square brackets) on the left
side of an assignment, we can update one of the list items.
BipinRupadiya.com
Lists and Mutability
BipinRupadiya.com
Cloning
Though it is allowed, but it is sensible to avoid mutating a list over which one is
iterating.
Consider, for example, the code…
Example:
Assumes that L1 and L2 are lists. Remove any element from L1 that also occurs in L2
BipinRupadiya.com
Cloning
You might be surprised to discover that the print statement produces the output
L1 = [2, 3, 4]
During a for loop, the implementation of Python keeps track of where it is in the list
using an internal counter that is incremented at the end of each iteration.
When the value of the counter reaches the current length of the list, the loop
terminates.
This works as one might expect if the list is not mutated within the loop, but can have
surprising consequences if the list is mutated.
In this case, the hidden counter starts out at 0, discovers that L1[0] is in L2, and
removes
it—reducing the length of L1 to 3.
The counter is then incremented to 1, and the code proceeds to check if the value of
L1[1] is in L2.
Notice that this is not the original value of L1[1] (i.e., 2), but rather the current value
of L1[1] (i.e., 3).
As you can see, it is possible to figure out what happens when the list is modified
within the loop.
BipinRupadiya.com
Cloning
One way to avoid this kind of problem is to use slicing to clone (i.e.,
make a copy of) the list and write for e1 in L1[:].
BipinRupadiya.com
List Comprehension
List comprehension provides a concise way to apply an operation
to the values in a sequence.
It creates a new list in which each element is the result of applying a
given operation to a value from a sequence.
BipinRupadiya.com
Functions as Objects
A function is the simplest callable object in Python
In Python, functions are first-class objects.
That means that they can be treated like objects of any other
type,
e.g., int or list.
Using functions as arguments can be particularly convenient in
conjunction with lists.
It allows a style of coding called higher-order programming.
BipinRupadiya.com
Example: Functions as Objects
BipinRupadiya.com
map()
Python has a built-in higher-order function, map, that is similar to
function as object, but more general than it.
map() function returns a list of the results after applying the given function
to each item of a given iterable (list, tuple etc.)
Syntax :
(fun , iter)
fun:
It is a function to which map passes each element of given iterable.
iter :
It is a iterable values which is to be mapped.
BipinRupadiya.com
Example: map()
Output:
[2, 4, 6, 8]
[1, 4, 9, 16]
BipinRupadiya.com
Functions as Objects
BipinRupadiya.com
Common operations on sequence types
We have looked at three different sequence types: str, tuple, and list
They are similar in that objects of all of these types can be operated upon
as described here
BipinRupadiya.com
Comparison of sequence type
BipinRupadiya.com
Some methods on string
BipinRupadiya.com
Dictionaries
BipinRupadiya.com 49
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.
BipinRupadiya.com
dict() Constructor
The dict() constructor to make a dictionary.
BipinRupadiya.com
Adding Items to Dictionaries
Adding an item to the dictionary is done by using a new index
key and assigning a value to it:
BipinRupadiya.com
Update Item in Dictionaries
BipinRupadiya.com
Removing Item from Dictionaries
Removing a dictionary item use the del() function
BipinRupadiya.com
Length of a Dictionary
The len() function returns the size of the dictionary
BipinRupadiya.com
Loop Through a Dictionary
BipinRupadiya.com 56
Built-in methods of dictionaries
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing the a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key.
If the key does not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
BipinRupadiya.com 57
clear()
BipinRupadiya.com
copy()
BipinRupadiya.com
copy() using equal operator
BipinRupadiya.com
fromkeys(seq[,v])
BipinRupadiya.com
fromkeys(seq[,v])
BipinRupadiya.com
fromkeys(seq[,v])
BipinRupadiya.com
get()
BipinRupadiya.com
Bipin S. Rupadiya
(MCA, PGDCA, BCA)
Assistant Professor,
JVIMS-MCA (537), Jamnagar
www.BipinRupadiya.com
BipinRupadiya.com 65