Python Variables and Data Types

Python Variables and Data Types

 

In this section we will learn about different types of variables, their use and rules for naming variable in Python.

 

Python Variables

A variable is a named memory location use to store some data or value. A variable provides us with named storage that our programs can manipulate. In python it is not necessary to declare a variable before using it.

The variable is only defined in Python or the variable is assigned a value only in Python. By definition we mean to assign a value to a variable. In python the data type of the variable is also not declared. It is decided by the Python interpreter that this variable has which type integer, float or some else. This is determined according to the value that is assigned to the variable. If the value assigned to variable is in decimal or fraction then the variable will be of float data type and if a simple integer is assigned to the variable then variable will be considered to be of integer data type.

 

Rules for naming variables

  1. Names of variable can contain letters both upper case and lowercase from (a-z) or (A-Z). A variable name can also contain underscore (_). Underscore is used to clarify the name of the variable for example my_file is clearer than myfile.
  2. We cannot start a variable name from a digit or number for example 3file is invalid but file3 is valid.
  3. We cannot use the keywords as the names of variables. Consider the following example to demonstrate this:

                            >>> while = 1

                            SyntaxError: invalid syntax

asd

  1. Special symbols cannot be used as the name or between the names of variables such as &, #, $, %, etc. Consider the following example:

                          >>> asd$ = 1

                         SyntaxError: invalid syntax

while

  1. Variables names can be of any length.
  2. Blank spaces are not allowed in the name of a variable.

 

Variable assignment

The assignment operator (=) is used to assign a value to a variable. A value of any data type can be assigned to a variable in Python. Consider the following example in which there are three variables and are assigned different types of values:

x = 2

y = 3.4

z = “World”

In the above three statements there are three variables. First variable is assigned a value 2 which is an integer and hence the variable itself becomes an integer type variable. Second variable is assigned a value 3.4 which is a float type value as it has a decimal part and hence the variable is declared to be of float data type. Third variable is assigned a string that is WORLD therefore this variable is of character data type as string is a sequence of characters.

 

Multiple assignments

In python we can assign values to multiple variables in one line. Consider the following example:

x, y, z = 2, 3.4, “World”

In the above example 2 is assigned to x, 3.4 is assigned to y and world is assigned to z.

A same value can also be assigned to multiple variables in one single line at once. Consider the following example:

x = y = z = “world”

In this way world is assigned to three variables x, y and z.

 

Data Types in Python

In Python every variable is considered to be an object and the data types of these variables are considered to be the classes. Therefore, in Python every value and variable has it data type. Some of the data types in Python are given below:

 

Python Numbers

Numbers consist of integer type number, floating point numbers or complex numbers (that have an imaginary part). In Python numbers’ category, integers, floating point numbers and complex numbers fall. These are written as data types as int, float and complex respectively. To determine the data type of a variable in Python type () function is used and to determine that he variable or object belongs to which class isinstance () function is used. Consider the following example:

CODE

>>> x = 2

>>> print(x, “Data type of x is”, type(x))

>>> x = 3.4

>>> print(x, “Data type of x is”, type(x))

>>> x = 1 + 5j

>>> print(x, “Is x a complex number?”, isinstance(1+5j, complex))

OUTPUT

2 Data type of x is <class ‘int’>

3.4 Data type of x is <class ‘float’>

(1+5j) Is x a complex number? True

first-line-x

In the above example, in first line x is assigned a value 2 and when type () function is called it tells the user that x is of integer data type. In the second line x is assigned a value 3.4 and when the type () function is executed it tells the user that the variable x is of float data type now. In the third line we assigned a complex number to x and called the function is instance () which returns a True if the number is complex and returns false if the number is not complex.

In Python we can write integers of any length. The length will be set by the internal memory available to store the variable. Whereas, the floating point number should be of 15 places after the decimal point. The difference between an integer and a floating point variable is that integer does not consist of decimal point that is 2 is an integer and 2.0 is a floating point number. The complex numbers have two parts one is the real part and the other is imaginary part. The following is a complex number:

x + yj

Where x is the real part and y is the imaginary part.

 

Python list

A list is a number of items that has certain sequence. In the python list we can use items of different data types. The items in the list are separated by commas and are enclosed within square brackets. The strings in the list are enclosed within single quotes.

Consider the following example in which a list of items of different data types is initialized.

x = [2, 3.4, ‘hello’]

In python the index of the list starts from 0 and to refer to any element of the list square bracket [] is used and is called slicing operator. Consider the following example in which we are printing any of the elements in the list using the slicing operator:

CODE

>>> x = [2, 3, 5, 7, 1, 8, 9]

>>> print(“The item on the index 3, x[3] = “, x[3])

OUTPUT

The item on the index 3, x[3] =  7

the-item-on-the-index-3

The values of the items of list can be changed and hence they are called mutable. Consider the following example in which the value of an item is changed:

CODE

>>> x = [4, 5, 6]

>>> x[1]=3

>>> x

OUTPUT

[4, 3, 6]

4-3-6

 

Python Tuple

A tuple is the same as a list and tuple is an organized list of items. The elements in a tuple have a sequence. The difference between a tuple and a list is that a tuple cannot be altered and hence it is immutable.

As the tuple cannot be changed therefore, they are used to protect data so that the data cannot be changed by the user dynamically. A tuple id defined within parenthesis () and the items are separated by a comma. Consider the following example in which a tuple is being initialized:

x = (2, ‘hello’, 3+4j)

The items can be extracted from a tuple by using the slicing operator []. The value cannot be changed. Consider the following example in which we have extracted values from a tuple and printed them also the index is started from 0:

CODE

>>> x = (2, ‘hello’, 4+2j)

>>> print(“The item of tuple on index 1, x[1] = “, x[1])

