Python Programming – Standard Data Types

You can learn about Introduction to Python Programming Programs with Outputs helped you to understand the language better.

Python Programming – Standard Data Types

The data stored in memory can be of many types. For example, a person’s age is stored as a numeric value, and his or her address is stored as alphanu¬meric characters. Python is known as a dynamically typed language, which means that you do not have to explicitly identify the data type when you ini¬tialize a variable. Python knows, based on the value it has been given, that it should allocate memory for a string, integer, or float. It has various standard types that are used to define the operations possible on them and the storage method for each of them. It has different data types such as Number, String, List, Tuple, and Dictionary.

Note that everything is an object in Python programming; data types are actually classes and variables are instances (objects) of these classes like most other languages.

Number

Number data types store numeric values. They are immutable (value of its object cannot be changed) data types, which means that changing the value of a number data type results in a newly allocated object. Number objects are created when you assign a value to them. For example,
num1 = 5
num2 = 7
Python automatically converts different types of numbers so that you (usually) do not need to think about the compatibility of different number types. For example, if you do a mathematical operation with both integers and floats, Python converts the integers into floats and gives the result as afloat. There are three numeric types in Python: int, float, and complex. Variables of numeric types are created when you assign a value to them. To verify the type of any object in Python, use the type() function:
X = 1 # int
y = 2.8 # float
z = 1j # complex
The three numerical types of Python are discussed below:

int (integer)

Positive or negative whole numbers (without a fractional part) are called integers. Integers are of two types Integers-(signed) and Booleans. int is the basic integer data type. It is a whole number, positive or negative, without decimals, of unlimited length. It cannot hold fractional values. Examples of integer are 5, 34, 92, -43, -3255522, etc. Do not use commas to separate digits and also integers should not have leading zeroes.
The boolean type can take only one of two values, True and False. These correspond to 1 and 0. This is the most appropriate return type for a function that uses its return value to express whether some condition holds true or not.

The following integer literals are recognized by Python:

a. Decimal Integer literals (base 10): An integer literal consists of a sequence of digits. For example, 245, -96, 53, etc.

b. Octal Integer literals (base 8): An octal value can contain digits 0 to 7. 8 and 9 are invalid dig-its an octal integer. To indicate an octal number, you will use the prefix Oo or OO (zero followed by either a lowercase or uppercase letter ‘o’). For example, 004, 0ol4, etc.

c. Hexadecimal Integer literals (base 16): To indicate hexadecimal literals, you will use the prefix ‘OX’ or ‘Ox’ (zero and uppercase or lowercase letter ‘X’).

float (floating point real values)

Numbers with fractions or decimal points are called floating-point numbers. For example, 0.34, .07, -12.9, 34.2963, etc. Float numbers can be positive or negative. They can also be used to represent a number in scientific dr exponent notation. For example, -3.0 X 105 is represented as -3.0e5.

complex (complex numbers)

A complex number is an extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part. A complex number consists of an ordered pair of real floating-point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number. The imaginary part is written with a j suffix, e.g., 3+lj. Python has built-in support for complex numbers.
For example,

>>> x=3+1j
>>> print( X . real , X . imag )
3.0 1.0
There may be times when you want to specify a type for a variable. This can be done with casting. Python is an object-orientated language, and it uses classes to define data types, including its primitive types. It provides a special function called type that tells us the data type of any value.

>>> type(72)
<class ‘ int ‘ >
>>>
>>> type(“string”)
<class ‘str’>
>>>
>>> type(98.7)
<class ‘float’>
>>>
<class ‘int’> indicates that the type of 72 is int. Simi-larly, <class ‘str’> and <class ‘float’> indicate that “string” and 98.7 are of type str and float, respectively.

  • In Python, the floating-point numbers have the precision of 15 digits, i.e., double precision.

Integers and floats are data types that deal with numbers. Sometimes you need to convert an integer to a float or vice-versa. To convert integer to float, use the float() function; and to convert a float to an integer, use the int( ) function. You can also convert numbers to strings by using the str( ) method.

Let’s Try

Write datatype for the following:

>>> type ( 4 )
>>> type ( 3 . 14 )
>>> type ( 2 . 0 )
>>> a= -53
>>> type ( a )

