SlideShare a Scribd company logo
BipinRupadiya.com 1
BipinRupadiya.com
GUJARAT TECHNOLOGICAL UNIVERSITY
MASTER OF COMPUTER APPLICATIONS (MCA)
SEMESTER: III
Subject Name: Programming in Python
Subject Code : 4639304
2
BipinRupadiya.com
Unit-1
 Introduction to Python:
 The basic elements of Python,
 Objects, expressions and numerical
Types,
 Variables and assignments,
 IDLE,
 Branching programs,
 Strings and Input,
 Iteration
 Structured Types, Mutability and
Higher-order Functions:
 Tuples,
 Lists and Mutability,
 Functions as Objects,
 Strings,
 Tuples and Lists,
 Dictionaries
3
BipinRupadiya.com
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
significant whitespace.
4
 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.
Guido van Rossum
BipinRupadiya.com
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
 Objects are the core things that Python programs manipulate
 Every object has a type that defines the kinds of things that programs
can do with objects of that type.
 Types are either scalar or non-scalar.
 Scalar objects are indivisible. Think of them as the atoms of the
language.
 Non-scalar objects, for example strings, have internal structure.
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 the product 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 integer division.
 For example, the value of 6//2 is the int 3 and the value of 6//4 is the int 1.
 The value is 1 because integer division returns the quotient and ignores the remainder.
 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.
 i%j is the remainder when the int i is divided by the int j.
 It is typically pronounced “i mod j,” which is short for “i modulo j.”
 i**j is i raised to the power 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.
 The comparison operators are == (equal), != (not equal), > (greater), >= (at least), <, (less) and
<= (at most).
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
• It first binds the names pi and radius to different objects of
type int.
• It then binds the name area to a third object of type int.
• An assignment statement associates the name to the left of
the = symbol with the object denoted by the expression to
the right of the =
• Python allows multiple assignment.
• The statement x, y = 2, 3
• Example of two variable exchanging code:
BipinRupadiya.com
IDLE
 Typing programs directly into the shell is highly inconvenient.
 Most programmers prefer to use some sort of text editor that is part of an
integrated development environment (IDE).
 we will use IDLE, the IDE that comes as part of the standard Python installation
package.
 IDLE is an application, just like any other application on your computer.
 Start it the same way you would start any other application, e.g., by double-
clicking on an icon.
 IDLE (Integrated Development Environment) provides
 a text editor with syntax highlighting, autocompletion, and smart
