Python Objects

2: Python Objects

2.1 INTRODUCTION

2.2 BASIC DATA TYPES REVISITED

2.3 STRINGS

2.4 LISTS AND TUPLES

2.5 POINTS TO REMEMBER

2.6 EXERCISES


2.1 INTRODUCTION

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.

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

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: orand, and not
  • Relational operators: <, <=, >, >=, != or < > and ==.

2.2 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.

2.   

3.  >>> import math

4.  >>>math.ceil(2.678)

5.  3

6.  That of 2 is 2.

7.  >>>math.ceil(2)

8.  2

9.  >>>  

10. Copy sign:  The sign of the second argument is returned along with the result on the execution of this function.

11. 

12. math.copysign(x, y)

13. Return x with the sign of y.

On a platform that supports signed zeros, copy sign (1.0, – 0.0) returns –1.0.

14. 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.

15. Factorial:  The factorial of a number x is defined as the continued product of the numbers from 1 to that value. That is:

16. 

17. 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.

18. 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.

19. 

20. >>> import math

21. >>>math.floor(2.678)

22. 2

23. >>>math.floor(2)

24. 2

25. >>>  

2.2.1 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

1/200

4419157134357299/562949953421312

2476979795053773/2251799813685248

2476979795053773/2251799813685248

11/10


2.3 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>

name[2]='p'

TypeError: 'str' object does not support item assignment


2.4 LISTS AND TUPLES


2.4.1 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

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)

>>>  

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). Lists also support slicing.

2.4.2 Tuples

A tuple contains elements which can be treated individually or as a group. A tuple (say (xy)) 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 (ab) to (ba). 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 number\t:')

num1= int(input())

print('Enter the second number\t:')

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

Enter the second number :

3

The numbers entered are 2& 3

The numbers now are 3& 2

>>>  

2.4.3 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)


2.5 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.

 

2.6 EXERCISES


MULTIPLE-CHOICE QUESTIONS

  1. >>> a = 5
    >>> a + 2.7
    >>> a

    1. a + 2.7

    2. 7

    3. None of the above

    4. An exception is raised

    Answer:

    (a)

  2. >>> a = 5
    >>> b = 2
    >>> a/b

    1. 2

    2. 2.5

    3. 3

    4. None of the above

    Answer:

    (b)

  3. >>> a = 5
    >>> b = 2
    >>> c = float (a)/b
    >>> c

    1. 2

    2. 2.5

    3. 3

    4. An exception is raised

    Answer:

    (b)

  4. >>> a = 2
    >>> b = 'A'
    >>> c = a + b
    >>> c

    1. 67

    2. 60

    3. None of the above

    4. An exception is raised

    Answer:

    (d)

  5. >>> a = 'A'
    >>> 2*A

    1. ‘AA’

    2. 2A

    3. A2

    4. None of the above

    Answer:

    (a)

  6. >>> a = 'A'
    >>> b = 'B'
    >>> a + b

    1. A + B

    2. AB

    3. BA

    4. None of the above

    Answer:

    (b)

  7. >>> (a, b) = (2, 5)
    >>> (a, b) = (b, a)
    >>> (a, b)

    1. (2, 5)

    2. (5, 2)

    3. (5, 5)

    4. None of the above

    Answer:

    (b)

  8. >>> a = 5
    >>> b = 2
    >>> a = a + b
    >>> b = a - b
    >>> a = a - b
    >>> a

    1. 5

    2. 2

    3. None of the above

    4. An exception is raised

    Answer:

    (b)

  9. >>> a = 5
    >>> b * b = a
    >>> b

    1. 2.7

    2. 25

    3. None of the above

    4. An exception is raised

    Answer:

    (d)

  10. >>> (a, b) = (2, 3)
    >>> (c, d) = (4, 5)
    >>> (a, b) + (c, d)

    1. (6, 8)

    2. (2, 3, 4, 5)

    3. (8, 6)

    4. None of the above

    Answer:

    (b)

  11. In the above question what would (ab) – (cd) generate

    1. (6, 8)

    2. (2, 3, 4, 5)

    3. (8, 6)

    4. None of the above

    Answer:

    (d)

  12. In the above question what would (ab) * (cd) generate

    1. (6, 8)

    2. (2, 3, 4, 5)

    3. (8, 6)

    4. None of the above

    Answer:

    (d)

  13. >>> a = 'harsh'
    >>> b = a[1: len(a)]
    >>> b

    1. arsh

    2. hars

    3. harsh

    4. None of the above

    Answer:

    (a)

  14. >>>a = 'harsh'
    >>>b = [-3, len (a)]

    1. a[-3: len(a)]

    2. arsh

    3. harsh

    4. None of the above

    Answer:

    (a)

  15. >>>b
    >>>a = 'tar'
    >>>b = 'rat'
    >>>2*(a + b) is

    1. tarrattarrat

    2. rattarrattar

    3. tarratrattar

    4. None of the above

    Answer:

    (a)



2.6 EXERCISES

  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.