logo

Python Variable Types


Show

Variables are said to be nothing but considered as reserved memory locations to store values. This depicts that when you create or develop a variable you reserve the little space in memory.

Depending on the data kind of a variable, the interpreter assigns memory and determines what could be stored in the reserved memory. Henceforth, by allocating different data kinds to variables, you could store integers, decimals or characters in all such variables.

Assigning Values to Variables

Python variables never require an explicit declaration to store memory space. The declaration occurs mechanically when you dedicate a value to a variable. The equal sign (=) is utilized to assign values to variables.

The quantity to the left of the = operator is the sanction of the variable and the operand to the correct of the = operator is the value stored in the variable. For example?

#!/usr/bin/python

counter = 100          # An integer assignment
miles   = 1000.0       # A floating point
name    = "John"       # A string

print counter
print miles
print name

Here, 100, 1000.0, and "John" are the values assigned to counter, miles, and name variables, respectively. Does this produce the following result?

100
1000.0
John

Multiple Assignment

Python authorizes you to allocate a single value to various variables at the same time. For example?

a = b = c = 1

Here, an integer object is developed with the value 1, and all these three variables are delegated to the same memory reserve or location. You could also allocate multiple objects to various variables. For instance?

a,b,c = 1,2,"john"

Here, two integer objects designating with the values of 1 and 2 are allotted to variables a and b respectively. However, one string object with the value "john" is delegated to the variable c.

Standard Data Types

The data stored in memory can be of numerous types. For illustration, a person's age is stored as a numeric value, and an individual's address is reserved as alphanumeric characters. Python has respective standard data types that are utilized to define the operations accomplished on them and the storage method for each of them.

Does Python have 5 standard data types?

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

Python Numbers

Number data types store numeric values. Number objects are developed when you allotted a value to them. For instance?

var1 = 1
var2 = 10

You could also delete the reference to a number object by utilized the del statement. The syntax of the del statement is ?

del var1[,var2[,var3[....,varN]]]]

Users can delete a single object or multiple objects by utilizing the del statement. For example?

Does python render four various numerical types?

  • int (signed integers)
  • long (long integers, they could also be represented in octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers)

Examples

Here are few examples of numbers?

int

long

float

complex

10

51924361L

0.0

3.14j

100

-0x19323L

15.20

45.j

-786

0122L

-21.9

9.322e-36j

080

0xDEFABCECBDAECBFBAEl

32.3+e18

.876j

-0490

535633629843L

-90.

-.6545+0J

-0x260

-052318172735L

-32.54e100

3e+26J

0x69

-4721885298529L

70.2-E12

4.53e-7j

    • Python authorizes users to utilize a lowercase with a long tail, however, it is recommended that utilize only an uppercase L to confront confusion with the number 1. Python shows long integers with an uppercase L.
    • An analyzable number comprises an ordered pair of actual floating-point numbers designated by x + yj, where x and y are assumed to be the actual numbers along with j is one of the imaginary units.

Python Strings

Strings in Python are identified as an immediate set of characters stand for in the quotation marks. Python authorizes either pair of single or double-quotes. Subsets of strings could be accepted through the slice operator ([ ] and [:] ) with indexes creating at 0 at the starting of the string and toiling their way from -1 at the end.

The plus (+) sign is the string connection operator and the asterisk (*) is the repetition operator. For instance?

#!/usr/bin/python

str = 'Hello World!'

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 + "TEST" # Prints concatenated string

This will produce the following result?

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python Lists

Lists are the fewest versatile of Python's compound data types. A list comprises items abstracted by commas and enveloped within square brackets ([]). To some extent, lists are akin to arrays in C. One quality between them is that all the items belonging to a list can be of antithetic data type.

The values stored in a listing can be accessed exploitation the slice operator ([ ] and [:]) with indexes beginning at 0 at the starting of the list and working their way to end -1. The plus (+) sign is the list connection operator, and the asterisk (*) is the repetition operator.

For example?

#!/usr/bin/python

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd till 3rd 
print list[2:]      # Prints elements starting from 3rd element
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists

Does this produce the following result?

['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Python Tuples

A tuple is a sequence data kind that is akin to the list. A tuple comprises a number of values separated by commas. Dissimilar lists, however, tuples are boxed within parentheses.

The primary dissimilarities between lists and tuples are: Lists are enveloped in brackets ( [ ] ) and their elements and size can be modified, while tuples are enveloped in parentheses ( ( ) ) and never be updated. Tuples can be content as read-only lists. For example?

#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print tuple           # Prints complete list
print tuple[0]        # Prints first element of the list
print tuple[1:3]      # Prints elements starting from 2nd till 3rd 
print tuple[2:]       # Prints elements starting from 3rd element
print tinytuple * 2   # Prints list two times
print tuple + tinytuple # Prints concatenated lists

Does this produce the following result?

('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The following code is fallacious with tuple because we attempted to update a tuple, which is not authorized. A similar case is accomplished with lists?

('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

Python Dictionary

Python's dictionaries are a type of hash table type. They activity like associative displays or hashes found in Perl and consist of key-value pairs. A dictionary key can exist in all versions of Python. All the Python type is considered but is usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enveloped by curly braces ({ }) and values can be allotted and accessed utilizing square braces ([]). For example?

#!/usr/bin/python

dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print dict['one']       # Prints value for 'one' key
print dict[2]           # Prints value for 2 key
print tinydict          # Prints complete dictionary
print tinydict.keys()   # Prints all the keys
print tinydict.values() # Prints all the values

Does this produce the following result?

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Dictionaries have no idea of order among elements. It is wrong to say that the elements are "out of order"; they are merely unordered.

Data Type Conversion

Formerly, you may demand to execute conversions between the built-in types. To person between types, you merely use the type name as a function.

There are respective built-in functions to execute conversion from one data type to another. These functions instrument a new object representing the converted value.

Sr.No.

Function & Description

1

int(x [,base])

Converts x to an integer. base specifies the base if x is a string.

2

long(x [,base] )

Converts x to a long integer. base specifies the base if x is a string.

3

float(x)

Converts x to a floating-point number.

4

complex(real [,imag])

Creates a complex number.

5

str(x)

Converts object x to a string representation.

6

repr(x)

Converts object x to an expression string.

7

eval(str)

Evaluates a string and returns an object.

8

tuple(s)

Converts s to a tuple.

9

list(s)

Converts s to a list.

10

set(s)

Converts s to a set.

11

dict(d)

Creates a dictionary. d must be a sequence of (key,value) tuples.

12

frozenset(s)

Converts s to a frozen set.

13

chr(x)

Converts an integer to a character.

14

unichr(x)

Converts an integer to a Unicode character.

15

ord(x)

Converts a single character to its integer value.

16

hex(x)

Converts an integer to a hexadecimal string.

17

oct(x)

Converts an integer to an octal string.

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.