Data Types and Variables in Python

  • By
  • July 26, 2019
  • Python
Data Types and Variables in Python

Data Types and Variables in Python

Python is one of the most famous programming languages nowadays. It has gained its popularity due to its simplicity and eases to use. Python has reduced no. of lines of code a lot, thus simplifying learning and implementation of python for practical use.

Also, python is platform-independent (means once code is written in one platform, it will get executed on any platform without making any changes) and dynamically typed language (Means the datatype of the variables is decided by an interpreter at the time of execution).

Developers want to focus on the implementation part rather than spending time writing complex programs. This is where Python is very useful due to its rich library functions.

This is where python provides reliable and easy access.

Basic concepts are the foundation of any programming language and hence in this blog, we will learn the concept of variables and data types in python.

Following are the topics covered in the blog:

  • Variables in Python
  • Variable Definition & Declaration
  • Data Types In Python
  • Numerical Data Type
  • Strings
  • Lists
  • Tuples
  • Sets
  • Dictionary
  • Range

For Free Demo classes Call: 8149467521

Registration Link: Click Here!

Variables in Python:

As the name suggests variables are the values that vary.

When we perform coding in python, we need space to store values in the system. In a programming language, a variable is a memory location where you store a value. The value that you have stored may change in the future according to the specifications.

A Variable in python is created as soon as a value is assigned to it. It does not need any additional commands to

declare a variable in python. In fact, we don’t declare variables in python, we directly initialize them. Thus the work of variable declaration has been reduced for programmers.

There are certain rules and regulations we have to follow while writing a variable, let’s take a look at the

variable definition and declaration to understand how we declare a variable in python.

Variable Definition & Declaration:

Python has no additional commands to declare a variable. As soon as the value is assigned to it, the variable is declared, and it’s the responsibility of interpreter to allot the datatype to the variables.

x = 10

#variable is declared as the value 10 is assigned to it.

There are certain rules that we have to keep in mind while declaring a variable. These variables are as given below:

  1. The variable name cannot start with a number.
  2. The name of the variable must start with a character or an underscore.
  3. Variables in python are case sensitive.
  4. They can only contain alpha-numeric characters and underscores.
  5. No special characters are allowed.
  6. There are several data types in python.
  7. There is no length limit when it comes to defining a variable in python. But it will be better to handle variables if defined with limited length

We will further discuss data types in python in detail.

Variables we declare in python has a data type. In python, all Data types are classes and variables are the instances of these classes.

Data Types In Python

According to the properties, there are mainly six data types in python. Although there is one more data type range which is often used while working with loops in python.

Numerical Data Types

Numerical data type holds a numerical value. In numerical data, there are 4 subtypes as well. Following are the sub-types of numerical data type:

Integers

Float

Complex Numbers

Boolean

Integers are used to represent whole number values.

x = 100

y = 124

# it will be the integer as long as the value is a whole number.

To check the type of any variable data type, we can use the type() function. It will return the type of the mentioned variable data type.

A float data type is used to represent decimal point values.

x  = 10.25

y = 12.30

Complex numbers are used to represent imaginary values. Imaginary values are denoted with ‘j’ at the end of the number.

x = 10 + 5j

 

Boolean is used for categorical output since the output of boolean is either true or false.

num = 5 > 4

#num is the boolean variable

type(num)

#the output will be bool

print(num)

#this will print true.

For Free Demo classes Call: 8149467521

Registration Link: Click Here!

Strings

Strings in Python are used to represent Unicode character values. In Python we do not have a character data type, a single character is also considered as a string.

We denote or declare the string values inside single quotes or double-quotes. To access the values in a string, we use the

indexes and square brackets.

name = ‘SevenMentor’

name[2]

#this will give you the output as ‘v’

Strings are immutable in nature, which means you cannot change a string once replaced.

Command line input for strings

x = input()

print( ‘hello’ , x)

Operations using strings

name = ‘SevenMentor’

name.upper()

#this will make the letters to uppercase

name.lower()

#this will make the letters to lowercase

name.replace(‘e’) = ‘E’

#this will replace the letter ‘e’ with ‘E’

name[1: 4]

#this will return the strings starting at index 1 until the index 4.

Now that we have understood numbers and strings, let’s understand the relatively complex data types.

Lists:

The list is one of the four data types that we have in python. When we are choosing a collection type, it is important

to understand the functionality and limitations of the collection. Tuple, set and dictionary are the other collection data type in python.

A list is ordered(forward and backward index is maintained) and changeable (ie. mutable), unlike strings. We can add duplicate values as well. To declare a list we use the square brackets.

my list = [10,20,30,40,20,30, ‘SevenMentor’]

Accessing values from a list

We use indexes to access values from a string.

mylist[2:6]

#this will get the values from index 2 until index 6.

Adding/Replacing values in a list

mylist[6] = ‘python’

#this will replace the value at index 6.

mylist.append(‘Hello’)

#this will add the value at the end of the list.

mylist.insert(5, ‘data science’)

#this will add the value at the index 5.

Other operations that we can perform on a list are the following:

clear():    removes all the elements from the list

copy():    returns a copy of the list

