The Best Tutorial on Python Variables and Python Data Types

1. Python Variables and Python Data Types

In this Python tutorial on Python Variables and Python Data Types, we will learn about at Python variables and data types being used in Python. Since we know that Python is a dynamically-typed language, we don’t specify the type of a variable when declaring one. We will also learn about converting one data type to another in Python and local and global variables in Python. So, let’s begin with Python variables and Python Data Type Tutorial.

The Best Tutorial on Python Variables and Python Data Types

The Best Tutorial on Python Variables and Python Data Types

2. What is Python Variables?

Let us now proceed towards Python variables and Python data types. Before starting, let us revise syntax in python.

A variable is a container for a value. It can be assigned a name, you can use it to refer to it later in the program. Based on the value assigned, the interpreter decides its data type. You can always store a different type in a variable.

For example, if you store 7 in a variable, later, you can store ‘Dinosaur’.

Read Errors and Exception in Python

a. Python Variables Naming Rules

There are certain rules to what you can name a variable(called an identifier).

  • Python variables can only begin with a letter(A-Z/a-z) or an underscore(_).
>>> 9lives=9

SyntaxError: invalid syntax

>>> flag=0
>>> flag
>>> _9lives='cat'
>>> _9lives


  • The rest of the identifier may contain letters(A-Z/a-z), underscores(_), and numbers(0-9).
>>> year2='Sophomore'
>>> year2


>>> _$$=7

SyntaxError: invalid syntax

  • Python is case-sensitive, and so are Python identifiers. Name and name are two different identifiers.
>>> name='Ayushi'
>>> name


>>> Name

Traceback (most recent call last):
File “<pyshell#21>”, line 1, in <module>
NameError: name ‘Name’ is not defined

Read: Python Variable Scope – Local, Global, Built-in, Enclosed

  • Reserved words (keywords) cannot be used as identifier names.

b. Assigning and Reassigning Python Variables

To assign a value to Python variables, you don’t need to declare its type. You name it according to the rules stated in section 2a, and type the value after the equal sign(=).

>>> age=7
>>> print(age)


>>> age='Dinosaur'
>>> print(age)


However, age=Dinosaur doesn’t make sense. Also, you cannot use python variables before assigning it a value.

>>> name

Traceback (most recent call last):
File “<pyshell#8>”, line 1, in <module>
NameError: name ‘name’ is not defined

You can’t put the identifier on the right-hand side of the equal sign, though. The following code causes an error.

>>> 7=age

SyntaxError: can’t assign to literal

Neither can you assign python variables to a keyword.

>>> False=choice

SyntaxError: can’t assign to keyword

Read: Python Number Types and Their Conversion Functions

c. Multiple Assignment

You can assign values to multiple python variables in one statement.

>>> age,city=21,'Indore'
>>> print(age,city)

21 Indore

Or you can assign the same value to multiple python variables.

>>> age=fav=7
>>> print(age,fav)

7 7

This is how you assign values to Python Variables

Read: Python Comment, Indentation and Statement

d. Swapping variables

Swapping means interchanging values. To swap Python variables, you don’t need to do much.

>>> a,b='red','blue'
>>> a,b=b,a
>>> print(a,b)

blue red

e. Deleting variables

You can also delete python variables using the keyword ‘del’.

>>> a='red'
>>> del a
>>> a

Traceback (most recent call last):
File “<pyshell#39>”, line 1, in <module>
NameError: name ‘a’ is not defined

This is How you can delete Python Variables

Read:Python Strings with String Functions and String Operations

Python Variables and Python Data Types

Python Variables and Python Data Types

3. Python Data Types

Although we don’t have to declare type for python variables, a value does have a type. This information is vital to the interpreter. Python supports the following Python data types.

a. Python Numbers

There are four numeric Python data types.

1. int– int stands for integer. This Python Data Type holds signed integers. We can use the type() function to find which class it belongs to.

>>> a=-7
>>> type(a)

<class ‘int’>

An integer can be of any length, with the only limitation being the available memory.

>>> a=9999999999999999999999999999999
>>> type(a)

<class ‘int’>

2. float– This Python Data Type holds floating point real values. An int can only store the number 3, but float can store 3.25 if you want.

>>> a=3.0
>>> type(a)

<class ‘float’>

3. long – This Python Data Types holds a long integer of unlimited length. But this construct does not exist in Python 3.x.

4. complex- This Python Data Types holds a complex number. A complex number looks like this: a+bj Here, a and b are the real parts of the number, and j is imaginary.

>>> a=2+3j
>>> type(a)

<class ‘complex’>

Use the isinstance() function to tell if python variables belong to a particular class. It takes two parameters- the variable/value, and the class.

>>> print(isinstance(a,complex))


Read: Python Operators with Syntax and Examples

b. Strings

A string is a sequence of characters. Python does not have a char data type, unlike C++ or Java. You can delimit a string using single quotes or double quotes.

>>> city='Ahmedabad'
>>> city


>>> city="Ahmedabad"
>>> city


1. Spanning a string across lines – To span a string across multiple lines, you can use triple quotes.

>>> var="""If
>>> var


>>> print(var)


>>> """If


As you can see, the quotes preserved the formatting (\n is the escape sequence for newline, \t is for tab).

2. Displaying part of a string– You can display a character from a string using its index in the string. Remember, indexing starts with 0.

>>> lesson='disappointment'
>>> lesson[0]


You can also display a burst of characters in a string using the slicing operator [].

>>> lesson[5:10]


This prints the characters from 5 to 9.

3. String Formatters– String formatters allow us to print characters and values at once. You can use the % operator.

>>> x=10;
>>> printer="Dell"
>>> print("I just printed %s pages to the printer %s" % (x, printer))

Or you can use the format method.

>>> print("I just printed {0} pages to the printer {1}".format(x, printer))
>>> print("I  just printed {x} pages to the printer {printer}".format(x=7, printer="Dell"))

A third option is to use f-strings.

>>> print(f"I just printed {x} pages to the printer {printer}")

4. String Concatenation– You can concatenate(join) strings.

>>> a='10'
>>> print(a+a)


However, you cannot concatenate values of different types.

>>> print('10'+10)

Traceback (most recent call last):

File “<pyshell#89>”, line 1, in <module>;


TypeError: must be str, not int

Read:Bitwise Operator in Python with Syntax and Example

c. Python Lists

A list is a collection of values. Remember, it may contain different types of values. To define a list, you must put values separated with commas in square brackets. You don’t need to declare a type for a list either.

>>> days=['Monday','Tuesday',3,4,5,6,7]
>>> days

[‘Monday’, ‘Tuesday’, 3, 4, 5, 6, 7]

1. Slicing a list – You can slice a list the way you’d slice a string- with the slicing operator.

>>> days[1:3]

[‘Tuesday’, 3]

Indexing for a list begins with 0, like for a string. A Python doesn’t have arrays.

2. Length of a list– Python supports an inbuilt function to calculate the length of a list.

>>> len(days)


3. Reassigning elements of a list– A list is mutable. This means that you can reassign elements later on.

>>> days[2]='Wednesday'
>>> days

[‘Monday’, ‘Tuesday’, ‘Wednesday’, 4, 5, 6, 7]

4. Multidimensional lists– A list may have more than one dimension. We will look further into this in the tutorial on Python Lists.

>>> a=[[1,2,3],[4,5,6]]
>>> a

[[1, 2, 3], [4, 5, 6]]

Read: Python Decision Making Statements with Syntax and Examples

d. Python Tuples

A tuple is like a list. You declare it using parentheses instead.

>>> subjects=('Physics','Chemistry','Maths')
>>> subjects

(‘Physics’, ‘Chemistry’, ‘Maths’)

1. Accessing and Slicing a Tuple– You access a tuple the same way as you’d access a list. The same goes for slicing it.

>>> subjects[1]


>>> subjects[0:2]

(‘Physics’, ‘Chemistry’)

2. A tuple is immutable– However, it is immutable. Once declared, you can’t change its size or elements.

>>> subjects[2]='Biology'

Traceback (most recent call last):
File “<pyshell#107>”, line 1, in <module>
TypeError: ‘tuple’ object does not support item assignment

>>> subjects[3]='Computer Science'

Traceback (most recent call last):
File “<pyshell#108>”, line 1, in <module>
subjects[3]=’Computer Science’
TypeError: ‘tuple’ object does not support item assignment

Read:Python Namespace and Variable Scope – Local and Global Variables

e. Dictionaries

A dictionary holds key-value pairs. Declare it in curly braces, with pairs separated by commas. Separate keys and values by a colon(:).

>>> person={'city':'Ahmedabad','age':7}
>>> person

{‘city’: ‘Ahmedabad’, ‘age’: 7}

The type() function works with dictionaries too.

>>> type(person)

<class ‘dict’>

1. Accessing a value– To access a value, you mention the key in square brackets.

>>> person['city']


2. Reassigning elements– You can reassign a value to a key.

>>> person['age']=21
>>> person['age']


3. List of keys– Use the keys() function to get a list of keys in the dictionary.

>>> person.keys()

dict_keys([‘city’, ‘age’])

f. bool

A Boolean value can be True or False.

>>> a=2>1
>>> type(a)

<class ‘bool’>

Read: Python Functions with Syntax and Examples

g. Sets

A set can have a list of values. Define it using curly braces.

>>> a={1,2,3}
>>> a

{1, 2, 3}

It returns only one instance of any value present more than once.

>>> a={1,2,2,3}
>>> a

{1, 2, 3}

However, a set is unordered, so it doesn’t support indexing.

>>> a[2]

Traceback (most recent call last):
File “<pyshell#127>”, line 1, in <module>
TypeError: ‘set’ object does not support indexing

Also, it is mutable. You can change its elements or add more. Use the add() and remove() methods to do so.

>>> a={1,2,3,4}
>>> a

{1, 2, 3, 4}

>>> a.remove(4)
>>> a

{1, 2, 3}

>>> a.add(4)
>>> a

{1, 2, 3, 4}

Read:Python Function Arguments with Types, Syntax and Examples

4. Type Conversion

Since Python is dynamically-typed, you may want to convert a value into another type. Python supports a list of functions for the same.

a. int()

It converts the value into an int.

>>> int(3.7)

Notice how it truncated 0.7 instead of rounding the number off to 4. You can also turn a Boolean into an int.

>>> int(True)


>>> int(False)

However, you cannot turn a string into an int. It throws an error.

>>> int("a")

Traceback (most recent call last):
File “<pyshell#135>”, line 1, in <module>;
ValueError: invalid literal for int() with base 10: ‘a’
However, if the string has only numbers, then you can.

>>> int("77")


Read: Python Built-In Functions with Syntax and Examples

b. float()

It converts the value into a float.

>>> float(7)


>>> float(7.7)


>>> float(True)


>>> float("11")

You can also use ‘e’ to denote an exponential number.

>>> float("2.1e-2")


>>> float(2.1e-2)

However, this number works even without the float() function.

>>> 2.1e-2


c. str()

It converts the value into a string.

>>> str(2.1)


>>> str(7)


>>> str(True)


You can also convert a list, a tuple, a set, or a dictionary into a string.

>>> str([1,2,3])

‘[1, 2, 3]’

d. bool()

It converts the value into a boolean.

>>> bool(3)


>>> bool(0)


>>> bool(True)


>>> bool(0.1)


You can convert a list into a Boolean.

>>> bool([1,2])


The function returns False for empty constructs.

>>> bool()


>>> bool([])


>>> bool({})


None is a keyword in Python that represents an absence of value.

>>> bool(None)


e. set()

It converts the value into a set.

>>> set([1,2,2,3])

{1, 2, 3}

>>> set({1,2,2,3})

{1, 2, 3}

f. list()

It converts the value into a list.

>>> del list
>>> list("123")

[‘1’, ‘2’, ‘3’]

>>> list({1,2,2,3})

[1, 2, 3]

>>> list({"a":1,"b":2})

[‘a’, ‘b’]

However, the following raises an error.

>>> list({a:1,b:2})

Traceback (most recent call last):
File “<pyshell#173>”, line 1, in <module>;
TypeError: unhashable type: ‘set’

