Data Types and Variables In Python
Last updated on September 06, 2020
Data Types #
Data Type is nothing but a categorization of data of different types. A data type defines set of values along with operations that can be performed on those values. Explicit values we use in our programs is known as literal. For example,
'pypi' are called literals. Each literal has a type associated with it. For example,
10 is of type
88.22 is of type
'pypi' is of type
str (or string). It is the type of the literal which determines which kinds of operations can be performed on it. The following table shows some base data types in Python along with examples:
|Types of data||In Python we call them||Examples|
Python has an in-built function called
type() which we can use to determine the data type of the literal.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
>>> >>> type(54) <class 'int'> >>> >>> type("a string") <class 'str'> >>> >>> type(98.188) <class 'float'> >>> >>> type("3.14") <class 'str'> >>> >>> type("99") <class 'str'> >>>
<class 'int'> indicates that the type of
<class 'str'> and
<class 'float'> indicates that
"a string" and
98.188 is of type
At first, you might think
"3.14" is of type
float but because
3.14 is wrapped inside double quotes, it is actually a string. For the same reason
"99" is a string too.
Python has many other data types which we will discuss later.
Variables are used to store data in our programs. We also use variables to access data as well as manipulate data. A variable is called so because it's value can be changed.
Creating variables #
To create a variable in Python we use assignment statement which has the following format.
variable_name = expression
variable_name is the name of the variable, (
=) is known as Assignment Operator and
expression is just a combination of values, variables and operators. Here is an example:
homerun = 6
This statement creates a variable named
homerun and assigns it the value
6. When Python Interpreter encounter statements like this it does the following things behind the scenes.
- Store the variable
6somewhere in the memory.
- Make variable
homerunrefer to it.
The important thing to understand here is that variable
homerun itself doesn't contain any value, it only refers to a memory location which contains the actual value.
Unlike languages like C, C++, and Java, in Python, we don't declare the type of the variable ahead of time. In fact, it a Syntax error if you try to do so.
1 2 3 4 5 6 7
>>> >>> int homerun File "<stdin>", line 1 int homerun ^ SyntaxError: invalid syntax >>>
While assigning a value to the variable, always write the variable name on the left side of the assignment (
=) operator. If you don't do this you will get a syntax error as follows:
1 2 3 4 5
>>> >>> 100 = words File "<stdin>", line 1 SyntaxError: can't assign to literal >>>
Python automatically detects the type of the variable and operations that can be performed on it based on the type of the value it contains. In programming jargon this behavior is known as Dynamic Typing. It means that we could use the same variable to refer to a data of completely different type than it initially points to. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
>>> >>> homerun = 6 # at this point, homerun contains an int or integer >>> homerun 6 >>> homerun = "now" # now homerun contains a string >>> homerun 'now' >>> >>> type(homerun) <class 'str'> >>> >>> homerun = 2.3 # now homerun contains a float >>> homerun 2.3 >>> type(homerun) <class 'float'> >>>
When we assign a new value to a variable the reference to old value is lost. For example, when
"now" is assigned to the
homerun, the reference to value
6 is lost. At this point, no variable is pointing to that memory location. When this happens Python Interpreter automatically removes the value from the memory through a process known as garbage collection.
If you try to access a variable before assigning any value to it. You will get
NameError error like this:
1 2 3 4 5 6
>>> >>> age Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'age' is not defined >>>
We can use also use
print() function to print the value of a variable like this:
1 2 3 4 5
>>> >>> age = 100 >>> print(age) 100 >>>
Variable Names #
In Python, we have the following rules to create a valid variable name.
Only use letters (
A-Z), underscore (
_) and numbers (
0-9) are allowed to create variable names, nothing else.
It must begin with a underscore (
_) or a letter.
You can't use reserved keywords to create variables names.(see below).
Variable name can be of any length.
Python is case-sensitive language which means that
home are two different variables.
Python keywords #
Python Keywords are words that denote something specific in a Python language. That's why, we are not allowed to use them as variables names. Here is the list of Python keywords:
We will learn more about some of the keywords mentioned here as we progress through this course.
The following are some valid and invalid variable names:
home4you - Valid
after_you - Valid
_thatsall - Valid
all10 - Valid
python_101 - Valid
$money - Invalid, variables can't begin with
hello pi - Invalid, variables can't have spaces between them
2001 - Invalid, variables can't begin with a digit
break - Invalid, keyword can't be a variable name
Comments are used to add notes to a program. In a large program, comments may describe the purpose of the program and how it works. They are solely intended for the people who are trying to understand the source code of the program. They are not programming statements so they are ignored by the Python Interpreter while executing the program.
In Python, everything from
# to end of the line is considered a comment. For example:
# This is a comment on a separate line print("Testing comments") # This is a comment after print statement
Named Constants #
Constants are variables whose values do not change during the lifetime of the program. Unlike languages like C or Java; Python doesn't have a special syntax to create constants. We create constants just like ordinary variables. However, to separate them from an ordinary variable, we use all uppercase letters.
1 2 3
>>> >>> MY_CONST = 100 # a constant >>>
MY_CONST is just a variable which refers to a value of type
int. It has no other special properties.
You are even allowed to change the value of
MY_CONST constant by assigning new value to it as follows:
1 2 3
>>> >>> MY_CONST = "new value" >>>
We will use named constant from time to time in our programs.
Displaying Multiple items with the print() Function #
We can also use
print() statement to print multiple items in a single call by separating each item by a comma (
,). When multiple arguments are passed to
print() function, they are printed to the console separated by spaces. For example:
1 2 3 4 5
>>> >>> message = "item2" >>> print("item1", message, "item3") item1 item2 item3 >>>
Simultaneous Assignment #
We can assign values to multiple variables at once using simultaneous assignment which has the following syntax:
var1, var2, var3, ... varN = exp1, exp2, exp3, ... expN
When Python encounters simultaneous assignment statement, it first evaluates all the expression on the right hand side and then assigns their value to the corresponding variables on the left. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13
>>> >>> name, age, designation = "tom", 25, "Lead Developer" >>> >>> name 'tom' >>> >>> age 25 >>> >>> designation 'Lead Developer' >>> >>>
Swapping values between two variables is a common programming operation. In languages like C, to perform swapping you have to create an additional variable to store the data temporarily. For example:
1 2 3 4 5
int i = 10, j = 20; int tmp; // variable to store data temporary tmp = i; // now tmp contains 10 i = j; // now i contains 20 j = tmp; // now j contains 10
In Python, we can use simultaneous assignment to swap values as follows:
1 2 3 4 5 6 7 8 9
>>> >>> x, y = 10, 20 >>> print(x, y) 10 20 # initial value >>> >>> x, y = y, x ## swapping values >>> print(x, y) 20 10 # final value >>>
Functions in Python #
A function is a piece of code which performs something very specific task. At this point, we have only discussed
type() function, but Python standard library has literally thousands of built-in functions that perform various kinds of operations.
A function can't do anything by itself unless you call it. To call a function type the name of the function followed by argument list inside the parentheses i.e
() as follows:
function_name(arg1, arg2, arg3, arg4, ..., argN)
So what are arguments ?
Arguments are additional data required by the function to perform the task. Some functions require arguments while others don't. To call a function which don't accept any argument, type function name followed by empty parentheses as follows:
Arguments are also commonly known as parameters.
In the statement,
"Big Python" is an argument.
When a function completes it's task, it usually returns a value. Not all function returns a value, some do while other's don't. If a function do not explicitly return any value then it returns a special value called
None, which is one of reserved keywords in Python. That's all you need to know right now. We will discuss function in great detail in lesson Functions in Python.
Modules in Python #
Python uses modules to group similar function, classes, variables etc. For example,
math module contains various Mathematical functions and constants,
datetime module contains various classes and functions for working with date and time and so on. To use functions, constants or classes defined inside the module, we first have to import it using the
import statement. The syntax of the
import statement is as follows:
math module inside the Python Shell type the following code:
1 2 3
>>> >>> import math >>>
To use a method or constant from the module type module name followed by the dot (
.) operator, which is followed by the name of the method or variable that you want to access. For example,
math module has
sqrt() function whose job is to return the square root of a number. To use this function type the following code in Python shell.
1 2 3 4
>>> >>> math.sqrt(441) 21.0 >>>
math module also has two commonly used Mathematical constants
e. To access them type the following code:
1 2 3 4 5 6 7
>>> >>> math.pi 3.141592653589793 >>> >>> math.e 2.718281828459045 >>>
To view a complete list of functions and constants provided by the
math module check the documentation for
math module here.
Built-in functions like
input() (we discuss this function next) belongs to a special module called
__builtin__. But Why it is special ? Because functions inside the
__builtin__ module are always available to use without explicitly importing
Reading Input from Keyboard #
Python has a built-in function named
input() to read input from the keyboard. It's syntax is as follows:
var = input(prompt)
prompt refers to the optional string which instructs the user to enter the input. The
input() function reads the input data from the keyboard and returns it as a string. The entered data is then assigned to a variable named
var for further processing.
It doesn't matter whether the entered data is of type
float or anything else, eventually the
input() function will convert the data to string.
input() statement is encountered, the program pauses and waits for the user to enter input. When you are done typing, hit enter key to submit the input. The
input() function then returns the entered data as string.
1 2 3 4 5 6 7 8 9 10 11
>>> >>> name = input("Enter your name: ") Enter your name: Tom >>> >>> name 'Tom' >>> >>> type(name) <class 'str'> >>> >>>
Getting Help using help() Function #
Documentation is an important part of any Computer language and as a budding programmer you should know how to access Python's documentation to learn more about language and various capabilities it provides.
We can use the
help() command to learn more about a function, class or modules. To use
help() function just pass the name of the function, class or module. For example, to learn about the
input() function call
help() function as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
>>> >>> help(input) Help on built-in function input in module builtins: input(...) input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. >>> >>>
input([prompt]) -> string is called the function signature. A function signature defines it's arguments and return value. If an argument is optional then it will be wrapped inside square brackets
input([prompt]) -> string means that
input() function accepts a optional argument called
prompt and returns a value of type string.
Note the that
help() function does not uses Internet connection to fetch the documentation, instead it uses a offline copy of the documentation stored in the hard drive. Python documentation is also available online, to access it visit https://docs.python.org/3/.