extend(): add the elements of the list to the end of the current list

count():   returns the number of elements of the specified value

index():   returns the index of the element

pop():      removes the element from the specified position

remove(): removes the item with the specified value

sort():      sorts the list

reverse(): returns the reversed list

Lists can store any data type as items. Be it numbers, strings or any other data type as well.

a = [10,20,30]

b = [60 , 50 , 40, a]

#to access a value from the list we can write

b[3][2]

#this will return 30 as output.

Let’s understand the next collection data type in python i.e tuples.

For Free Demo classes Call: 8149467521

Registration Link: Click Here!

Tuples:

A tuple is a collection which is unchangeable or immutable. It is ordered and the values can be accessed using the index values. A tuple can have duplicate values as well. To declare a tuple we use the round brackets.

mytuple = (10,10,20,30,40,50)

#to count the number of elements

mytuple.count(10)

#the output will be 2

#to find the index

mytuple.index(50)

#the output will be 5. since the index number at 50 is 5.

Since a tuple is unchangeable once you have declared it, there are not many operations you can perform on a tuple. But there is a bright side to using a tuple, you can store values in a tuple which you do not want to change while working in a project.

Although you will be able to access the values, there will not be any changes to be made.

Sets

A set is a collection which is unordered, it does not have any indexes as well. As set do not maintain index, so it does not support indexing and slicing.

A set in python is declared using the curly brackets ie {}.

myset = {10, 20 , 30 ,40, 50, 50}

A set does not have any duplicate values, even though it will not show any errors while declaring the set, the output will only have distinct values.

To access the values in a set we can either loop through the set, or use a membership operator to find a particular value.

for x in myset:

print(x)

#this will get all the values.

20 in myset

#this will  return true if the value is in the set.

#to add a value in a set

myset.add(‘SevenMentor’)

#to add multiple values in a list

myset.update([ 10, 20, 30, 40, 50])

#to remove an item from a set

myset.remove(‘SevenMentor’)

#we can use the discard or pop method to remove an item from a set as well.

myset = {10, 20, 30}

myset1 = {10,30,50}

myset.issubset(myset1)

#this will return false

myset.union(myset1)

#this will return a set with the union of the two sets.

Method Name                                    Property

clear():                           clears the items from a set

copy():                           returns the copy of the set

difference():                   returns a set with the difference of the two sets

isdisjoint():                     returns if the sets have intersection

issubset():                       returns if the set is a subset

symmetricdifference():  returns a set with the symmetric difference

update():                        update the sets with the union of the set

 

Let’s take a look at another collection data type which has key-value pairs.

Dictionary:

A dictionary is not like any other datatype in Python. As they have key-value pairs. A dictionary is unordered and changeable. We use the keys to access the items from a dictionary. To declare a dictionary curly brackets are used.

mydictionary = { ‘python’: ‘data science’, ‘machine learning’ : ‘tensorflow’ , ‘artificial intelligence’: ‘keras’}

mydictionary[‘machine learning’]

#this will give the output as ‘tensorflow’

mydictionary.get(‘python’)

#this serves the same purpose to access the value.

Since we are using the keys to access the items, they cannot be duplicate.The values can have duplicate items.

Data Manipulation in a dictionary

#adding a new value

mydictionary[‘analysis’] = ‘matplotlib’

#replacing a value

mydictionary[‘analysis’] = ‘pandas’

#deleting a value

mydictionary.pop(‘analysis’)

#remove() , del also serves the same purpose for deleting a value.

Other operations in a dictionary include the following.

Method Name                                   Property

copy()             returns a copy of the dictionary

clear()             clears the dictionary

items()             returns a list containing tuple of key value pairs

keys()              returns a list containing all the keys

update()           updates the dictionary with all the key-value pairs

values()            returns a list of all the values in a dictionary

setdefault()      returns the value of a specified key

Range

Range is a data type which is mainly used when we are using a loop. Lets take an example to understand this.

for x in range(10):

print(x)

#this will print the numbers from 0-10. The range will have the numbers from 0-10

Now that we have understood different data types that we have in python, there is another important concept of typecasting

which is helpful when we change from one data type into another. Let’s understand the concept of typecasting.

For Free Demo classes Call: 8149467521

Registration Link: Click Here!

Type Casting:

Type casting basically is the process of changing one data type into another. We have constructors for each of the data types in python.

  • list()
  • set()
  • tuple()
  • dict()
  • str()
  • int()
  • float()

We can simply use these constructors to use the specified data type or we can change a data type to another using these constructors.

Let’s understand this with an example.

a = [ 10 , 20 ,30,40]

#to change this list into a tuple i can simply write

tuple(a)

#now the list will change to a tuple.

Using these constructors we can use various data types with the functionality of the other. Suppose we declare the list mentioned

in the example as a tuple in a program, it will become immutable for that particular operation. Similarly we can use other constructors as well.

Now that we have discussed variables and data types in python. I hope the properties of each data type and the operations are clear to you.

Call the Trainer and Book your free demo Class for now!!!

call icon

© Copyright 2019 | Sevenmentor Pvt Ltd.

 

Submit Comment

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

*
*