indentation,
 a shell with syntax highlighting, and
 an integrated debugger
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‘)
print ('Done with conditional‘)
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
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
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()
[2, 4, 6, 8]
[1, 4, 9, 16]
Output:
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
49
BipinRupadiya.com
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
56
BipinRupadiya.com
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
57
BipinRupadiya.com
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
65

More Related Content

Similar to Python_Unit_1.pdf (20)

PPTX
Lecture1_introduction to python.pptx
MohammedAlYemeni1
 
PPT
Spsl iv unit final
Sasidhar Kothuru
 
PPT
Spsl iv unit final
Sasidhar Kothuru
 
DOCX
A Introduction Book of python For Beginners.docx
kumarrabinderkumar77
 
PPTX
Chapter1 python introduction syntax general
ssuser77162c
 
PPTX
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa Thapa
 
PPTX
Introduction to Python Programming
VijaySharma802
 
PDF
Python: An introduction A summer workshop
ForrayFerenc
 
PPTX
Introduction to Python for Data Science and Machine Learning
ParrotAI
 
PPT
python fundamental for beginner course .ppt
samuelmegerssa1
 
PDF
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
PPTX
Python knowledge ,......................
sabith777a
 
PPTX
Python programing
hamzagame
 
PDF
Introduction To Programming with Python
Sushant Mane
 
PPTX
Python Demo.pptx
ParveenShaik21
 
PPTX
Dr.C S Prasanth-Physics ppt.pptx computer
kavitamittal18
 
PPTX
Python Demo.pptx
ParveenShaik21
 
PPTX
1664611760basics-of-python-for begainer1 (3).pptx
krsonupandey92
 
PPTX
Python For Data Science.pptx
rohithprabhas1
 
PPTX
Keep it Stupidly Simple Introduce Python
SushJalai
 
Lecture1_introduction to python.pptx
MohammedAlYemeni1
 
Spsl iv unit final
Sasidhar Kothuru
 
Spsl iv unit final
Sasidhar Kothuru
 
A Introduction Book of python For Beginners.docx
kumarrabinderkumar77
 
Chapter1 python introduction syntax general
ssuser77162c
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa Thapa
 
Introduction to Python Programming
VijaySharma802
 
Python: An introduction A summer workshop
ForrayFerenc
 
Introduction to Python for Data Science and Machine Learning
ParrotAI
 
python fundamental for beginner course .ppt
samuelmegerssa1
 
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
Python knowledge ,......................
sabith777a
 
Python programing
hamzagame
 
Introduction To Programming with Python
Sushant Mane
 
Python Demo.pptx
ParveenShaik21
 
Dr.C S Prasanth-Physics ppt.pptx computer
kavitamittal18
 
Python Demo.pptx
ParveenShaik21
 
1664611760basics-of-python-for begainer1 (3).pptx
krsonupandey92
 
Python For Data Science.pptx
rohithprabhas1
 
Keep it Stupidly Simple Introduce Python
SushJalai
 

Recently uploaded (20)

PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Ad

Python_Unit_1.pdf

  • 2. BipinRupadiya.com GUJARAT TECHNOLOGICAL UNIVERSITY MASTER OF COMPUTER APPLICATIONS (MCA) SEMESTER: III Subject Name: Programming in Python Subject Code : 4639304 2
  • 3. BipinRupadiya.com Unit-1  Introduction to Python:  The basic elements of Python,  Objects, expressions and numerical Types,  Variables and assignments,  IDLE,  Branching programs,  Strings and Input,  Iteration  Structured Types, Mutability and Higher-order Functions:  Tuples,  Lists and Mutability,  Functions as Objects,  Strings,  Tuples and Lists,  Dictionaries 3
  • 4. BipinRupadiya.com 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 significant whitespace. 4  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. Guido van Rossum
  • 5. BipinRupadiya.com Python Chapter-2 The basic elements of Python, Objects, expressions and numerical Types, Variables and assignments, IDLE, Branching programs, Strings and Input, Iteration
  • 6. 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
  • 7. 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
  • 8. BipinRupadiya.com Objects  Objects are the core things that Python programs manipulate  Every object has a type that defines the kinds of things that programs can do with objects of that type.  Types are either scalar or non-scalar.  Scalar objects are indivisible. Think of them as the atoms of the language.  Non-scalar objects, for example strings, have internal structure.
  • 9. 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.
  • 10. BipinRupadiya.com Expressions  Objects and operators can be combined to form expressions,  each of which evaluates to an object of some type.
  • 11. 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 the product 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 integer division.  For example, the value of 6//2 is the int 3 and the value of 6//4 is the int 1.  The value is 1 because integer division returns the quotient and ignores the remainder.  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.  i%j is the remainder when the int i is divided by the int j.  It is typically pronounced “i mod j,” which is short for “i modulo j.”  i**j is i raised to the power 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.  The comparison operators are == (equal), != (not equal), > (greater), >= (at least), <, (less) and <= (at most).
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. BipinRupadiya.com Variables and Assignment • It first binds the names pi and radius to different objects of type int. • It then binds the name area to a third object of type int. • An assignment statement associates the name to the left of the = symbol with the object denoted by the expression to the right of the = • Python allows multiple assignment. • The statement x, y = 2, 3 • Example of two variable exchanging code:
  • 16. BipinRupadiya.com IDLE  Typing programs directly into the shell is highly inconvenient.  Most programmers prefer to use some sort of text editor that is part of an integrated development environment (IDE).  we will use IDLE, the IDE that comes as part of the standard Python installation package.  IDLE is an application, just like any other application on your computer.  Start it the same way you would start any other application, e.g., by double- clicking on an icon.  IDLE (Integrated Development Environment) provides  a text editor with syntax highlighting, autocompletion, and smart indentation,  a shell with syntax highlighting, and  an integrated debugger
  • 18. 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
  • 19. 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‘) print ('Done with conditional‘)
  • 20. BipinRupadiya.com Branching Programs  Indentation is semantically meaningful in Python.  Python programs get structured through indentation.
  • 21. 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".
  • 22. 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.
  • 23. BipinRupadiya.com Strings and Input  The length of a string can be found using the len function.
  • 24. BipinRupadiya.com Strings and Input  Indexing can be used to extract individual characters from a string.  In Python, all indexing is zero-based.
  • 25. 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.
  • 26. 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.
  • 27. 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
  • 29. BipinRupadiya.com Python Chapter-5 • Tuples, Lists and Mutability, • Functions as Objects, • Strings, • Tuples and Lists, • Dictionaries
  • 30. 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.
  • 31. BipinRupadiya.com Tuples  Like strings, tuples can be concatenated, indexed, and sliced.
  • 32. 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 [],
  • 34. 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 insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the item with the specified value reverse() Reverses the order of the list sort() Sorts the list
  • 35. 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.
  • 37. 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
  • 38. 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.
  • 39. 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[:].
  • 40. 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.
  • 41. 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.
  • 43. 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.
  • 44. BipinRupadiya.com Example: map() [2, 4, 6, 8] [1, 4, 9, 16] Output:
  • 46. 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
  • 50. BipinRupadiya.com 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.
  • 51. BipinRupadiya.com dict() Constructor  The dict() constructor to make a dictionary.
  • 52. 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:
  • 54. BipinRupadiya.com Removing Item from Dictionaries Removing a dictionary item use the del() function
  • 55. BipinRupadiya.com Length of a Dictionary The len() function returns the size of the dictionary
  • 57. BipinRupadiya.com 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 57
  • 65. BipinRupadiya.com Bipin S. Rupadiya (MCA, PGDCA, BCA) Assistant Professor, JVIMS-MCA (537), Jamnagar www.BipinRupadiya.com 65