# Python Chapter#2: Variable Types

Ankur Kulhari

A variable is associated with pair of a storage location and associated symbolic name (an identifier), i.e. [location,identifier].

• Location is used by system and identifier is used by user/programmer to access the variable
• When a variable is created, some space in memory is reserved
• Data type of a variable decides, the amount of reserved memory and what can be stored in the reserved memory
• In python type of variable is decided based on the value it is assigned
• According to the type of variable, operations which can be performed on it are decided
• Ex:

```num   = 100          # An integer value assignment
dec   = 100.0        # A floating point
name  = &amp;quot;Jonny&amp;quot;      # A string
x = y = z = 100      # Multiple assignment
a,b,c = 100,100.0,&amp;quot;Jonny&amp;quot;    # Multiple assignment
print (num)
print (dec)
print (name)
print (&amp;quot;x: &amp;quot;,x,&amp;quot; y: &amp;quot;,y,&amp;quot; z: &amp;quot;,z)
print (&amp;quot;a: &amp;quot;,a,&amp;quot; b: &amp;quot;,b,&amp;quot; c: &amp;quot;,c)
```

OUTPUT:

```100
100.0
Jonny
x:  100  y:  100  z:  100
```
##### Standard Data Types

Python has five standard data types −

1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
##### Python Numbers

Number data types store numeric values. Number objects are created when a value is assigned to them.
Ex:

```num1 = 5
num2 = 10
```

Four different numerical types are supported in python:

1. int (signed integers)
2. long (long integers, they can also be represented in octal and hexadecimal)
3. float (decimal/real values)
4. complex (complex numbers)
###### Mathematical Functions

Python includes following functions for numbers:

abs(x), math.ceil(x), cmp(x, y), exp(x), fabs(x), math.floor(x), math.log(x), math.log10(x), max(x1, x2,…), min(x1, x2,…), math.modf(x), pow(x, y), round(x, n), math.sqrt(x).

###### Random Number Functions

Python includes following functions that are widely used. You have to import random library to use these functions.
choice(seq), random.randrange (start, last, step), random.random(), random.seed(x), random.shuffle(list), uniform(x, y).

###### Trigonometric Functions

In python trigonometric functions are avaiabe in math ibrary.
math.acos(x), math.asin(x), math.atan(x), math.atan2(y, x), math.cos(x), math.hypot(x, y), math.sin(x), math.tan(x), math.degrees(x), math.radians(x).

###### Mathematical Constants

In python pi and e are the two mathematical constants. They can be used as math.pi and math.e.

##### Python Strings

In Python character type variables are not defined; they are treated as strings of length one.

• Strings in Python are set of characters enclosed in the pair of quotation marks (either single or double quotes).
• Slice operator ([ ] and [:] ) can be used to take subset of string
• Indexes start at 0
• Concatenation operator: plus (+) sign
• Repetition operator: asterisk (*)

Ex:

```str = &amp;quot;Hello world!&amp;quot;
print(str)          # Prints complete string
print(str)       # Prints 1st character of the string
print(str[2:5])     # Prints 3rd to 5th characters of the str
print(str[2:])      # Prints rest of the string from 3rd character
print(str * 2)      # Prints string twice
print(str + &amp;quot;TEST&amp;quot;) # Prints concatenated string
```

OUTPUT:

```Hello world!
H
llo
llo world!
Hello world!Hello world!
Hello world!TEST
```
###### Triple Quotes

Row strings are defined by enclosing string within triple, single quotes or double quotes. While printing the tabs, new lines are also displayed. Ex:

```para_str = &amp;quot;&amp;quot;This shows how triple quotes been executed.
It shows how multiple lines and non-printable symbols such as
TAB (\t), NEWLINEs [\n]are displayed.&amp;quot;&amp;quot;&amp;quot;
print (para_str)
```

OUTPUT:

```This shows how triple quotes been executed.
It shows how multiple lines and non-printable symbols such as
TAB (	), NEWLINEs [
]are displayed.
```
###### Built-in String Methods

Python includes the following built-in methods/functions to manipulate strings:
len(string), find(str, beg, end), rfind(str, beg, end), index(str, beg, end), rindex( str, beg, end), max(str), min(str), startswith(str, beg, end), endswith(suffix, beg, end), join(seq), count(str, beg, end), capitalize(), swapcase(), lower(), upper(), split(“str”, num), splitlines(num), strip(), lstrip(), rstrip(), replace(old, new, max), ljust(width, fillchar), rjust(width, fillchar), zfill (width), title(), center(width, fillchar), isalnum(), isalpha(), isdigit(), islower(), isnumeric(), isdecimal(), isspace(), istitle(), isupper().

##### Python Lists

A list in python is a compound data type which can store multiple elements.

