Assigning Values in Python

In Python everything is an object. Let us try to understand how it works and what it actually means.


#!/usr/bin/python3

a = 4

def main():
    print(type(a))

if __name__ == '__main__':
    main()


So in this code, when we assign a value to ‘a’ and get that value, it actually represents the value of a class. The output of this code is
class 'int'

If we change the value and write it like this:

a = "This is a string."

The output will be :
class 'string'

Basically the assignment operator “=” creates an object when we assign a value.

There are many types of value. Like tuple, list and dictionary. Let us see how our code and output change with them.



#!/usr/bin/python3

b = 4
a = "This is a string."

x, y = 2, 5
##we are just swapping values##
x ,y  = y, x 

tuples = (1, 2, 34, 89)

lists = [1, "Goutam Budhdha", 4, 90]

dictionaries = {'a' : 4, 'b' : "Debansu is a good boy and his friend lives in Bombay Harbour.", 'c' : 8}

def main():
    print(type(a))
    print(x, y)
    print(tuples)
    print(lists)
    print(dictionaries)

if __name__ == '__main__':
    main()


And here is the output:

5, 2
(1, 2, 34, 89)
[1, 'Goutam Budhdha', 4, 90]
{'a': 4, 'b': 'Debansu is a good boy and his friend lives in Bombay Harbour.', 'c': 8}

If want to check types of the objects,


def main():
    print(type(b))
    print(type(a))
    print(type(tuples))
    print(type(lists))
    print(type(dictionaries))

if __name__ == '__main__':
    main()

we will get this output:

class 'int'
class 'str'
class 'tuple'
class 'list'
class 'dict'

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s