SlideShare a Scribd company logo
Python Objects
2.1
CHAPTER
2
PYTHON OBJECTS
After reading this chapter, the reader will be able to
• Understand the meaning and importance of variables, operators, keywords, and objects
• Use numbers and fractions in a program
• Appreciate the importance of strings
• Understand slicing and indexing in strings
• Use of lists and tuples
• Understand the importance of tuples
INTRODUCTION
To be able to write a program in Python the programmer can use Anaconda, the
installation of which was described in the previous chapter—or you can use
IDLE, which can be downloaded from the reference given at the end of the
Chapter 1. IDLE has an editor specially designed for writing a Python program.
As stated earlier Python is an interpreted language, so one need not to compile
every piece of code. The programmer can just write the command and see the
output at the command prompt. For example, when writing 2+3 on the command
line we get
>>2+3
5
As a matter of fact you can add, subtract, multiply, divide and perform
exponentiation in the command line. Multiplication can be done using the *
operator, the division can be performed using the / operator, the exponentiation
can be done using the ** operator and the modulo can be found using the %
operator. The modulo operator finds the remained if the first number is greater
than the other, otherwise it returns the first number as the output. The results of
the operations have been demonstrated as follows:
>>> 2*3
6
>>> 2/3
0.6666666666666666
>>> 2**3
8
>>> 2%3
2
>>> 3%2
1
>>>
In the above case, the Python interpreter is used to execute the commands. This
is referred to as a script mode. This mode works with small codes. Though
simple commands can be executed on the command line, the complex programs
can be written in a file. A file can be created as follows:
Step 1. Go to FILE NEW
Step 2. Save the file as calc.py
Step 3. Write the following code in the file
print(2+3)
print(2*3)
print(2**3)
print(2/3)
print(2%3)
print(3/2)
Step 4. Go to debug and run the program. The following output will be
displayed.
>>>
============ RUN C:/Python/Chapter 2/calc.py ============
5
6
8
0.6666666666666666
2
1.5
>>>
Conversely, the script can be executed by writing Python calc.py on the
command prompt. In order to exit IDLE go to FILE->EXIT or write the exit()
function at the command prompt.
In order to store values, we need variables. Python empowers the user to
manipulate variables. These variables help us to use the values later. As a matter
of fact, everything in Python is an object. This chapter focuses on objects. Each
object has identity, a type, and a value (given by the user / or a default value).
The identity, in Python, refers to the address and does not change. The type can
be any of the following.
None: This represents the absence of a value.
Numbers: Python has three types of numbers:
Integer: It does not have any fractional part
Floating Point: It can store number with a fractional part
Complex: It can store real and imaginary parts
Sequences: These are ordered collections of elements. There are three types of
sequences in Python:
String
Tuples
Lists
2.2
These types have been discussed in the sections that follow.
Sets: This is an un-ordered collection of elements.
Keywords: These are words having special meanings and are understood by the
interpreter. For example, and, del, from, not, while, as, elif, global,
else, if, pass, Yield, break, except, import, class, raise,
continue, finally, return, def, for, and try are some of the keywords
which have been extensively used in the book. For a complete list of keywords,
the reader may refer to the Appendix.
Operators: These are special symbols which help the user to carry out
operations like addition, subtraction, etc. Python provides following type of
operators:
Arithmetic operators: +, –, *, /, %, ** and //.
Assignment operators: =, + =, – =, *=, /=, %=, **= and //=
Logical operators: or, and, and not
Relational operators: <, <=, >, >=, != or < > and ==.
This chapter deals with the basic data types in Python and their uses. The chapter
has been organized as follows: Section 2 of this chapter deals with the
introduction to programming in Python and basic data types, and Section 3 deals
with strings. Section 4 deals with lists and tuples. The last section of this chapter
concludes the chapter. The readers are advised to go through the references at the
end of this book for comprehensive coverage of the topic.
BASIC DATA TYPES REVISITED
The importance of data types has already been discussed. There is another
reason to understand and to be able to deal with built-in data types, which is that
they generally are an intrinsic part of the bigger types which can be developed
by the user.
The data types provided by Python are not only powerful but also can be nested
within others. In the following discussion the concept of nested lists has been
presented, which is basically a list within a list. The power of data types can be
gauged by the fact that Python provides the user with dictionaries, which makes
mapping easy and efficient.
Numbers are the simplest data types. Numbers comprise of integers, floats,
decimals, and complexes in Python. The type of numbers and their explanations
have been summarized in Table 2.1. The operators supported by numbers have
been presented in Table 2.2.
Table 2.1 Numbers
Numbers Explanation
Integers Which do not have any fractional part
Floating point numbers That do have a fractional part
Complex numbers The numbers having a real and an imaginary part
Decimal Those having fixed precision
Rational Those having a numerator and a denominator
Sets Abstraction of a mathematical set
Table 2.2 Operators supported in numbers
+ Addition
– Subtraction
* Multiplication
** Power
% Modulo
In addition to the above, Python is practically free from the problems of C and
C++ and can calculate very, very large integers. Let us now have a look at how
to use these operators. For example if one needs to calculate the square root of a
number, then importing math and using math.sqrt() is a solution. Some of the
most important functions have been explained in the following sneak peek.
Sneak Peek
1. Ceil: The ceiling of a given number is the nearest integer greater than or
equal to that number. For example, the ceiling of 2.678 is 3.
>>> import math
>>>math.ceil(2.678)
3
That of 2 is 2.
>>>math.ceil(2)
2
>>>
2. Copy sign: The sign of the second argument is returned along with the result
on the execution of this function.
math.copysign(x, y)
Return x with the sign of y.
On a platform that supports signed zeros, copy sign (1.0, – 0.0) returns –1.0.
3. Fabs: The absolute value of a number is its positive value; that is if the
number is positive then the number itself is returned. If, on the other hand,
the number is negative then it is multiplied by –1 and returned.
In Python, this task is accomplished with the function fabs (x).
The fabs(x) returns the absolute value of x.
>>>math.fabs(-2.45)
2.45
>>>math.fabs(x)
Return the absolute value of x.
4. Factorial: The factorial of a number x is defined as the continued product of
the numbers from 1 to that value. That is:
Factorial(x) = 1 × 2 × 3 × … × n.
In Python, the task can be accomplished by the factorial function math.
factorial(x).
It returns the factorial of the number x. Also if the given number is not an
integer or is negative, then an exception is raised.
5. Floor: The floor of a given number is the nearest integer smaller than or
equal to that number. For example the floor of 2.678 is 2 and that of 2 is also
2.
2.2.1
>>> import math
>>>math.floor(2.678)
2
>>>math.floor(2)
2
>>>
Fractions
Python also provides the programmer the liberty to deal with fractions. The use
of fractions and decimals has been shown in the following listing.
Listing
from fractions import Fraction
print(Fraction(128, -26))
print(Fraction(256))
print(Fraction())
print(Fraction('2/5'))
print(Fraction(' -5/7'))
print(Fraction('2.675438 '))
print(Fraction('-32.75'))
print(Fraction('5e-3'))
print(Fraction(7.85))
print(Fraction(1.1))
print(Fraction(2476979795053773, 2251799813685248))
from decimal import Decimal
print(Fraction(Decimal('1.1')))
>>>
Output
========== RUN C:/Python/Chapter 2/Fraction.py ==========
-64/13
256
0
2/5
-5/7
1337719/500000
-131/4
2.3
1/200
4419157134357299/562949953421312
2476979795053773/2251799813685248
2476979795053773/2251799813685248
11/10
>>>
STRINGS
In Python a string is a predefined object which contains characters. The string in
Python is non-mutable; that is, once defined the value of a string cannot be
changed. However, as we proceed further, the exceptions to the above premise
will be discussed. To begin with, let us consider a string containing value
“Harsh,” that is:
name = 'Harsh'
The value of this string can be displayed simply by typing the name of the object
(name in this case) into the command prompt.
>>>name
Harsh
The value can also be printed by using the print function, explained previously.
print(name)
The value at a particular location of a string can be displayed using indexing.
The syntax of the above is as follows.
<name of the String>[index]
It may be stated here that the index of the first location is 0. So, name[0] would
print the first letter of the string, which is “H.”
print(name[0])
H
Negative indexing in a string refers to the character present at the nth position
beginning from the end. In the above case, name[-2] would generate “s.”
print(name[-2])
s
The length of a string can be found by calling the len function. len(str) returns
the length of the string “str.” For example, len(name) would return 5, as
'harsh' has 5 characters.
The last character of a given string can also be printed using the following.
print(name[len(name)-1])
The + operator concatenates, in the case of a string. For example “harsh” +
“arsh” would return “Harsharsh,” that is
name = name + 'arsh'
print(name)
Harsharsh
After concatenation, if the first and the second last characters are to be printed
then the following can be used.
print(name[0])
print(name[-2])
print(name[len(name)-1→2])
H
S
s
The * operator, of string, concatenates a given string the number of times, given
as the first argument. For example, 3*name would return “harsharshharsharsh.”
The complete script as follows:
Listing
name = 'Harsh'
print(name)
print(name[0])
print(name[-2])
print(name[len(name)-1])
name = name + 'arsh'
print(name)
print(name[0])
print(name[-2])
print(name[len(name)-1])
>>>
Output
=========== RUN C:/Python/Chapter 2/String.py ===========
Harsh
H
s
h
Harsharsh
H
s
h
>>>
Slicing: Slicing, in strings, refers to removing some part of a string. For
example:
>>>name = 'Sonam'
>>>name
'Sonam'
Here, if we intend to extract the portion after the first letter we can write [1:].
>>> name1=name[1:]
>>> name1
'onam'
In the same way the portion of the string after the first two letters can be
extracted as follows.
>>>name = name[2:]
>>>name
'nam'
Now, we modify the string by adding “man man”
>>>name = “man”+name
>>>name
'mannam'
It may be noted that the last two characters cannot be removed in the same way
as the first two. Observe the following output in order to understand the concept.
>>>name = name[:2]
>>>name
'ma'
>>>name = “man manam”
In order to accomplish the above task, negative indexing ought to be used.
>>>name
'manmanam'
>>> name2 = name[:-2]
>>> name2
'man man'
>>>
Immutability of Strings
It may be noted that when we write
name = 'Hello' + name
we don’t actually change the string; as a matter of fact we create a new string
having the value 'Hello' concatenated with the value stored in name. The
concept can be understood by the fact that when we try to change the value of a
particular character in a string, an error crops up.
>>>name='Anupam'
>>>name
'Anupam'
>>>name[2]='p'
Traceback (most recent call last):
File “<pyshell#17>”, line 1, in <module>
2.4
2.4.1
name[2]='p'
TypeError: 'str' object does not support item assignment
>>>
LISTS AND TUPLES
List
A list, in Python, is a collection of objects. As per Lutz “It is the most general
sequence provided by the language.” Unlike strings, lists are mutable. That is, an
element at a particular position can be changed in a list. A list is useful in dealing
with homogeneous and heterogeneous sequences.
A list can be one of the following:
A list can be a collection of similar elements (homogeneous), for example
[1, 2, 3]
It can also contain different elements (heterogeneous), like [1, “abc,” 2.4]
A list can also be empty ([])
A list can also contain a list (discussed in Chapter 4, of this book)
For example, the following list of authors has elements “Harsh Bhasin,” “Mark
Lutz,” and “Shiv.” The list can be printed using the usual print function. In the
following example, the second list in the following listing contains a number, a
string, a float, and a string. “list 3” is a null list and list-of-list contains list as its
elements.
Listing
authors = ['Harsh Bhasin', 'Mark Lutz', 'Shiv']
print(authors)
combined =[1, 'Harsh', 23.4, 'a']
print(combined)
list3= []
print(list3)
listoflist = [1, [1,2], 3]
print(listoflist)
>>>
2.4.2
Output
============ RUN C:/Python/Chapter 2/Lists.py ===========
['Harsh bhasin', 'Mark Lutz', 'Shiv']
[1, 'Harsh', 23.4, 'a']
[]
[1, [1, 2], 3]
>>>
An element of a list can be accessed by indexing; for example if list 1 contains
[1, 2, 3], then list 1[1] contains “2” and list 1[-1] contains “3.”
Listing
list1 = [1, 2, 3]
print(list1[1])
print(list1[-1])
>>>
Output
=========== RUN C:/Python/Chapter 2/list2.py ============
2
3
>>>
A list can also contain list(s). The topic has been discussed in Chapter 4. Lists
also support slicing.
Tuples
A tuple contains elements which can be treated individually or as a group. A
tuple (say (x, y)) can be printed using the standard print( ) function. The elements
of a tuple can be accessed by assigning it to a tuple, as shown in the following
listing. A tuple may also contain heterogeneous elements. For example, in the
following listing, tup2 and tup3 contain a string and an integer.
Listing
tup1= (2, 3)
print(tup1)
(a, b) = tup1
print('The first element is ',a)
print('The second element is ',b)
tup2=(101, 'Hari')
tup3=(102,'Shiv')
(code1, name1)=tup1
(code2, name2)=tup2
print('The code of ', name1,' is ',code1,'nThe code of
',name2, ' is ',code2)
>>>
Output
=========== RUN C:/Python/Chapter 2/tuple.py ============
(2, 3)
The first element is 2
The second element is 3
The code of 3 is 2
The code of Hari is 101
>>>
Tuples are extremely useful in operations like swapping etc. Swapping in Python
is as simple as assigning (a, b) to (b, a). The program for swapping two numbers
using tuples has been given as follows.
Illustration 2.1: Write a program to swap two numbers using tuples.
Solution:
print('Enter the first numbert:')
num1= int(input())
print('Enter the second numbert:')
num2= int(input())
print('nThe numbers entered are ',num1,' & ', num2)
(num1, num2) = (num2, num1)
print('nThe numbers now are ',num1,' & ', num2)
>>>
Output
============ RUN C:/Python/Chapter 2/swap.py ============
Enter the first number :
2.4.3
2.5
2
Enter the second number :
3
The numbers entered are 2& 3
The numbers now are 3& 2
>>>
Features of Tuples
Tuples are immutable—an element of a tuple cannot be assigned a different
value once it has been set. For example,
tup1 = (2, 3)
tup1[1] = 4
would raise an exception.
The “+” operator in a tuple concatenates two tuples. For example,
>>> tup1= (1,2)
>>> tup2=(3,4)
>>> tup3= tup1+tup2
>>> tup3
(1, 2, 3, 4)
>>>
CONCLUSION
In a program, instructions are given to a computer to perform a task. To be able
to do so, the operators operate on what are referred to as “objects.” This chapter
explains the various types of objects in Python and gives a brief overview of the
operators that act upon them. The objects can be built in or user defined. As a
matter of fact, everything that will be operated upon is an object.
The first section of this chapter describes various built-in objects in Python. The
readers familiar with “C” must have an idea as to what a procedural language is.
In “C,” for example, a program is divided into manageable modules, each of
which performs a particular task. The division of bigger tasks into smaller parts
makes parts manageable and the tracking of bugs easy. There are many more
advantages of using modules, some of which have been stated in Chapter 1.
These modules contain a set of statements, which are equivalent to instructions
(or no instruction, e.g. in case of a comment). The statements may contain
expressions, in which objects are operated upon by operators. As stated earlier,
Python gives its user the liberty to define their own objects. This will be dealt
with in the chapter on classes and objects. This chapter focuses on the built in
objects.
In C (or for that matter C++), one needs to be careful not only about the built-in
type used but also about the issues relating to the allocation of memory and data
structures. However, Python spares the user of these problems and can therefore
focus on the task at hand. The use of built-in data types makes things easy and
efficient.
GLOSSARY
None: This represents the absence of value.
Numbers: Python has three types of numbers: integers, floating point, complex.
Sequences: These are ordered collections of elements. There are three types of
sequences in Python:
String
Tuples
Lists
POINTS TO REMEMBER
In order to store values, we need variables.
Everything in Python is an object.
Each object has identity, a type, and a value.
EXERCISES
MULTIPLE CHOICE QUESTIONS
1. >>> a = 5
>>> a + 2.7
>>> a
(a) 7.7
(b) 7
(c) None of the above
(d) An exception is raised
2. >>> a = 5
>>> b = 2
>>> a/b
(a) 2
(b) 2.5
(c) 3
(d) None of the above
3. >>> a = 5
>>> b = 2
>>> c = float (a)/b
>>> c
(a) 2
(b) 2.5
(c) 3
(d) An exception is raised
4. >>> a = 2
>>> b = 'A'
>>> c = a + b
>>> c
(a) 67
(b) 60
(c) None of the above
(d) An exception is raised
5. >>> a = 'A'
>>> 2*A
(a) ‘AA’
(b) 2A
(c) A2
(d) None of the above
6. >>> a = 'A'
>>> b = 'B'
>>> a + b
(a) A + B
(b) AB
(c) BA
(d) None of the above
7. >>> (a, b) = (2, 5)
>>> (a, b) = (b, a)
>>> (a, b)
(a) (2, 5)
(b) (5, 2)
(c) (5, 5)
(d) None of the above
8. >>> a = 5
>>> b = 2
>>> a = a + b
>>> b = a - b
>>> a = a - b
>>> a
(a) 5
(b) 2
(c) None of the above
(d) An exception is raised
9. >>> a = 5
>>> b * b = a
>>> b
(a) 2.7
(b) 25
(c) None of the above
(d) An exception is raised
10. >>> (a, b) = (2, 3)
>>> (c, d) = (4, 5)
>>> (a, b) + (c, d)
(a) (6, 8)
(b) (2, 3, 4, 5)
(c) (8, 6)
(d) None of the above
11. In the above question what would (a, b) – (c, d) generate
(a) (6, 8)
(b) (2, 3, 4, 5)
(c) (8, 6)
(d) None of the above
12. In the above question what would (a, b) * (c, d) generate
(a) (6, 8)
(b) (2, 3, 4, 5)
(c) (8, 6)
(d) None of the above
13. >>> a = 'harsh'
>>> b = a[1: len(a)]
>>> b
(a) arsh
(b) hars
(c) harsh
(d) None of the above
14. >>>a = 'harsh'
>>>b = [-3, len (a)]
(a) rsh
(b) arsh
(c) harsh
(d) None of the above
15. >>>b
>>>a = 'tar'
>>>b = 'rat'
>>>2*(a + b) is
(a) tarrattarrat
(b) rattarrattar
(c) tarratrattar
(d) None of the above
PROGRAMS
1. Write a program to swap two numbers.
2. Ask the user to enter the coordinates of a point and find the distance of the
point from the origin.
3. Ask the user to enter two points (x and y coordinates) and find the distance
between them.
4. Ask the user to enter three points and find whether they are collinear.
5. In the above question, if the points are not collinear then find the type of
triangle formed by them (equilateral, isosceles or scalene).
6. In the above question, check if the triangle is right angled.
7. In question number 4, find the angles of the triangle.
8. Ask the user to enter two points and find if they are at equal distances from
the origin.
9. In question number 8, find the angle between the line joining the points and
the origin.
10. Ask the user to enter 4 points and arrange them in order of their distances
from the origin.
11. In question 10, arrange the above points in order of their x co-ordinates.
Ad

More Related Content

What's hot (17)

Ch03
Ch03Ch03
Ch03
Arriz San Juan
 
Ch02
Ch02Ch02
Ch02
Arriz San Juan
 
User Defined Functions in C Language
User Defined Functions   in  C LanguageUser Defined Functions   in  C Language
User Defined Functions in C Language
Infinity Tech Solutions
 
Functions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothiFunctions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothi
Sowmya Jyothi
 
Ch04
Ch04Ch04
Ch04
Arriz San Juan
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
Dushmanta Nath
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III Term
Andrew Raj
 
Ch09
Ch09Ch09
Ch09
Arriz San Juan
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
Hattori Sidek
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
Dushmanta Nath
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
Praveen M Jigajinni
 
Savitch ch 04
Savitch ch 04Savitch ch 04
Savitch ch 04
Terry Yoast
 
Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2
Syed Farjad Zia Zaidi
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya Jyothi
Sowmya Jyothi
 
Main topic 3 problem solving and office automation
Main topic 3 problem solving and office automationMain topic 3 problem solving and office automation
Main topic 3 problem solving and office automation
Infinity Tech Solutions
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
Mohammed Sikander
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
K Durga Prasad
 

Similar to Python Objects (20)

ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxFUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
SudhanshiBakre1
 
Python Interview Questions PDF By ScholarHat.pdf
Python Interview Questions PDF By ScholarHat.pdfPython Interview Questions PDF By ScholarHat.pdf
Python Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
Home
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
kavinilavuG
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
KavithaChekuri3
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
RojaPriya
 
advanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with pythonadvanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with python
barmansneha1204
 
Advanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learnersAdvanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learners
barmansneha1204
 
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptxpython notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
yuvarajkumar334
 
GE3151 UNIT II Study material .pdf
GE3151 UNIT II Study material .pdfGE3151 UNIT II Study material .pdf
GE3151 UNIT II Study material .pdf
Guru Nanak Technical Institutions
 
basics of python programming5.pdf
basics of python programming5.pdfbasics of python programming5.pdf
basics of python programming5.pdf
Pushkaran3
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
mustafatahertotanawa1
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
MaheshPandit16
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
ethiouniverse
 
PPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptxPPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptx
tcsonline1222
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxFUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
SudhanshiBakre1
 
Python Interview Questions PDF By ScholarHat.pdf
Python Interview Questions PDF By ScholarHat.pdfPython Interview Questions PDF By ScholarHat.pdf
Python Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
Home
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
kavinilavuG
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
RojaPriya
 
advanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with pythonadvanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with python
barmansneha1204
 
Advanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learnersAdvanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learners
barmansneha1204
 
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptxpython notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
yuvarajkumar334
 
basics of python programming5.pdf
basics of python programming5.pdfbasics of python programming5.pdf
basics of python programming5.pdf
Pushkaran3
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
MaheshPandit16
 
PPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptxPPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptx
tcsonline1222
 
Ad

More from MuhammadBakri13 (9)

Uxd01 uxd fundamental
Uxd01 uxd fundamentalUxd01 uxd fundamental
Uxd01 uxd fundamental
MuhammadBakri13
 
Chapter 4 stack and queue
Chapter 4 stack and queueChapter 4 stack and queue
Chapter 4 stack and queue
MuhammadBakri13
 
Views in MySQL
Views in MySQLViews in MySQL
Views in MySQL
MuhammadBakri13
 
Slide 03: Data Management
Slide 03: Data ManagementSlide 03: Data Management
Slide 03: Data Management
MuhammadBakri13
 
Chapter 02 - Database Development
Chapter 02 - Database DevelopmentChapter 02 - Database Development
Chapter 02 - Database Development
MuhammadBakri13
 
Slide 01-Data and the Enterprise
Slide 01-Data and the EnterpriseSlide 01-Data and the Enterprise
Slide 01-Data and the Enterprise
MuhammadBakri13
 
Chapter 14 Searching and Sorting
Chapter 14 Searching and SortingChapter 14 Searching and Sorting
Chapter 14 Searching and Sorting
MuhammadBakri13
 
Chapter 09-Trees
Chapter 09-TreesChapter 09-Trees
Chapter 09-Trees
MuhammadBakri13
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
MuhammadBakri13
 
Chapter 4 stack and queue
Chapter 4 stack and queueChapter 4 stack and queue
Chapter 4 stack and queue
MuhammadBakri13
 
Slide 03: Data Management
Slide 03: Data ManagementSlide 03: Data Management
Slide 03: Data Management
MuhammadBakri13
 
Chapter 02 - Database Development
Chapter 02 - Database DevelopmentChapter 02 - Database Development
Chapter 02 - Database Development
MuhammadBakri13
 
Slide 01-Data and the Enterprise
Slide 01-Data and the EnterpriseSlide 01-Data and the Enterprise
Slide 01-Data and the Enterprise
MuhammadBakri13
 
Chapter 14 Searching and Sorting
Chapter 14 Searching and SortingChapter 14 Searching and Sorting
Chapter 14 Searching and Sorting
MuhammadBakri13
 
Ad

Recently uploaded (20)

Physical and Physic-Chemical Based Optimization Methods: A Review
Physical and Physic-Chemical Based Optimization Methods: A ReviewPhysical and Physic-Chemical Based Optimization Methods: A Review
Physical and Physic-Chemical Based Optimization Methods: A Review
Journal of Soft Computing in Civil Engineering
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Journal of Soft Computing in Civil Engineering
 
Environment .................................
Environment .................................Environment .................................
Environment .................................
shadyozq9
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic AlgorithmDesign Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Journal of Soft Computing in Civil Engineering
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdfIBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
VigneshPalaniappanM
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Construction-Chemicals-For-Waterproofing.ppt
Construction-Chemicals-For-Waterproofing.pptConstruction-Chemicals-For-Waterproofing.ppt
Construction-Chemicals-For-Waterproofing.ppt
ssuser2ffcbc
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Environment .................................
Environment .................................Environment .................................
Environment .................................
shadyozq9
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdfIBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
VigneshPalaniappanM
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Construction-Chemicals-For-Waterproofing.ppt
Construction-Chemicals-For-Waterproofing.pptConstruction-Chemicals-For-Waterproofing.ppt
Construction-Chemicals-For-Waterproofing.ppt
ssuser2ffcbc
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 

Python Objects

  • 2. 2.1 CHAPTER 2 PYTHON OBJECTS After reading this chapter, the reader will be able to • Understand the meaning and importance of variables, operators, keywords, and objects • Use numbers and fractions in a program • Appreciate the importance of strings • Understand slicing and indexing in strings • Use of lists and tuples • Understand the importance of tuples INTRODUCTION To be able to write a program in Python the programmer can use Anaconda, the installation of which was described in the previous chapter—or you can use IDLE, which can be downloaded from the reference given at the end of the Chapter 1. IDLE has an editor specially designed for writing a Python program. As stated earlier Python is an interpreted language, so one need not to compile every piece of code. The programmer can just write the command and see the output at the command prompt. For example, when writing 2+3 on the command line we get >>2+3 5 As a matter of fact you can add, subtract, multiply, divide and perform exponentiation in the command line. Multiplication can be done using the * operator, the division can be performed using the / operator, the exponentiation can be done using the ** operator and the modulo can be found using the % operator. The modulo operator finds the remained if the first number is greater than the other, otherwise it returns the first number as the output. The results of the operations have been demonstrated as follows:
  • 3. >>> 2*3 6 >>> 2/3 0.6666666666666666 >>> 2**3 8 >>> 2%3 2 >>> 3%2 1 >>> In the above case, the Python interpreter is used to execute the commands. This is referred to as a script mode. This mode works with small codes. Though simple commands can be executed on the command line, the complex programs can be written in a file. A file can be created as follows: Step 1. Go to FILE NEW Step 2. Save the file as calc.py Step 3. Write the following code in the file print(2+3) print(2*3) print(2**3) print(2/3) print(2%3) print(3/2)
  • 4. Step 4. Go to debug and run the program. The following output will be displayed. >>> ============ RUN C:/Python/Chapter 2/calc.py ============ 5 6 8 0.6666666666666666 2 1.5 >>> Conversely, the script can be executed by writing Python calc.py on the command prompt. In order to exit IDLE go to FILE->EXIT or write the exit() function at the command prompt. In order to store values, we need variables. Python empowers the user to manipulate variables. These variables help us to use the values later. As a matter of fact, everything in Python is an object. This chapter focuses on objects. Each object has identity, a type, and a value (given by the user / or a default value). The identity, in Python, refers to the address and does not change. The type can be any of the following. None: This represents the absence of a value. Numbers: Python has three types of numbers: Integer: It does not have any fractional part Floating Point: It can store number with a fractional part Complex: It can store real and imaginary parts Sequences: These are ordered collections of elements. There are three types of sequences in Python: String Tuples Lists
  • 5. 2.2 These types have been discussed in the sections that follow. Sets: This is an un-ordered collection of elements. Keywords: These are words having special meanings and are understood by the interpreter. For example, and, del, from, not, while, as, elif, global, else, if, pass, Yield, break, except, import, class, raise, continue, finally, return, def, for, and try are some of the keywords which have been extensively used in the book. For a complete list of keywords, the reader may refer to the Appendix. Operators: These are special symbols which help the user to carry out operations like addition, subtraction, etc. Python provides following type of operators: Arithmetic operators: +, –, *, /, %, ** and //. Assignment operators: =, + =, – =, *=, /=, %=, **= and //= Logical operators: or, and, and not Relational operators: <, <=, >, >=, != or < > and ==. This chapter deals with the basic data types in Python and their uses. The chapter has been organized as follows: Section 2 of this chapter deals with the introduction to programming in Python and basic data types, and Section 3 deals with strings. Section 4 deals with lists and tuples. The last section of this chapter concludes the chapter. The readers are advised to go through the references at the end of this book for comprehensive coverage of the topic. BASIC DATA TYPES REVISITED The importance of data types has already been discussed. There is another reason to understand and to be able to deal with built-in data types, which is that they generally are an intrinsic part of the bigger types which can be developed by the user. The data types provided by Python are not only powerful but also can be nested within others. In the following discussion the concept of nested lists has been presented, which is basically a list within a list. The power of data types can be gauged by the fact that Python provides the user with dictionaries, which makes
  • 6. mapping easy and efficient. Numbers are the simplest data types. Numbers comprise of integers, floats, decimals, and complexes in Python. The type of numbers and their explanations have been summarized in Table 2.1. The operators supported by numbers have been presented in Table 2.2. Table 2.1 Numbers Numbers Explanation Integers Which do not have any fractional part Floating point numbers That do have a fractional part Complex numbers The numbers having a real and an imaginary part Decimal Those having fixed precision Rational Those having a numerator and a denominator Sets Abstraction of a mathematical set Table 2.2 Operators supported in numbers + Addition – Subtraction * Multiplication ** Power % Modulo In addition to the above, Python is practically free from the problems of C and C++ and can calculate very, very large integers. Let us now have a look at how to use these operators. For example if one needs to calculate the square root of a number, then importing math and using math.sqrt() is a solution. Some of the most important functions have been explained in the following sneak peek. Sneak Peek 1. Ceil: The ceiling of a given number is the nearest integer greater than or equal to that number. For example, the ceiling of 2.678 is 3. >>> import math
  • 7. >>>math.ceil(2.678) 3 That of 2 is 2. >>>math.ceil(2) 2 >>> 2. Copy sign: The sign of the second argument is returned along with the result on the execution of this function. math.copysign(x, y) Return x with the sign of y. On a platform that supports signed zeros, copy sign (1.0, – 0.0) returns –1.0. 3. Fabs: The absolute value of a number is its positive value; that is if the number is positive then the number itself is returned. If, on the other hand, the number is negative then it is multiplied by –1 and returned. In Python, this task is accomplished with the function fabs (x). The fabs(x) returns the absolute value of x. >>>math.fabs(-2.45) 2.45 >>>math.fabs(x) Return the absolute value of x. 4. Factorial: The factorial of a number x is defined as the continued product of the numbers from 1 to that value. That is: Factorial(x) = 1 × 2 × 3 × … × n. In Python, the task can be accomplished by the factorial function math. factorial(x). It returns the factorial of the number x. Also if the given number is not an integer or is negative, then an exception is raised. 5. Floor: The floor of a given number is the nearest integer smaller than or equal to that number. For example the floor of 2.678 is 2 and that of 2 is also 2.
  • 8. 2.2.1 >>> import math >>>math.floor(2.678) 2 >>>math.floor(2) 2 >>> Fractions Python also provides the programmer the liberty to deal with fractions. The use of fractions and decimals has been shown in the following listing. Listing from fractions import Fraction print(Fraction(128, -26)) print(Fraction(256)) print(Fraction()) print(Fraction('2/5')) print(Fraction(' -5/7')) print(Fraction('2.675438 ')) print(Fraction('-32.75')) print(Fraction('5e-3')) print(Fraction(7.85)) print(Fraction(1.1)) print(Fraction(2476979795053773, 2251799813685248)) from decimal import Decimal print(Fraction(Decimal('1.1'))) >>> Output ========== RUN C:/Python/Chapter 2/Fraction.py ========== -64/13 256 0 2/5 -5/7 1337719/500000 -131/4
  • 9. 2.3 1/200 4419157134357299/562949953421312 2476979795053773/2251799813685248 2476979795053773/2251799813685248 11/10 >>> STRINGS In Python a string is a predefined object which contains characters. The string in Python is non-mutable; that is, once defined the value of a string cannot be changed. However, as we proceed further, the exceptions to the above premise will be discussed. To begin with, let us consider a string containing value “Harsh,” that is: name = 'Harsh' The value of this string can be displayed simply by typing the name of the object (name in this case) into the command prompt. >>>name Harsh The value can also be printed by using the print function, explained previously. print(name) The value at a particular location of a string can be displayed using indexing. The syntax of the above is as follows. <name of the String>[index] It may be stated here that the index of the first location is 0. So, name[0] would print the first letter of the string, which is “H.” print(name[0]) H Negative indexing in a string refers to the character present at the nth position
  • 10. beginning from the end. In the above case, name[-2] would generate “s.” print(name[-2]) s The length of a string can be found by calling the len function. len(str) returns the length of the string “str.” For example, len(name) would return 5, as 'harsh' has 5 characters. The last character of a given string can also be printed using the following. print(name[len(name)-1]) The + operator concatenates, in the case of a string. For example “harsh” + “arsh” would return “Harsharsh,” that is name = name + 'arsh' print(name) Harsharsh After concatenation, if the first and the second last characters are to be printed then the following can be used. print(name[0]) print(name[-2]) print(name[len(name)-1→2]) H S s The * operator, of string, concatenates a given string the number of times, given as the first argument. For example, 3*name would return “harsharshharsharsh.” The complete script as follows: Listing name = 'Harsh' print(name) print(name[0]) print(name[-2]) print(name[len(name)-1])
  • 11. name = name + 'arsh' print(name) print(name[0]) print(name[-2]) print(name[len(name)-1]) >>> Output =========== RUN C:/Python/Chapter 2/String.py =========== Harsh H s h Harsharsh H s h >>> Slicing: Slicing, in strings, refers to removing some part of a string. For example: >>>name = 'Sonam' >>>name 'Sonam' Here, if we intend to extract the portion after the first letter we can write [1:]. >>> name1=name[1:] >>> name1 'onam' In the same way the portion of the string after the first two letters can be extracted as follows. >>>name = name[2:] >>>name 'nam'
  • 12. Now, we modify the string by adding “man man” >>>name = “man”+name >>>name 'mannam' It may be noted that the last two characters cannot be removed in the same way as the first two. Observe the following output in order to understand the concept. >>>name = name[:2] >>>name 'ma' >>>name = “man manam” In order to accomplish the above task, negative indexing ought to be used. >>>name 'manmanam' >>> name2 = name[:-2] >>> name2 'man man' >>> Immutability of Strings It may be noted that when we write name = 'Hello' + name we don’t actually change the string; as a matter of fact we create a new string having the value 'Hello' concatenated with the value stored in name. The concept can be understood by the fact that when we try to change the value of a particular character in a string, an error crops up. >>>name='Anupam' >>>name 'Anupam' >>>name[2]='p' Traceback (most recent call last): File “<pyshell#17>”, line 1, in <module>
  • 13. 2.4 2.4.1 name[2]='p' TypeError: 'str' object does not support item assignment >>> LISTS AND TUPLES List A list, in Python, is a collection of objects. As per Lutz “It is the most general sequence provided by the language.” Unlike strings, lists are mutable. That is, an element at a particular position can be changed in a list. A list is useful in dealing with homogeneous and heterogeneous sequences. A list can be one of the following: A list can be a collection of similar elements (homogeneous), for example [1, 2, 3] It can also contain different elements (heterogeneous), like [1, “abc,” 2.4] A list can also be empty ([]) A list can also contain a list (discussed in Chapter 4, of this book) For example, the following list of authors has elements “Harsh Bhasin,” “Mark Lutz,” and “Shiv.” The list can be printed using the usual print function. In the following example, the second list in the following listing contains a number, a string, a float, and a string. “list 3” is a null list and list-of-list contains list as its elements. Listing authors = ['Harsh Bhasin', 'Mark Lutz', 'Shiv'] print(authors) combined =[1, 'Harsh', 23.4, 'a'] print(combined) list3= [] print(list3) listoflist = [1, [1,2], 3] print(listoflist) >>>
  • 14. 2.4.2 Output ============ RUN C:/Python/Chapter 2/Lists.py =========== ['Harsh bhasin', 'Mark Lutz', 'Shiv'] [1, 'Harsh', 23.4, 'a'] [] [1, [1, 2], 3] >>> An element of a list can be accessed by indexing; for example if list 1 contains [1, 2, 3], then list 1[1] contains “2” and list 1[-1] contains “3.” Listing list1 = [1, 2, 3] print(list1[1]) print(list1[-1]) >>> Output =========== RUN C:/Python/Chapter 2/list2.py ============ 2 3 >>> A list can also contain list(s). The topic has been discussed in Chapter 4. Lists also support slicing. Tuples A tuple contains elements which can be treated individually or as a group. A tuple (say (x, y)) can be printed using the standard print( ) function. The elements of a tuple can be accessed by assigning it to a tuple, as shown in the following listing. A tuple may also contain heterogeneous elements. For example, in the following listing, tup2 and tup3 contain a string and an integer. Listing tup1= (2, 3) print(tup1) (a, b) = tup1
  • 15. print('The first element is ',a) print('The second element is ',b) tup2=(101, 'Hari') tup3=(102,'Shiv') (code1, name1)=tup1 (code2, name2)=tup2 print('The code of ', name1,' is ',code1,'nThe code of ',name2, ' is ',code2) >>> Output =========== RUN C:/Python/Chapter 2/tuple.py ============ (2, 3) The first element is 2 The second element is 3 The code of 3 is 2 The code of Hari is 101 >>> Tuples are extremely useful in operations like swapping etc. Swapping in Python is as simple as assigning (a, b) to (b, a). The program for swapping two numbers using tuples has been given as follows. Illustration 2.1: Write a program to swap two numbers using tuples. Solution: print('Enter the first numbert:') num1= int(input()) print('Enter the second numbert:') num2= int(input()) print('nThe numbers entered are ',num1,' & ', num2) (num1, num2) = (num2, num1) print('nThe numbers now are ',num1,' & ', num2) >>> Output ============ RUN C:/Python/Chapter 2/swap.py ============ Enter the first number :
  • 16. 2.4.3 2.5 2 Enter the second number : 3 The numbers entered are 2& 3 The numbers now are 3& 2 >>> Features of Tuples Tuples are immutable—an element of a tuple cannot be assigned a different value once it has been set. For example, tup1 = (2, 3) tup1[1] = 4 would raise an exception. The “+” operator in a tuple concatenates two tuples. For example, >>> tup1= (1,2) >>> tup2=(3,4) >>> tup3= tup1+tup2 >>> tup3 (1, 2, 3, 4) >>> CONCLUSION In a program, instructions are given to a computer to perform a task. To be able to do so, the operators operate on what are referred to as “objects.” This chapter explains the various types of objects in Python and gives a brief overview of the operators that act upon them. The objects can be built in or user defined. As a matter of fact, everything that will be operated upon is an object. The first section of this chapter describes various built-in objects in Python. The readers familiar with “C” must have an idea as to what a procedural language is. In “C,” for example, a program is divided into manageable modules, each of which performs a particular task. The division of bigger tasks into smaller parts makes parts manageable and the tracking of bugs easy. There are many more advantages of using modules, some of which have been stated in Chapter 1.
  • 17. These modules contain a set of statements, which are equivalent to instructions (or no instruction, e.g. in case of a comment). The statements may contain expressions, in which objects are operated upon by operators. As stated earlier, Python gives its user the liberty to define their own objects. This will be dealt with in the chapter on classes and objects. This chapter focuses on the built in objects. In C (or for that matter C++), one needs to be careful not only about the built-in type used but also about the issues relating to the allocation of memory and data structures. However, Python spares the user of these problems and can therefore focus on the task at hand. The use of built-in data types makes things easy and efficient. GLOSSARY None: This represents the absence of value. Numbers: Python has three types of numbers: integers, floating point, complex. Sequences: These are ordered collections of elements. There are three types of sequences in Python: String Tuples Lists POINTS TO REMEMBER In order to store values, we need variables. Everything in Python is an object. Each object has identity, a type, and a value. EXERCISES MULTIPLE CHOICE QUESTIONS
  • 18. 1. >>> a = 5 >>> a + 2.7 >>> a (a) 7.7 (b) 7 (c) None of the above (d) An exception is raised 2. >>> a = 5 >>> b = 2 >>> a/b (a) 2 (b) 2.5 (c) 3 (d) None of the above 3. >>> a = 5 >>> b = 2 >>> c = float (a)/b >>> c (a) 2 (b) 2.5 (c) 3 (d) An exception is raised 4. >>> a = 2 >>> b = 'A' >>> c = a + b >>> c (a) 67 (b) 60 (c) None of the above (d) An exception is raised
  • 19. 5. >>> a = 'A' >>> 2*A (a) ‘AA’ (b) 2A (c) A2 (d) None of the above 6. >>> a = 'A' >>> b = 'B' >>> a + b (a) A + B (b) AB (c) BA (d) None of the above 7. >>> (a, b) = (2, 5) >>> (a, b) = (b, a) >>> (a, b) (a) (2, 5) (b) (5, 2) (c) (5, 5) (d) None of the above 8. >>> a = 5 >>> b = 2 >>> a = a + b >>> b = a - b >>> a = a - b >>> a (a) 5 (b) 2 (c) None of the above (d) An exception is raised
  • 20. 9. >>> a = 5 >>> b * b = a >>> b (a) 2.7 (b) 25 (c) None of the above (d) An exception is raised 10. >>> (a, b) = (2, 3) >>> (c, d) = (4, 5) >>> (a, b) + (c, d) (a) (6, 8) (b) (2, 3, 4, 5) (c) (8, 6) (d) None of the above 11. In the above question what would (a, b) – (c, d) generate (a) (6, 8) (b) (2, 3, 4, 5) (c) (8, 6) (d) None of the above 12. In the above question what would (a, b) * (c, d) generate (a) (6, 8) (b) (2, 3, 4, 5) (c) (8, 6) (d) None of the above 13. >>> a = 'harsh' >>> b = a[1: len(a)] >>> b (a) arsh
  • 21. (b) hars (c) harsh (d) None of the above 14. >>>a = 'harsh' >>>b = [-3, len (a)] (a) rsh (b) arsh (c) harsh (d) None of the above 15. >>>b >>>a = 'tar' >>>b = 'rat' >>>2*(a + b) is (a) tarrattarrat (b) rattarrattar (c) tarratrattar (d) None of the above PROGRAMS 1. Write a program to swap two numbers. 2. Ask the user to enter the coordinates of a point and find the distance of the point from the origin. 3. Ask the user to enter two points (x and y coordinates) and find the distance between them. 4. Ask the user to enter three points and find whether they are collinear. 5. In the above question, if the points are not collinear then find the type of triangle formed by them (equilateral, isosceles or scalene).
  • 22. 6. In the above question, check if the triangle is right angled. 7. In question number 4, find the angles of the triangle. 8. Ask the user to enter two points and find if they are at equal distances from the origin. 9. In question number 8, find the angle between the line joining the points and the origin. 10. Ask the user to enter 4 points and arrange them in order of their distances from the origin. 11. In question 10, arrange the above points in order of their x co-ordinates.
  翻译: