We now have a youtube channel. Subscribe!

Python Variables and Data Types



Hello dear readers! Welcome back to another edition of our tutorial on Python. In this tutorial guide, we are going to be discussing about Python variables and data types.

Variables are reserved memory locations used in storing values. This means that when you create a variable, you reserve some space in memory.

Based on data type of a variable, the interpreter allocates memory and decides what can be stored in it. Therefore, by assigning other data types to these variables, you can then store decimals, integers, and characters in these variables.

Assigning Values to Variables

Variables in Python do not need explicit declaration to reserve the memory location. The declaration just happens automatically when you assign a value to a variable. The equal sign(=) is used to assign values to a variable.

RECOMMENDED POST: Python Basic Syntax Tutorial

The operand to the left of the equal (=) operator is the variable name and the operand to the right of the equal ( = ) operator is the value stored in the variable.

Example

Below is a very brief example -

#!/usr/bin/python

counter = 200          # An integer assignment
miles   = 3000.0       # A floating point
name    = "kennedy"       # A string

print counter
print miles

Here 200, 3000.0 and "Kennedy" are the values that are assigned to counter, miles, and name variables, respectively.

Output

It produces the following output -

200
3000.0
kennedy

Multiple Assignment

Python lets you to assign a single value to multiple variables at the same time. For example -

x = y = z = 1

Here an integer object is created with the value 1, and all the three variables are assigned to the same memory space. You can as well assign multiple objects to multiple variables. For example -

x ,y ,z = 1, 2,  "paul"

Here, two integer objects with the values 1 and 2 are assigned to the variables a and b respectively, and one string object with value "paul" is assigned to the variable c.



Python Data Types

Data stored in a reserved memory can be of different types. For example, a person's age is stored as a numeric value while his/her address is stored as alphanumeric characters. Python has support for various data types that are used to define the operations possible on them and the storage method for each of them.

Python has five standard data types -

  • String
  • Numbers
  • Turple
  • List
  • Dictionary

Python Strings

Strings in Python are identified as contiguous set of characters that are represented in quotes. Python allows either pairs of a single or double quotes. Subsets of strings can be taken by using the slice operator ([] or [:]) with the indexes starting at 0 in the beginning of the string and working their way from -1 at the end.

The plus (+) sign here is the string concate operator and the asterisk (*) is the repetition operator.

Example

Following below is a short example -

#!/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 output -

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


Python Numbers

The number data types are used for storing numeric values. The number objects are created when you assign a value to them. For example -

var1  =  1
var2  =  10

You can also delete the reference to a number object by making use the del statement. The syntax of a del statement is -

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

You can delete a single object or even multiple objects by using the del statement. For example -

del  var
del  var_a,  var_b

Python have support for four types of numerical values -

  • int (signed integers)
  • float (floating point real values)
  • complex (complex numbers)
  • long (long integers)

Example

Following below are few examples -

intlongfloatcomplex
1051924361L0.03.14j
100-0x19323L15.2045.j
-7860122L-21.99.322e-36j
0800xDEFABCECBDAECBFBAEl32.3+e18.876j
-0490535633629843L-90.-.6545+0J
-0x260-052318172735L-32.54e1003e+26J
0x69-4721885298529L70.2-E124.53e-7j

  • Python allows you to use a lowercase l with long, but it is recommended that you make use of only uppercase L to avoid confusion with the number 1.
  • A complex number consists of an ordered pair of real floating point numbers that is denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.



Python Turple

Turple is another sequence that is similar to a list. A turple consists of a number of values which are separated by commas. Turples are enclosed within parentheses.

The major distinct between a lists and turples are: Lists are enclosed in brackets ( [] ) and their elements & size can be changed, but turples are enclosed in parentheses ( () ) and can not be changed. Turples can be thought of as a read-only lists. For example -

#!/usr/bin/python

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

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

This will produce the following output -

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

Below code is invalid with turple, because we attempted to update a turple, which isn't allowed. Similar case is possibe while using lists -

#!/usr/bin/python

tuple  =  ( 'abcd',  786 ,  2.23,  'paul',  70.2  )
list  =  [ 'abcd',  786 ,  2.23,  'paul',  70.2  ]
tuple[2] = 1000    # Invalid syntax with tuple
list[2] = 1000     # Valid syntax with list



Python Lists

A list contains items separated by commas and then enclosed within square brackets ( [] ). 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 type.

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

#!/usr/bin/python

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

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

This will produce the following output -

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


Python Dictionary

Dictionaries are kind of hash table type. They function like associated arrays or hashes that are found in Perl and consist of key value pairs. A dictionary key can be almost any Python data type, but are usually numbers or strings. Values on the other hand, could be any arbitrary Python object.

Python dictionaries are enclosed with curly braces ({}) and values can be assigned and accessed by square braces ([]). For example -

#!/usr/bin/python

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

tinydict  =  {'name':  'paul',  '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

This will produce the following output -

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

The Python Dictionaries have no concept of order among elements. It is incorrect to say the elements are "out of order"; they are simply unordered.



Data Type Conversation
At times you may need to perform conversions between built-in data types. In order to convert between data types, You simply make use of the type name as a function.

There are several built-in functions that are used for performing conversions from one data type to another. These functions returns a new object representing the value converted.

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.

Alright guys! This is where we are rounding up for this tutorial. In our next tutorial, we will be discussing about the Python Basic Operators.

Do feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain