<<

CLASS-XI

COMPUTER SCIENCE

PYTHON DATA TYPES

NOTES

Data Types :

A , in Python or in any , is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error. The string and int , for example, are Python data types that are used to classify text and an integer is a data type used to classify whole number

A=10+12

A= “ram”

A=10.5

Classifications of Data Types in Python

(i) Numbers (ii) string (iii) list (iv) tuple (v) dictionary

Python data types are divided into two categories, mutable data types and immutable data types.

Mutable Data Type: Data types in python where the value assigned to a variable can be changed.

Immutable Data Type: Data types in Python where the value assigned to a variable cannot be changed.

Mutable and Immutable objects:

Data objects of the above types are stored in a computer’s memory for processing. Some of these values can be modified during processing, but the contents of others cannot be altered once they are created in the memory.

Number values, string, and tuple are immutable, which means their contents can’t be altered after creation.

On the other hand, the collection of items in a list or dictionary object can be modified. It is possible to add, delete, insert, and rearrange items in a list or dictionary. Hence they are mutable objects.

Example Data Type x = "Hello World" str x = 20 int x = 20.5 float x = 1j complex x = ["apple", "banana", "cherry"] list x = ("apple", "banana", "cherry") tuple x = {"name" : "John", "age" : 36} dict x = {"apple", "banana", "cherry"} x = True bool

NUMBERS DATA TYPE

As it is clear by the name the Number data types are used to store numeric values in Python. The Numbers in Python have following core Data types.

* Integers Integers (signed)

Booleans

* Floating Point Numbers

* Complex Numbers

Integers are whole numbers with no fractional parts. Integers can be positive or negative. Booleans are subtype of plain integers. Long integers have unlimited precision and float represent real numbers and are written with a decimal point dividing the integer and fractional parts. Complex numbers have a real and imaginary part. a+bj. Where a is the real part and b is the imaginary part.

It is useful for problem solvers to understand a couple of Python’s core data types in order to write well-constructed code.

The Python Programming language provides four numeric data types. They are as follows:

* int—All the numbers without fraction part(Example-10). For int there is no upper limit. *float –All the numbers with a fraction part(Example- 10.5) .It’s accurate up to 15 decimal places.

*complex- All the numbers with real and imaginary parts.(Example-5+10 j).

*bool – Boolean values True and False

Integers are whole numbers with no fractional parts. Integers can bepositive or negative. Booleans are subtype of plain integers. Long integers have unlimited precision and float represent real numbers and are written with a decimal point dividing the integer and fractional parts. Complex numbers have a real and imaginary part. a+bj. Where a is the real part and b is the imaginary part.

It is useful for problem solvers to understand a couple of Python’s core data types in order to write well-constructed code.

Integers Data Types

 Int – signed integers  Long-Ling integers for representing higher values

Like in math, integers in computer programming are whole numbers that can be positive, negative, or 0(……-1,0.1……).An integer can also be known as an int. As with other programming languages, you should not use commas in number of four digits or more. So when you write 1.000 in your program write it as 1000.

A=1000

We can print out as integer in a simple way like this: print(-25)

Output :

-25

We can do math with integers in Python, too : int ans= 116-68 print(ans) output

48

Floating – Point Numbers Data Types

The float data types are used to represent decimal point values. This value is represented by float class. It is real number with floating point representation. It is specified by a decimal point. Optionally, the e or E followed by a positive or negative integer may be appended to specify scientific notation.

It can be written as fractional form or exponent form. Floating point number has two advantages over integers:

1. They can represent values between two integers. 2. They can represent a much greater range of values. And the disadvantage is :

Its operation are slower than integer operations.

Example :

>>>d= 6.2

>>>type(d)

>>>a=-0.03

>>>type(a)

>>>e=6.02e23

>>>e

6.02e+23

>>>type(e)

To make sure a variable is a float instead of an integer even if it is a whole number, a trailing decimal point is used. Note the difference when a decimal point comes after a whole number:

>>>g=5 # no decimal point

>>>type(g)

>>>g=5.0 #decimal point

>>>type(g)