What is typecasting?

Typecasting is a process of explicitly specifying types of variables in a programming language.

Example 2.
Program demonstrating working of typecasting.

# Program demonstrating working of typecasting
x=10
y= “2”
z=int(y) # convert string to integer using int( )
sum=x+z
print(sum)RUN
>>>
12
>>>

Sometimes you need to convert data type. For example, if you want to add two numbers in which one value of a variable is an integer, and the second is a string. Then you need to use typecasting to convert string data type into an integer before you perform addition (See Figure 3.24). Casting in Python is done using constructor functions as given below: into – It constructs an integer number from an integer literal, afloat literal (by rounding down to the previous whole number), or a string literal (provided that the string represents a whole number). For example,

x = int ( 1 )       # X will be 1
y = int ( 2 . 8 )  # Y will be 2
z = int ( ” 3 ” )  # Z will be 3

float ( ) – It constructs a float number from an integer literal, afloat literal or a string literal (provided that the string represents a float or an integer). For example,

x = float ( 1 )            # x will be 1.0
y = float ( 2 . 8 )       # y will be 2.8
z = float ( ” 3 ” )       # z will be 3.0
w = float ( ” 4 . 2 ” ) # w will be 4.2

str( ) – It constructs a string from a wide variety of data types, including strings, integer literals, and float literals. For example,
x = str ( ” s1 ” )     # x will be ‘ s1’
y = str ( 2 )           # y will be ‘ 2 ‘
z = str ( 3 . 0 )     # z will be ‘ 3 . 0 ‘

  • Converting one data type to another data type is called typecasting.

Let’s Try

What will be the output of the following float casting operations?

# float casting operations
x=float ( 5 )
y=float ( 20 . 0 )
z=float ( ” 80 ” )
print ( X )
print ( Y )
print ( Z )

Let’s Try

What will be the output of the following int casting operations?

# int casting operations
x=int ( 5 )
y=int ( 20 . 0 )
z=int ( ” 80 ” )
print ( X )
print ( Y )
print ( Z )

Let’s Try

What will be the output of the following string casting operations?

# String casting operations
x=str ( 5 )
y=str ( 20 . 0 )
z=str ( ” 80 ” )
print ( X )
print ( Y )
print ( Z )

The range of Python numbers

The range of numbers supported by Python numeric data types is discussed below:

  1. Integer numbers can be of any length, only limited by available memory.
  2. Booleans can have only two permissible values True(1) or False(0).
  3. Float numbers can be of unlimited range, depending on machine architecture.
  4. Complex numbers range is the same as floating-point numbers because the real part and imaginary part both are represented internally as float values.

Real

Real numbers, or floating-point numbers, are represented in Python according to the IEEE 754 double-precision binary floating-point format, which is stored in 64 bits of information divided into three sections: sign, exponent, and mantissa.

Sets

Python has a data type called a set. Sets work like mathematical sets. They are a lot like lists with no repeats. Sets are denoted by curly braces.

String

Strings in Python are identified as a contiguous set of characters in between quotation marks. Python allows for either pair of single or double-quotes.

Example 3.
Program demonstrating working with string

str = ‘Hello Python’
print( str ) # Prints complete string
print( str [ 0 ] ) # Prints first character of the string
print( str [ 2 : 5 ] ) # Prints characters starting from 3rd to 5th
print( str [ 2 : ] ) # Prints string starting from 3rd character
print( str * 2 ) # Prints string two times
print( str + ” PROGRAMMING ” ) # Prints concatenated stringRUN
>>>
Hello Python
H
llo
llo Python
Hello PythonHello Python
Hello PythonPROGRAMMING
>>>

So ‘hello’ is the same as “hello”. A string can have any number of characters in it, including 0. The empty string is ” (two quote characters with nothing between them). The string with length 1 represents a character in Python. The plus ( + ) sign is the string concatenation operator, and the asterisk ( * ) is the repetition operator. Strings are defined using quotes (“, ‘, or ” ” ” ).

>>> st = “Hello World”
>>> st = ‘Hello World
>>> st = ” ” ” This is a multi-line string that uses triple quotes.” ” ”
Strings can be displayed on the screen using the print function. For example:
print(“hello”) # It will print hello

  • In Python, the # symbol is used to add comments. Everything from the # to the end of the line is ignored.