• Items of a list are enclosed within square brackets ([])
• Items are separated by commas
• The items of a list can be of different data type.
Ex: l1 = [1,2,”a”,2.3,3j]
• Slice operator ([ ] and [:] ) can be used to access elements in a list. Negative index: count from the right. Ex: print(l1[-2]) returns 2.3
• Indexes start at 0
• Concatenation operator: plus (+) sign. Ex: [1, 2, 3] + [4, 5, 6]returns [1, 2, 3, 4, 5, 6]
• Repetition operator: asterisk (*). Ex: [‘Hi!’] * 4 returns [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]
• len(list) returns the number of elements in the list. Ex: len([1, 2, 3]) returns 3
• in operator returns the membership of an element in a list. Ex: 3 in [1, 2, 3] returns True
• ```l1 = [1,2,&amp;quot;a&amp;quot;,2.3,3j]
l2 = [567, &amp;quot;jonny&amp;quot;]
print(l1)          # Prints all the elements of list
print(l1)       # Prints 1st elements of the list
print(l1[1:3])     # Prints elements from 2nd till 3rd
print(l1[2:])      # Prints all the elements of l1 from 3rd value
print(l2 * 2)      # Prints list l2 twice
print(l1 + l2)     # Prints concatenated lists
l1=3            # Updates 3rd element of the list
print(l1)       # Prints updated 3rd element of the list
del l1          # Deleting 3rd element of the list
print(l1)
```

OUTPUT:

```[1, 2, 'a', 2.3, 3j]
1
[2, 'a']
['a', 2.3, 3j]
[567, 'jonny', 567, 'jonny']
[1, 2, 'a', 2.3, 3j, 567, 'jonny']
3
[1, 2, 2.3, 3j, 567, 'jonny']
```
###### Built-in List Functions & Methods:

Functions defined for lists in python:
cmp(list1, list2), len(list), max(list), min(list), append(obj), count(obj), extend(seq), index(obj), insert(index, obj), pop(index), remove(obj), reverse(), sort().

##### Python Tuples: Read only List

A tuple in python is also a compound data type which can store multiple elements.

• Tuples are almost same as list except that, elements of a tuple can not be changed like list.
• Items of a tuple are enclosed within round brackets (())
• Items are separated by commas
• The items of a tuple can be of different data type.
Ex: t1 = (1,2,”a”,2.3,3j)
• Slice operator ([ ] and [:] ) can be used to access elements in a tuple. Negative index: count from the right. Ex: print(l1[-2]) returns 2.3
• Indexes start at 0
• Concatenation operator: plus (+) sign
• Repetition operator: asterisk (*)

To write a tuple containing a single value you have to include a comma, even though there is only one value:
tup1 = (50,);
Ex:

```t1 = (1,2,&amp;quot;a&amp;quot;,2.3,3j)
t2 = (567, &amp;quot;jonny&amp;quot;)
print(t1)          # Prints all the elements of list
print(t1)       # Prints 1st elements of the list
print(t1[1:3])     # Prints elements from 2nd till 3rd
print(t1[2:])      # Prints all the elements of l1 from 3rd value
print(t2 * 2)      # Prints list l2 twice
print(t1 + t2)     # Prints concatenated lists
t1=3            #updates 3rd element of the list
print(t1)       #prints updated 3rd element of the list
```

OUTPUT:

```Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/Python/1.py", line 9, in <module>
t1=3            #updates 3rd element of the list
TypeError: 'tuple' object does not support item assignment
```
###### Basic Tuples Operations
• len(): returns the length of tuple. Ex: len((1,2,3)) returns 3.
• +: Concatenation operation. Ex: (1, 2, 3) + (4, 5, 6) results (1, 2, 3, 4, 5, 6)
• *: Repetition. Ex: (‘Hi!’,) * 4 results (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’)
• in: Membership operation. Ex: 3 in (1, 2, 3) results True
• for: Iterationt operation. Ex: for x in (1, 2, 3): print (x), results 1 2 3
• cmp(tuple1, tuple2): Compares elements of both tuples.
• max(tuple): Returns item from the tuple with max value.
• min(tuple): Returns item from the tuple with min value.
• tuple(seq): Converts a list into tuple.
##### Python Dictionary

Lets understand the basic functionalities of dictionaries with an example:

```d1 = {}
d1 = &amp;quot;Hello&amp;quot;
d1[&amp;quot;World&amp;quot;] = 123
d2 = {&amp;quot;;name&amp;quot;: &amp;quot;jonny&amp;quot;,&amp;quot;Employee_code&amp;quot;:6103467, &amp;quot;dept&amp;quot;: &amp;quot;CSE&amp;quot;}
print(d1)         # Prints value for 'one' key
print(d1[&amp;quot;World&amp;quot;])     # Prints value for 2 key
print(d2)              # Prints complete dictionary
print(d2.keys())       # Prints all the keys
print(d2.values())     # Prints all the values
```

OUTPUT:

```Hello
123
{'Employee_code': 6103467, 'dept': 'CSE', 'name': 'jonny'}
dict_keys(['Employee_code', 'dept', 'name'])
dict_values([6103467, 'CSE', 'jonny'])
```
###### Python Dictionary Functions

cmp(dict1, dict2), len(dict), str(dict), type(variable), clear(), copy(), fromkeys(seq,Value), get(key, default), has_key(key), items(), keys(), setdefault(key, default), update(d2), values(), del dict[‘Name’], dict.clear(), del dict, dict.has_key(key), dict.items(), dict.keys(), dict1.update(dict2), dict.values().