Complex Number Data Type complex numbers: Python represents complex number as a pair of floating point numbers. >>>c= 0+4.5 j >>>d =1.1 +3.4 j >>>c 4.5 j >>>d (1.1 +3.4 j)

A complex number with non-zero real part is displayed with parentheses around it.

>>>print (c )

4.5 j

>>>print(d)

(1.1 +3.4 j)

Complex numbers are specified as + j. For example :

>>>2 +3j

(2+3j)

>>>type(2+3j)

Boolean Data Types

A Boolean is such a data type that almost every programming language has, and so does python. Boolean in Python can have two values-True or False. These values can be used for assigning and comparison.

Boolean data types are similar to a coin. At a time either we found head or tail, such that Boolean either returns True or False. There are two constants, true and false, these constants are used to assign the value to a Boolean data type.

Example 1 Boolean Data Type :

A= True

B= False

A&B

A|B

Output :

False

True

Example 2 Boolean Data Type : print(True+false+True) output:

2 Note: Python treats a True value as 1 and a False value as 0.So a the above example returns 2(1+0+1)

Example 3 Boolean Data Type: print(bool(True)) ; print(bool(False)); print(bool(0)); print(bool()); print(bool(3)); print(bool(“pankaj”)); print(bool(“”)); print((bool(‘’)) print(bool(True+True)); print(bool(False+False)); print(bool(True+False)) print(bool(None));

Output:

True

False

False

False

True

True

False True

True

False

True

False

STRING DATA TYPE

A python string is a sequence of characters and each character can be individually accessed using its index. Strings are immutable so assignment is not allowed.  Strings in python are stored by storing each character separately in contiguous locations.  The characters of the strings are given two-way indices : . 0,1,2,…. in the forward direction and . -1,-2,-3,…. in the backward direction.

Ex : name = ‘hello’ name[0]= ‘j’ will cause an error.

0 1 2 3 4 5 P Y T H O N

-6 -5 -4 -3 -2 -1 It’s very easy to create the strings objects in Python, any characters which are enclosed by quotes become string(quotes can single or double).

A string in Python is an immutable and ordered sequence of items. They can be defined using single – quotes(‘’) or double quotes(“”).

A string spanning multiple lines can be defined using triple single-quotes(‘’’) or triple double-quotes(“””).For example:

>>>myvar= ‘This\ is a string’

>>>type(myvar)

>>>my_string= “””This is

…my

…first

…string”””

>>>print(my_string)

This is

My first string

>>>my_string2=’’’

…This

…is

…my

…second

…string

…’’’

>>>print(my_string2)

This Is

My

Second string

Since strings in Python are ordered, we can extract individual characters from a string using their integer indices, starting with 0. The first letter of a string is always at position 0, and the positions numerically increases after that. For example:

>>>myvar= ‘This is a string’

>>>myvar[0]

‘T’

>>>myvar[10]

‘s’

Strings in Python also support slicing. Slicing is a technique which is used to extract a part of a variable using the notation[start_position: end_position], where start_position and end_position are integers indicating the length of the slice. If start_positon is omitted, then slicing begins at the beginning of the string, and if end position is omitted, then slicing end at the end of the string. For example:

>>>myvar[0:1]

>>> ‘T’

>>>myvar[0:]

‘This is a string’

>>>myvar[:len(myvar)]

‘This is a string’

TUPLE DATA TYPE

The tuple is similar to list in Python. In Python, The tuple data type is immutable. That means the tuples cannot be modified, unlike lists. In Python, The tuple may contain different data type values. The tuples are enclosed in parentheses. They are represent as group of comma-separated values of any data types within parentheses, e.g. following are some tuples:

Tuples are identical to lists in all respects, except for the following properties:

 Tuples are defined by enclosing the elements in parentheses (()) instead of square brackets ([]).  Tuples are immutable. p = (1,2,3,4,5) q= (2,4,6.5,8) f=(2.4,7.6,9,”ram”,’v’) r = (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) h = (7,8,9, ‘A’, ‘B’, ‘C’)

Example – Python code to illustrate ‘Tuple’ in Python

>>>roll=(1,2,3,4,5)

>>>print(roll)

(1,2,3,4,5)

>>>student=(1,“raman”, “12 class”)

>>>print(type(student))

>>>first =(1,2,3)

>>>second=(4,5,6) >>>print(len(first))

3

>>>print(max(first))

3

>>>print(min(first))

1

>>>print(first+second)

(1,2,3,4,5,6)

>>>print(first*3)

(1,2,3,1,2,3,1,2,3)

>>>print(1 in first)

True

>>>print(5 not in second)

False

This example shows several basic operations with tuples.The len( ) function returns the number of elements in the first tuple. The max() function returns the maximum value and the min() function returns the minimum value. The addition operator adds two tuples, the multiplication operator multiplies the tuple. The in operator determines if the value is in the tuple.

Why use a tuple instead of a list?

 Program execution is faster when manipulating a tuple than it is for the equivalent list. (This is probably not going to be noticeable when the list or tuple is small.)  Sometimes you don’t want data to be modified. If the values in the collection are meant to remain constant for the life of the program, using a tuple instead of a list guards against accidental modification.  There is another Python data type that you will encounter shortly called a dictionary, which requires as one of its components a value that is of an immutable type. A tuple can be used for this purpose, whereas a list can’t be.

LIST DATA TYPE

A list in python represents a list of comma separated values of any data type between square brackets.

The important characteristics of Python lists are as follows:

 Lists are ordered.  Lists can contain any arbitrary objects.  List elements can be accessed by index.  Lists can be nested to arbitrary depth.  Lists are mutable.  Lists are dynamic

Eg : following are some list:

>>>L1=[1,2,3,4,5]

>>>print(L1)

[1,2,3,4,5]

>>>print(type)

>>>y=[‘a’, ‘e’, ‘I , ‘o’, ‘u’]

>>>s=[‘Neha’,102,79.5]

[1,2,3,4,5]

>>>print (a)

[1,2,3,4,5]

To change first Like any other value, you can assign a list to a variable. eg;

>>> a=[1,2,3,4,5] -#statement 1 >>>a value in a list namely a (given above), you may write

>>>a[0] = 10

>>>a

[10,2,3,4,5]

To change 3rd item, you may write

>>>a[2] = 30

>>>a

[10,2,30,4,5]

The list is one of the most used in Python for traversing the elements.It is used along with tuples, dictionaries and sets. The list is a collection of items/data which is ordered and can be changed whenever needed. It also allows duplicate records in the data sets.

Lists versus Tuples:

Tuples are used to collect an immutable ordered list of elements. This means that:

 You can’t add elements to a tuple. There’s no append() or extend() method for tuples,  You can’t remove elements from a tuple. Tuples have no remove() or pop() method,  You can find elements in a tuple since this doesn’t change the tuple.

You can also use the in operator to check if an element exists in the tuple

Dictionary Data Type

Dictionaries are a collection of some key-value pairs. .Dictionaries is mutable, unordered collections with elements in the form of a key: a value pair that associates keys to values. The syntax to create a dictionary is:

= { : , :……………}

Ex: emp = {‘salary’ : 10000 , ‘age’ :24 , ‘name’ : ‘john’ } >>>emp.keys() [‘salary’,’age’,’name’] >>>emp.values() [10000,24,’john’]

Properties of Dictionary Keys

There are two important points while using dictionary keys

 More than one entry per key is not allowed ( no duplicate key is allowed)  The values in the dictionary can be of any type while the keys must be immutable like numbers, tuples or strings.  Dictionary keys are case sensitive- Same key name but with the different case are treated as different keys in Python dictionaries. {“ab” :12,”AB”: 13}

Dictionaries and lists share the following characteristics:

 Both are mutable.  Both are dynamic. They can grow and shrink as needed.  Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.

Dictionaries differ from lists primarily in how elements are accessed:

 List elements are accessed by their position in the list, via indexing.  Dictionary elements are accessed via keys.

Q1.What is the output produced by above code: d1= {5:[6,7,8] ,”a”:(1,2,3)} print(d1.key()) print(d1.values())

Expressions An expression in python is any valid combination of operators and atoms. An atom is something that has a value. So all of these are atoms in Python: identifiers, literals and values-in-enclosures such as parentheses, brackets etc. >> The type of operators and operands used in an expression determine the expression type. >>An expression can be compound expression too if it involves multiple types of operators.

Different types of expressions in python are:

(1)Arithmetic expression: It Involve numbers and arithmetic operators. Ex: 2+3**5

(2)Relational expression: It involves variables and relation operators. Ex: X >Y , y!=z

(3)Logical expression : It involves variables and logical operators .Ex :a or b

(4)String expression : Only two operators * and + can be applied on strings. For example : “and” + “then” will print and then “and” + 2 will print andand

In a mixed arithmetic expression python converts all operands up to the type of the largest operand which is called type promotion.

Evaluating Arithmetic Expression : To evaluate an arithmetic expression, Python follows these rules: >> Determines the order of evaluation in an expression considering the operator precedence. For Example: (i) a,b = 3,6 c=b/a c=6/3 c= 2.0 (Here the operator is / ,which always gives floating point result) (ii)a,b= 3,6 c=b//a c=6//3 c=2 (Here the operator is // , which always gives integer result)

Evaluating Relational Expression : All relational expressions yield Boolean values only i.e. True or False. All comparisons operations in Python have the same priority, which is lower than that of any arithmetic operations. For Example:

(i)What will be the output of the following code when the inputs are?

(a) a= 10,b=23,c=23 (b)a=23,b=10,c=10

print(a

print(b<=c)

print(a

For input combination (a) the output would be :

True

True

True

For input combination (b) the output would be :

False

True

False

Evaluating Logical Expression: Python follows these rules while evaluating Logical expressions:

(i) The precedence of logical operators is lower than the arithmetic operators.

(ii) The precedence of logical operators among themselves is not, and, or. So the expression a or b and not c will be evaluated as:

(a or (b and (not c) ) )

Important : While evaluating, Python minimizes internal work by following these rules:

(a)In or evaluation, Python only evaluates the second argument if the first one is false.

(b) In and evaluation, Python only evaluates the second argument if the first one is true.

For Example , In expression (3<5) or (5<2), since first argument is true , simply its result is returned as overall result.

TYPE CONVERSION Converting one data type to another is known as .It is of two types. 1. Implicit type conversion: It is done by the compiler without programmers Intervention. An implicit type conversion is applied generally whenever different data types are intermixed in an expression, so as not to lose information. Python converts all operands up to the type of the largest operand. It is also known As type promotion.

Example: ch=5 I=2 db=5.0 A= ((ch + I) / db ) int + int ---- int int / float ------ will result in float , so there is no loss of information. 2.Explict type conversion : It is user defined conversion that forces an expression to be of specific type . It is also known as type casting. Example : if we have a = 3 and b= 5.0 int(b)------will make the data type of expression as int D = float(a)------will make the data type of expression as float 3.0 A= 10 float(A)

Using random Module Python has a module namely random that provides random number generators. A random number in simple words means -----a number generated by chance, i.e. randomly. To use random number generators you need to import module random using import command. e.g. import random

The most common random number generator functions in random module are: random()----It returns a random floating point number N in the range(0.0,1.0). randint(a,b)------It returns a random integer N in the range (a,b) i.e.a<=N<=b. randrange---It returns random numbers from range start….stop with step value.

Example 1-To generate a random floating-point number between 0.0 to 1.0, simply use random(): >>>import random >>>print(random.random()) 0.0234678(Any number between range 0.0 to 1.0)

Example 2-To generate a random floating point number between range lower to Upper using random( )

(a) multiply random() with difference of upper limit and lower limit.

(b) add to it lower limit

>>>import random

>>>print(random.random()*(35-15) + 15)

28.5678344(The output generated is any number between the range 15 to 35 )

Example 3- To gererate a random integer number in range 15 to 35 using randint( ), write :

>>>print(random.random(15,35))

18 (Any number between range 15 to 35)