g. tuple()

It converts the value into a tuple.

>>> tuple({1,2,2,3})

(1, 2, 3)

You can try your own combinations. Also try composite functions.

>>> tuple(list(set([1,2])))

(1, 2)

Python Interview Questions

5. Python Local and Python Global Variables

Another classification of python variables is based on scope.

a. Python Local variables

When you declare a variable in a function, class, or so, it is only visible in that scope. If you call it outside of that scope, you get an ‘undefined’ error.

>>> def func1():
>>> func1()


>>> uvw

Traceback (most recent call last):
File “<pyshell#76>”, line 1, in <module>
NameError: name ‘uvw’ is not defined[/php]

Here, the variable uvw is local to function func1().

b. Global variables

When you declare a variable outside any context/scope, it is visible in the whole program.

>>> xyz=3
>>> def func2():
>>> func2()


>>> xyz

You can use the ‘global’ keyword when you want to treat a variable as global in a local scope.

>>> foo=1
>>> def func2():
	global foo
>>> func2()


>>> foo

Read: Data Structures in Python – Lists, Tuples, Sets, Dictionaries

This was all about the Python Variables and Python data type tutorial

6. Python Variables and Python Data Types – Conclusion

In this tutorial on Python Variables and Python Data Types, we learnt about different python variables and data types with examples. We looked at the naming rules, and defining and deleting them. Then we saw different types of data- numbers, strings, lists, dictionaries, tuples, sets, and many more. We also learnt how to convert one variable type into another and local and global variables in python. Don’t forget to try out your own combinations.

If you have any queries the Python Variables and Python Data Type Tutorial, Please drop a comment.

See also –

Exception Handling in Python

For reference

14 Responses

  1. Kirti soni says:

    >>> person
    >>>{‘Ahmedabad’: ‘Ahmedabad’, 7: 7}
    this code is giving error ,please improve it.

  2. padmaja says:

    In datatype conversions i am unable to convert str(2) into string.As output showing me as a integer.

    • DataFlair Team says:

      Hi Padmaja,
      Thanks for the comment. It should work. Try this:
      >>> str(2)
      >>> type(str(2))

      Hope, it will help you!
      For more queries regarding Python variable and datatype, ping here.

      • Bakare Oluwayemisi says:

        Great explanation. Is there a way you can put practice questions at the end of each topic?

        • DataFlair Team says:

          Hello Bakare,
          We have 6 Articles on Python Interview Questions, you can practice from there and soon we will publish a series of Python Quiz. So, stay connected from DataFlair to get it.

  3. Semih says:

    print(“I just printed {x} pages to the printer {printer}”.format(x=7, printer=Dell)) there is a little mistake here, just wanted to let you know. It should be: printer=”Dell”, you forgot the quotes there 🙂
    Thank you for such a great site.

    • DataFlair Team says:

      Hey Semih,
      Thanks for improving us. It was a typo error, we have corrected it. Now, you can learn Python Variables and data types hassle free.

  4. Durga says:

    Hi Team,

    Can you pleas give more explanation on f string – string formaters

    • DataFlair Team says:

      Hey Durga,
      Thanks for connecting with DataFlair, we have another article on Python Strings, in which you can get all the details about f-strings and string formatters. Please refer to our sidebar for the same.
      Hope it helps!

  5. Ben Sale says:

    Hi Team
    If I try the code for Global variables as typed:
    def func2():
    I get a few issues – namely around indents which I correct and then that the statement xyz has no effect. Changing this to func2() then causes an error that says local variable ‘xyz’ referenced before assignment.
    Have I misunderstood the tutorial? I thought that defining xyz in line 1 made it global? But it seems not. If I add ‘global xyz’ as line 3 then it works.
    Can you help explain?

    • DataFlair Team says:

      Hi, Ben
      Thanks for pointing this out. We have made the necessary changes.
      Also, defining xyz=1 does not make it global for func2- you need to put ‘global xyz’ in func2 so it can modify the value of the global xyz.
      Hope, it helps!

  6. Furkan says:

    you should give practice questions after each important article.Like in this Python Variable article questions are must for practice.Hope you will understand it

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.