>>> x[0] = 12

OUTPUT

The item of tuple on index 1, x[1] =  hello

Traceback (most recent call last):

File “<pyshell#10>”, line 1, in <module>

x[0] = 12

TypeError: ‘tuple’ object does not support item assignment

tuple

In the above example, it can be seen that an error is generated when we tried to change the value of tuple at index 0.

The item is extracted successfully.

 

Python Strings

A string consists of a number of characters arranged in some sequence. A string can also have spaces. Single quotes or double quotes can be used to represent a string whereas multiple strings can be represented by triple quotes.

Consider the following example in which a variable is being initialized with a string and another variable is initialized with multiple line string:

x = “A string”

x = ”’Multiple line string

In python strings cannot be changed that is they are immutable. To extract a character from a string slicing operator is used and index is started from 0.

Consider the following example:

CODE

>>> x = ‘This is a string’

>>> print(“The character at index 3, x[3] = “, x[3])

>>> x[6] = ‘a’

OUTPUT

The character at index 3, x[3] =  s

Traceback (most recent call last):

File “<pyshell#13>”, line 1, in <module>

x[6] = ‘a’

TypeError: ‘str’ object does not support item assignment

str

It can be seen in the above example that a character is extracted successfully from the string but when we tried to change the string an error is generated just like a tuple.

 

Python Set

A set is unique collection of items that are not in an order. The items of a set are separated by comma and are enclosed in braces {}.

Consider the following example in which a variable is being initialized as a set and we have printed the whole set:

CODE

>>> x = {2, 5, 3, 1, 6}

>>> print (“The set x  “, x)

OUTPUT

The set x   {1, 2, 3, 5, 6}

the-set-x

Here is another example in which the data type of the variable is determined:

CODE

>>> x = {2, 5, 3, 1, 6}

>>> print(“The set x  “, x)

>>> print(type(x))

OUTPUT

The set x   {1, 2, 3, 5, 6}

<class ‘set’>

class-set

In the above example the type function with an argument that is the variable whose data type was to be determined is called.

In python we can also perform the set operations such as union, intersection, etc. If the user has written repeated values in a set then the interpreter will only display the unique values. Consider the following example:

CODE

>>> x = {1, 1, 4, 4, 7, 5, 4, 2, 1, 7}

>>> x

OUTPUT

{1, 2, 4, 5, 7}

1-2-4-5-7

On sets there is no use of slicing operator or indexes because a set is an unordered sequence of list.

Consider the following example in which when we tried to use slicing operator or indexes to extract an item from list an error is generated:

CODE

>>> x = {1, 4, 5}

>>> x[2]

OUTPUT

Traceback (most recent call last):

File “<pyshell#22>”, line 1, in <module>

x[2]

TypeError: ‘set’ object does not support indexing

set

 

Python Dictionary

A dictionary in Python is an unordered collection of the key value pairs. Each key in the dictionary and a value as pair are separated by a colon as key: value.

The whole is enclosed within curly brackets.

The keys within the dictionary are unique but the values are not unique. The keys in the dictionary are immutable that is they cannot be changed just like strings. Consider the following example in which a variable is being initialized with a dictionary and the data type of variable is also determined:

CODE

>>> x = {1:’value’, ‘key’:2}

>>> type(x)

OUTPUT

<class ‘dict’>

class-dict

Consider the following example in which indexing is used to extract an item:

CODE

x = {1:’value’, ‘key’:2}

>>> type(x)

>>> print(“x[1] = “, x[1])

>>> print(“x[‘key’] = “, x[‘key’])

>>> print(“x[2] = “, x[2])

OUTPUT

<class ‘dict’>

x[1] =  value

x[‘key’] =  2

Traceback (most recent call last):

File “<pyshell#35>”, line 1, in <module>

print(“x[2] = “, x[2])

KeyError: 2

keyerror

In the above example we used keys to print the values, in the above example 1 and key are the keys and value and 2 are values. Hence the error was generated because value was used instead of key.

 

Conversion Between Data Types

In Python the data types can be converted to other data types using the conversion functions. Some of the conversion data types functions are float (), int (), etc. Consider the following example in which we converted an integer type nu,ber to float data type:

CODE
>>> float(8)

OUTPUT

8.0

8

The conversion from float data type to integer data type will truncate the value. Consider the following example:

CODE

>>> int(3.7)

>>> int(-3.7)

OUTPUT

3

-3

3

If you want to convert a string value to another data type then you should write the value in the specified format. We cannot convert a character or a string data type to integer and float data types. Consider the following example:

CODE

>>> float(‘3.7’)

>>> str(2)

>>> int(‘q’)

>>> float(‘l’)

OUTPUT

3.7

‘2’

Traceback (most recent call last):

File “<pyshell#45>”, line 1, in <module>

int(‘q’)

ValueError: invalid literal for int() with base 10: ‘q’

Traceback (most recent call last):

File “<pyshell#46>”, line 1, in <module>

float(‘l’)

ValueError: could not convert string to float: ‘l’

valueerror

In Python we can also convert one type of sequence to another type of sequence for example a set to a tuple etc. Consider the following example:

CODE

>>> set ([2, 6, 3])

>>> tuple ({5, 3, 4})

>>> list (‘Python’)

OUTPUT

{2, 3, 6}

(3, 4, 5)

[‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

converted-a-list-sequence

In the above example first we converted a list sequence to a set, then a set to a tuple and at the end a string to list.

We can also convert a list to a dictionary but to do this each element should be in pair. Consider the following example:

CODE

>>> dict ([[3,5], [6,7]])

>>> dict ([(3,7),(2,9)])

OUTPUT

{3: 5, 6: 7}

{2: 9, 3: 7}

dict