Like many other popular programming languages, strings in Python are arrays of bytes representing Unicode characters. However, Python does not have a character data type; a single character is simply a string with a length of one. For example ‘a’, ‘b’, ‘c’ are strings of length one. Square brackets can be used to access elements of the string.

  • In Python, there are no limits to the number of char¬acters you can put in a string. A string, having 0 characters, is known as an empty string.

a = “hello”
print(a[1]) # it will print e
Slicing is a mechanism used to select a range of items from sequence types like list, tuple, and string. It is beneficial and easy to get elements from a range by using slice way. It requires a : (colon) which sep¬arates the start and end index of the field in square brackets.

List

Python has a basic notation of a kind of data structure called a container, which is basically any object that can contain other objects. The two main kinds of containers are sequences (such as lists and tuples) and mappings (such as dictionaries).
Lists are the most versatile form of Python com¬pound data types. A list contains items separated by commas and enclosed within square brackets ([ ]). For example,
>>> li = [” abc “, 34, 4.34, 23]
To some extent, lists are similar to arrays in C. Difference between them is that all the items belonging to a list can be of different data types (heterogeneous). The values stored in a list can be accessed using the slice operator ( [ ] and [: ] ) with indexes starting at 0 at the beginning of the list and working their way to end-1. The plus ( + ) sign is the list concatenation operator, and the asterisk ( * ) is the repetition operator.

You can access individual members of a list in the following way:
>>> li = [ “abc” , 34 , 4 . 34 , 23 ]
>>> li [ 1 ] # Second item in the list.
34
Unlike strings which are immutable, it is possible to change individual elements and the size of the list.

Tuples

A tuple is like a list whose values cannot be modified once they have been created (enclosed in regular brackets). In other words, the tuple is immutable. Another way to think about tuples is to consider them to be a constant list. Tuples have elements that are indexed starting at 0. Items in a tuple are accessed using a numeric index.
>>> x = ( ‘ Vivek ‘ ,  ‘ Abhishek ‘ ,  ‘ Arti ‘ )
>>> print( x [ 2 ] )
Arti
>>> y = (1 , 9 , 2 )
>>> print ( y )
( 1 ,  9 ,  2 )
>>> print ( max ( y ) )
9

Dictionary

Dictionaries are Python’s most powerful data col-lection. Dictionaries store a mapping between a set of keys and a set of values. They allow us to do fast database-like operations in Python. They literals use curly braces and have a list of key : value pairs. You can make an empty dictionary also. Dictionaries are written like this:
>>> pword = { ‘Amit’ : ‘chuck’ , ‘Beena’ : ‘permit’, ‘Deepak’: ‘grant’}
>>> print(pword)
{ ‘Amit’ : ‘chuck’ , ‘Beena’ : ‘permit’, ‘Deepak’: ‘grant’}
>>> ooo = {  }
>>> print(ooo)
{ }

Dictionaries consist of pairs (called items) of keys and their corresponding values. In this example, the names are the keys and the passwords are the val¬ues. Each key is separated from its value by a colon (:); the items are separated by commas and the whole thing is enclosed in curly braces. An empty dictionary (without any items) is written with just two curly braces, like this: {}.

Sets

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces or the set( ) function can be used to create sets. To create an empty set, you have to use set( ), not { }; the latter creates an empty dictionary, a data structure that you discussed earlier, fruits = { ” apple ” ,  ” banana ” , ” cherry ” } print ( fruits )
{ ‘ cherry ‘ , ‘ banana ‘ , ‘ apple ‘ }
The setlist is unordered, so the items will appear in random order. The items in the set are not dis¬played in the order that they were defined. Sets, like dictionaries, do not maintain a logical ordering. The order in which items are stored is determined by Python, and not by the order in which they were provided. Therefore, it is invalid and makes no sense to access an element of the set by an index value.

  • A set is a collection that is unordered and unin¬dexed. In Python, sets are written with curly brackets.

సంతృప్తిని మించిన సంపద లేదు

Leave a Reply

Your email address will not be published. Required fields are marked *