Aakashns - Python-Variables-And-Data-Types - Jovian
Aakashns - Python-Variables-And-Data-Types - Jovian
Join the Zero to Data Science Bootcamp by Jovian. 20 weeks part-time, 7 courses, 12 assignments, 4
projects, and 6 months of career support.
These tutorials take a practical and coding-focused approach. The best way to learn the material is to
execute the code and experiment with it yourself.
Jupyter Notebooks: This tutorial is a Jupyter notebook - a document made of cells. Each cell can contain
code written in Python or explanations in plain English. You can execute code cells and view the results,
e.g., numbers, messages, graphs, tables, files, etc. instantly within the notebook. Jupyter is a powerful
platform for experimentation and analysis. Don't be afraid to mess around with the code & break things -
you'll learn a lot by encountering and fixing errors. You can use the "Kernel > Restart & Clear Output"
menu option to clear all outputs and start again from the top.
my_favorite_color = "blue"
my_favorite_color
'blue'
A variable is created using an assignment statement. It begins with the variable's name, followed by the
assignment operator = followed by the value to be stored within the variable. Note that the assignment
operator = is different from the equality comparison operator == .
You can also assign values to multiple variables in a single statement by separating the variable names
and values with commas. Sign In
color1
'red'
color2
'green'
color3
'blue'
You can assign the same value to multiple variables by chaining multiple assignment operations within a
single statement.
color4
'magenta'
color5
'magenta'
color6
'magenta'
You can change the value stored within a variable by assigning a new value to it using another assignment
statement. Be careful while reassigning variables: when you assign a new value to the variable, the old
value is lost and no longer accessible.
my_favorite_color = "red"
my_favorite_color
'red'
While reassigning a variable, you can also use the variable's previous value to compute the new value.
counter = 10 Sign In
counter = counter + 1
counter
11
counter = 10
counter += 4
counter
14
A variable's name must start with a letter or the underscore character _. It cannot begin with a number.
A variable name can only contain lowercase (small) or uppercase (capital) letters, digits, or underscores
(a-z, A-Z, 0-9, and _).
Variable names are case-sensitive, i.e., a_variable, A_Variable, and A_VARIABLE are all different
variables.
a_variable = 23
is_today_Saturday = False
my_favorite_car = "Delorean"
Let's try creating some variables with invalid names. Python prints a syntax error if your variable's name is
invalid.
Syntax: The syntax of a programming language refers to the rules that govern the structure of a valid
instruction or statement. If a statement does not follow these rules, Python stops execution and informs
you that there is a syntax error. You can think of syntax as the rules of grammar for a programming
language. Sign In
a variable = 23
a variable = 23
is_today_$aturday = False
is_today_$aturday = False
my-favorite-car = "Delorean"
my-favorite-car = "Delorean"
^
SyntaxError: cannot assign to operator
import jovian
jovian.commit(project='python-variables-and-data-types')
'https://jovian.ai/samanvitha/python-variables-and-data-types'
The first time you run jovian.commit , you'll be asked to provide an API Key to securely upload the
notebook to your Jovian account. You can get the API key from your Jovian profile page after logging in /
signing up.
jovian.commit uploads the notebook to your Jovian account, captures the Python environment, and
creates a shareable link for your notebook, as shown above. You can use this link to share your work and
let anyone (including you) run your notebooks and reproduce your work.
a_variable
23
type(a_variable)
int
is_today_Saturday
False
type(is_today_Saturday)
bool
my_favorite_car
'Delorean'
type(my_favorite_car)
str
the_3_musketeers Sign In
type(the_3_musketeers)
list
Python has several built-in data types for storing different kinds of information in variables. Following are
some commonly used data types:
1. Integer
2. Float
3. Boolean
4. None
5. String
6. List
7. Tuple
8. Dictionary
Integer, float, boolean, None, and string are primitive data types because they represent a single value.
Other data types like list, tuple, and dictionary are often called data structures or containers because they
hold multiple pieces of data together.
Integer
Integers represent positive or negative whole numbers, from negative infinity to infinity. Note that integers
should not include decimal points. Integers have the type int .
current_year = 2020
current_year
2020
type(current_year)
int
Unlike some other programming languages, integers in Python can be arbitrarily large (or small). There's
no lowest or highest value for integers, and there's just one int type (as opposed to short , int ,
long , long long , unsigned int , etc. in C/C++/Java).
a_large_negative_number = -23374038374832934334234317348343
Sign In
a_large_negative_number
-23374038374832934334234317348343
type(a_large_negative_number)
int
Float
Floats (or floating-point numbers) are numbers with a decimal point. There are no limits on the value or the
number of digits before or after the decimal point. Floating-point numbers have the type float .
pi = 3.141592653589793238
pi
3.141592653589793
type(pi)
float
Note that a whole number is treated as a float if written with a decimal point, even though the decimal
portion of the number is zero.
a_number = 3.0
a_number
3.0
type(a_number)
float
another_number = 4.
another_number
4.0
type(another_number)
float
Sign In
Floating point numbers can also be written using the scientific notation with an "e" to indicate the power of
10.
one_hundredth = 1e-2
one_hundredth
0.01
type(one_hundredth)
float
avogadro_number = 6.02214076e23
avogadro_number
6.02214076e+23
type(avogadro_number)
float
You can convert floats into integers and vice versa using the float and int functions. The operation
of converting one type of value into another is called casting.
float(current_year)
2020.0
float(a_large_negative_number)
-2.3374038374832935e+31
int(pi)
int(avogadro_number)
602214075999999987023872
While performing arithmetic operations, integers are automatically converted to float s if any of the Sign In
operands is a float . Also, the division operator / always returns a float , even if both operands are
integers. Use the // operator if you want the result of the division to be an int .
type(45 * 3.0)
float
type(45 * 3)
int
type(10/3)
float
type(10/2)
float
type(10//2)
int
Boolean
Booleans represent one of 2 values: True and False . Booleans have the type bool .
is_today_Sunday = True
is_today_Sunday
True
type(is_today_Saturday)
bool
Booleans are generally the result of a comparison operation, e.g., == , >= , etc.
cost_of_ice_bag = 1.25
is_ice_bag_expensive
False
Sign In
type(is_ice_bag_expensive)
bool
Booleans are automatically converted to int s when used in arithmetic operations. True is converted
to 1 and False is converted to 0 .
5 + False
3. + True
4.0
Any value in Python can be converted to a Boolean using the bool function.
Only the following values evaluate to False (they are often called falsy values):
2. The integer 0
Everything else evaluates to True (a value that evaluates to True is often called a truthy value).
bool(False)
False
bool(0)
False
bool(0.0)
False
Sign In
bool(None)
False
bool("")
False
bool([])
False
bool(())
False
bool({})
False
bool(set())
False
bool(range(0))
False
None
The None type includes a single value None , used to indicate the absence of a value. None has the type
NoneType . It is often used to declare a variable whose value may be assigned later.
nothing = None
type(nothing)
NoneType
String Sign In
A string is used to represent text (a string of characters) in Python. Strings must be surrounded using
quotations (either the single quote ' or the double quote " ). Strings have the type string .
today = "Saturday"
today
'Saturday'
type(today)
str
You can use single quotes inside a string written with double quotes, and vice versa.
my_favorite_movie
my_favorite_pun = 'Thanks for explaining the word "many" to me, it means a lot.'
my_favorite_pun
To use a double quote within a string written with double quotes, escape the inner quotes by prefixing
them with the \ character.
another_pun = "The first time I got a universal remote control, I thought to myself
another_pun
'The first time I got a universal remote control, I thought to myself "This
changes everything".'
Strings created using single or double quotes must begin and end on the same line. To create multiline
strings, use three single quotes ''' or three double quotes """ to begin and end the string. Line
breaks are represented using the newline character \n .
yet_another_pun = '''Son: "Dad, can you tell me what a solar eclipse is?"
Sign In
Dad: "No sun."'''
yet_another_pun
'Son: "Dad, can you tell me what a solar eclipse is?" \nDad: "No sun."'
print(yet_another_pun)
a_music_pun = """
Two windmills are standing in a field and one asks the other,
"""
print(a_music_pun)
Two windmills are standing in a field and one asks the other,
You can check the length of a string using the len function.
len(my_favorite_movie)
31
Note that special characters like \n and escaped characters like \" count as a single character, even
though they are written and sometimes printed as two characters.
multiline_string = """a
b"""
multiline_string
'a\nb'
Sign In
len(multiline_string)
list(multiline_string)
Strings also support several list operations, which are discussed in the next section. We'll look at a couple
of examples here.
You can access individual characters within a string using the [] indexing notation. Note the character
indices go from 0 to n-1 , where n is the length of the string.
today = "Saturday"
today[0]
'S'
today[3]
'u'
today[7]
'y'
You can access a part of a string using by providing a start:end range instead of a single index in
[] .
today[5:8]
'day'
You can also check whether a string contains a some text using the in operator.
'day' in today
True
'Sun' in today
False Sign In
Two or more strings can be joined or concatenated using the + operator. Be careful while concatenating
strings, sometimes you may need to add a space character " " between words.
greeting = "Hello"
greeting + full_name
"HelloDerek O'Brien"
Strings in Python have many built-in methods that are used to manipulate them. Let's try out some
common string methods.
Methods: Methods are functions associated with data types and are accessed using the . notation e.g.
variable_name.method() or "a string".method() . Methods are a powerful technique for
associating common operations with values of specific data types.
The .lower() , .upper() and .capitalize() methods are used to change the case of the
characters.
today.lower()
'saturday'
"saturday".upper()
'SATURDAY'
'Monday'
The .replace method replaces a part of the string with another string. It takes the portion to be
replaced and the replacement text as inputs or arguments.
'Wednesday'
Note that replace returns a new string, and the original string is not modified.
today
'Saturday'
The .split method splits a string into a list of strings at every occurrence of provided character(s).
"Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",")
The .strip method removes whitespace characters from the beginning and end of a string.
a_long_line = " This is a long line with some space before, after, and som
a_long_line_stripped = a_long_line.strip()
a_long_line_stripped
'This is a long line with some space before, after, and some space in the
middle..'
The .format method combines values of other data types, e.g., integers, floats, booleans, lists, etc. with
strings. You can use format to construct output messages for display.
# Input variables
cost_of_ice_bag = 1.25
profit_margin = .2
number_of_bags = 500
output_template = """If a grocery store sells ice bags at $ {} per bag, with a profi
then the total profit it makes by selling {} ice bags is $ {}."""
print(output_template)
If a grocery store sells ice bags at $ {} per bag, with a profit margin of {}
%,
print(output_message)
If a grocery store sells ice bags at $ 1.25 per bag, with a profit margin of
20.0 %,
then the total profit it makes by selling 500 ice bags is $ 125.0.
Notice how the placeholders {} in the output_template string are replaced with the arguments
provided to the .format method.
It is also possible to use the string concatenation operator + to combine strings with other values.
However, those values must first be converted to strings using the str function.
"If a grocery store sells ice bags at $ " + cost_of_ice_bag + ", with a profit margi
---------------------------------------------------------------------------
<ipython-input-127-78b7958ec7cc> in <module>
----> 1 "If a grocery store sells ice bags at $ " + cost_of_ice_bag + ", with
a profit margin of " + profit_margin
"If a grocery store sells ice bags at $ " + str(cost_of_ice_bag) + ", with a profit
'If a grocery store sells ice bags at $ 1.25, with a profit margin of 0.2'
You can str to convert a value of any data type into a string.
str(23)
'23'
str(23.432)
'23.432'
str(True)
'True'
str(the_3_musketeers)
"['Athos', 'Porthos', 'Aramis']"
Sign In
Note that all string methods return new values and DO NOT change the existing string. You can find a full
list of string methods here: https://www.w3schools.com/python/python_ref_string.asp.
Strings also support the comparison operators == and != for checking whether two strings are equal.
first_name = "John"
first_name == "Doe"
False
first_name == "John"
True
first_name != "Jane"
True
We've looked at the primitive data types in Python. We're now ready to explore non-primitive data
structures, also known as containers.
Before continuing, let us run jovian.commit once again to record another snapshot of our notebook.
jovian.commit()
'https://jovian.ai/samanvitha/python-variables-and-data-types'
Running jovian.commit multiple times within a notebook records new versions automatically. You will
continue to have access to all the previous versions of your notebook, using the versions dropdown on the
notebook's Jovian.
List
A list in Python is an ordered collection of values. Lists can hold values of different data types and support
operations to add, remove, and change values. Lists have the type list .
To create a list, enclose a sequence of values within square brackets [ and ] , separated by commas.
Sign In
fruits
type(fruits)
list
Let's try creating a list containing values of different data types, including another list.
a_list
empty_list = []
empty_list
[]
To determine the number of values in a list, use the len function. You can use len to determine the
number of values in several other data types.
len(fruits)
Number of fruits: 3
len(a_list)
len(empty_list)
0
You can access an element from the list using its index, e.g., fruits[2] returns the element at index 2 Sign In
within the list fruits . The starting index of a list is 0.
fruits[0]
'apple'
fruits[1]
'banana'
fruits[2]
'cherry'
If you try to access an index equal to or higher than the length of the list, Python returns an IndexError .
fruits[3]
---------------------------------------------------------------------------
<ipython-input-152-7ceeafd384d7> in <module>
----> 1 fruits[3]
fruits[4]
---------------------------------------------------------------------------
<ipython-input-153-b8c91da6ba3a> in <module>
----> 1 fruits[4]
You can use negative indices to access elements from the end of a list, e.g., fruits[-1] returns the
last element, fruits[-2] returns the second last element, and so on.
fruits[-1]
'cherry'
fruits[-2]
'banana'
fruits[-3] Sign In
'apple'
fruits[-4]
---------------------------------------------------------------------------
<ipython-input-157-1cb2d66442ee> in <module>
----> 1 fruits[-4]
You can also access a range of values from the list. The result is itself a list. Let us look at some
examples.
a_list
len(a_list)
a_list[2:5]
Note that the range 2:5 includes the element at the start index 2 but does not include the element at
the end index 5 . So, the result has 3 values (index 2 , 3 , and 4 ).
Here are some experiments you should try out (use the empty cells below):
Try setting one or both indices of the range are larger than the size of the list, e.g., a_list[2:10]
Try setting the start index of the range to be larger than the end index, e.g., a_list[12:10]
Try leaving out the start or end index of a range, e.g., a_list[2:] or a_list[:5]
Try using negative indices for the range, e.g., a_list[-2:-5] or a_list[-5:-2] (can you explain the
results?)
The flexible and interactive nature of Jupyter notebooks makes them an excellent tool for learning and
experimentation. If you are new to Python, you can resolve most questions as soon as they arise simply
by typing the code into a cell and executing it. Let your curiosity run wild, discover what Python is
capable of and what it isn't!
Sign In
You can also change the value at a specific index within a list using the assignment operation.
fruits
fruits[1] = 'blueberry'
fruits
A new value can be added to the end of a list using the append method.
fruits.append('dates')
fruits
A new value can also be inserted at a specific index using the insert method.
fruits.insert(1, 'banana')
fruits
You can remove a value from a list using the remove method.
fruits.remove('blueberry')
fruits
['apple', 'banana', 'cherry', 'dates'] Sign In
What happens if a list has multiple instances of the value passed to .remove ? Try it out.
To remove an element from a specific index, use the pop method. The method also returns the removed
element.
fruits
fruits.pop(1)
'banana'
fruits
If no index is provided, the pop method removes the last element of the list.
fruits.pop()
'dates'
fruits
['apple', 'cherry']
You can test whether a list contains a value using the in operator.
'pineapple' in fruits
False
'cherry' in fruits
True
To combine two or more lists, use the + operator. This operation is also called concatenation.
fruits Sign In
['apple', 'cherry']
more_fruits
To create a copy of a list, use the copy method. Modifying the copied list does not affect the original.
more_fruits_copy = more_fruits.copy()
more_fruits_copy
more_fruits_copy.remove('pineapple')
more_fruits_copy.pop()
more_fruits_copy
more_fruits
Note that you cannot create a copy of a list by simply creating a new variable using the assignment
operator = . The new variable will point to the same list, and any modifications performed using either
variable will affect the other.
more_fruits
more_fruits_not_a_copy = more_fruits
more_fruits_not_a_copy.remove('pineapple')
more_fruits_not_a_copy.pop()
'banana'
more_fruits_not_a_copy Sign In
more_fruits
Just like strings, there are several in-built methods to manipulate a list. However, unlike strings, most list
methods modify the original list rather than returning a new one. Check out some common list operations
here: https://www.w3schools.com/python/python_ref_list.asp .
Following are some exercises you can try out with list methods (use the blank code cells below):
Tuple
A tuple is an ordered collection of values, similar to a list. However, it is not possible to add, remove, or
modify values in a tuple. A tuple is created by enclosing values within parentheses ( and ) , separated
by commas.
Any data structure that cannot be modified after creation is called immutable. You can think of tuples as
immutable lists.
fruits[0]
'apple'
fruits[-2]
'cherry'
'dates' in fruits
True
fruits[0] = 'avocado'
---------------------------------------------------------------------------
<ipython-input-195-eea1d48cc8b5> in <module>
fruits.append('blueberry')
---------------------------------------------------------------------------
<ipython-input-196-e5ea20adaaf8> in <module>
----> 2 fruits.append('blueberry')
fruits.remove('apple')
---------------------------------------------------------------------------
<ipython-input-197-37543d45b6b4> in <module>
You can also skip the parantheses ( and ) while creating a tuple. Python automatically converts
comma-separated values into a tuple.
the_3_musketeers
You can also create a tuple with just one element by typing a comma after it. Just wrapping it with
parentheses ( and ) won't make it a tuple.
single_element_tuple = 4,
single_element_tuple
(4,)
another_single_element_tuple = (4,)
another_single_element_tuple
(4,)
not_a_tuple = (4)
not_a_tuple
Tuples are often used to create multiple variables with a single statement.
point = (3, 4)
point_x
3
Sign In
point_y
You can convert a list into a tuple using the tuple function, and vice versa using the list function
Tuples have just two built-in methods: count and index . Can you figure out what they do? While you
look could look for documentation and examples online, there's an easier way to check a method's
documentation, using the help function.
help(a_tuple.count)
Within a Jupyter notebook, you can also start a code cell with ? and type the name of a function or
method. When you execute this cell, you will see the function/method's documentation in a pop-up
window.
?a_tuple.index
Try using count and index with a_tuple in the code cells below.
Dictionary
A dictionary is an unordered collection of items. Each item stored in a dictionary has a key and value. You
can use a key to retrieve the corresponding value from the dictionary. Dictionaries have the type dict . Sign In
Dictionaries are often used to store many pieces of information e.g. details about a person, in a single
variable. Dictionaries are created by enclosing key-value pairs within braces or curly brackets { and } .
person1 = {
'sex': 'Male',
'age': 32,
'married': True
person1
person2
type(person1)
dict
person1['name']
'John Doe'
person1['married']
True
person2['name']
'Jane Judy'
person1['address']
---------------------------------------------------------------------------
Sign In
KeyError Traceback (most recent call last)
<ipython-input-223-f2b8bd2476d4> in <module>
----> 1 person1['address']
KeyError: 'address'
You can also use the get method to access the value associated with a key.
person2.get("name")
'Jane Judy'
The get method also accepts a default value, returned if the key is not present in the dictionary.
person2.get("address", "Unknown")
'Unknown'
You can check whether a key is present in a dictionary using the in operator.
'name' in person1
True
'address' in person1
False
You can change the value associated with a key using the assignment operator.
person2['married']
False
person2['married'] = True
person2['married']
True
The assignment operator can also be used to add new key-value pairs to the dictionary.
person1
person1
'sex': 'Male',
'age': 32,
'married': True,
To remove a key and the associated value from a dictionary, use the pop method.
person1.pop('address')
person1
Dictionaries also provide methods to view the list of keys, values, or key-value pairs inside it.
person1.keys()
person1.values()
person1.items()
person1.items()[1]
---------------------------------------------------------------------------
<ipython-input-239-b9fb361f2a9e> in <module>
----> 1 person1.items()[1]
The results of keys , values , and items look like lists. However, they don't support the indexing
operator [] for retrieving elements.
Can you figure out how to access an element at a specific index from these results? Try it below. Hint: Use
the list function Sign In
Dictionaries provide many other methods. You can learn more about them here:
https://www.w3schools.com/python/python_ref_dictionary.asp .
Here are some experiments you can try out with dictionaries (use the empty cells below):
What happens if you use the same key multiple times while creating a dictionary?
How can you create a copy of a dictionary (modifying the copy should not change the original)?
Can the value associated with a key itself be a dictionary?
How can you add the key-value pairs from one dictionary into another dictionary? Hint: See the update
method.
Can the dictionary's keys be something other than a string, e.g., a number, boolean, list, etc.?
Further Reading
We've now completed our exploration of variables and common data types in Python. Following are some
resources to learn more about data types in Python:
You are now ready to move on to the next tutorial: Branching using conditional statements and loops in
Python
Let's save a snapshot of our notebook one final time using jovian.commit .
Sign In
jovian.commit()
'https://jovian.ai/samanvitha/python-variables-and-data-types'
10. Are variable names case-sensitive? Do a_variable, A_Variable, and A_VARIABLE represent the same
variable or different ones?
19. What kind of data does the Integer data type represent?
20. What are the numerical limits of the integer data type?
21. What kind of data does the float data type represent?
Sign In
22. How does Python decide if a given number is a float or an integer?
23. How can you create a variable which stores a whole number, e.g., 4 but has the float data type?
24. How do you create floats representing very large (e.g., 6.023 x 10^23) or very small numbers
(0.000000123)?
31. What are the data types of the results of the division operators / and //?
32. What kind of data does the Boolean data type represent?
33. Which types of Python operators return booleans as a result?
34. What happens if you try to use a boolean in arithmetic operation?
39. What kind of data does the None data type represent?
40. What is the purpose of None?
41. What kind of data does the String data type represent?
42. What are the different ways of creating strings in Python?
43. What is the difference between strings creating using single quotes, i.e. ' and ' vs. those created using
double quotes, i.e. " and "?
44. How do you create multi-line strings in Python?
58. How do you remove whitespace from the beginning and end of a string?
59. What is the string .format method used for? Can you give an example?
60. What are the benefits of using the .format method instead of string concatenation?
61. How do you convert a value of another type to a string?
62. How do you check if two strings have the same value?
63. Where can you find the list of all the methods supported by strings?
71. What is the smallest and largest index you can use to access elements from a list containing five
elements?
72. What happens if you try to access an index equal to or larger than the size of a list?
73. What happens if you try to access a negative index within a list?
74. How do you access a range of elements from a list?
75. How many elements does the list returned by the expression a_list[2:5] contain?
84. Does the expression a_new_list = a_list create a copy of the list a_list?
85. Where can you find the list of all the methods supported by lists?
91. What are the count and index method of a Tuple used for?
92. What is a dictionary in Python?
93. How do you create a dictionary?