First Steps with Python and Jupyter
Part 1 of "A Gentle Introduction to Programming with Python"
This tutorial is the first in a series of beginner-friendly tutorials on programming using the Python language. These tutorials take a practical coding-based approach, and the best way to learn the material is to execute the code and experiment with the examples.
The following topics are covered in this tutorial:
- Performing arithmetic operations using Python
- Solving multi-step problems using variables
- Evaluating conditions using Python
- Combining conditions with logical operators
- Adding text styles using Markdown
This tutorial is an executable Jupyter notebook. Click the Open in Colab button at the top of this page to execute the code.
Jupyter Notebooks: This notebook is 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 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 "Edit > Clear All Outputs" and "Runtime > Restart Session" menu option to clear all outputs and start again from the top.
Performing Arithmetic Operations using Python
Let's begin by using Python as a calculator. You can write and execute Python using a code cell within Jupyter.
Working with Cells: To create a new cell within Jupyter, you can select "Insert > Insert Cell Below" from the menu bar or just press the "+" button on the toolbar. You can also use the keyboard shortcut
Esc+Bto create a new cell. Once a cell is created, click on it to select it. You can then change the cell type to code or markdown (text) using "Cell > Cell Type" menu option. You can also use the keyboard shortcutsEsc+YandEsc+M. Double click a cell to edit the content within the cell. To apply your changes and run a cell, use the "Cell > Run Cells" menu option or click the "Run" button on the toolbar or just use the keyboard shortcutShift+Enter. You can see a full list of keyboard shortcuts using the "Help > Keyboard Shortcuts" menu option.
Run the code cells below to perform calculations and view their result. Try changing the numbers and run the changed cells again to see updated results. Can you guess what the //, % and ** operators are used for?
2 + 3 + 91499 - 732623.54 * -1432-33709.28100 / 714.285714285714286100 // 714100 % 725 ** 3125As you might expect, certain operators like / and * take precendence over other operators like + and - as per mathematical conventions. You can use parantheses i.e. ( and ) to specify the order in which operations are performed.
((2 + 5) * (17 - 3)) / (4 ** 3)1.53125Python supports the following arithmetic operators:
| Operator | Purpose | Example | Result |
|---|---|---|---|
+ | Addition | 2 + 3 | 5 |
- | Subtraction | 3 - 2 | 1 |
* | Multiplication | 8 * 12 | 96 |
/ | Division | 100 / 7 | 14.28.. |
// | Floor Division | 100 // 7 | 14 |
% | Modulus/Remainder | 100 % 7 | 2 |
** | Exponent | 5 ** 3 | 125 |
Try solving some simple problems from this page: https://www.math-only-math.com/worksheet-on-word-problems-on-four-operations.html . You can use the empty cells below and add more cells if required.
Solving multi-step problems using variables
Let's try solving the following word problem using Python:
A grocery store sells a bag of ice for $1.25, and makes 20% profit. If it sells 500 bags of ice, how much total profit does it make?
We can list out the information provided, and gradually convert the word problem into a mathematical expression which can be evaluated using Python.
Cost of ice bag ($) = 1.25
Profit margin = 20% = .2
Profit per bag ($) = profit margin * cost of ice bag = .2 * 1.25
No. of bags = 500
Total profit = no. of bags * profit per bag = 500 * (.2 * 1.25)
500 * (.2 * 1.25)125.0Thus, the grocery store makes a total profit of $125.0 . While this is a reasonable way to solve a problem, it's not quite clear by looking at the code cell what the numbers represent. We can give names to each of the numbers by creating Python variables.
Variables: While working with a programming language such as Python, informations is stored in variables. You can think of variables as containers for storing data. The data stored within a variable is called it's value.
cost_of_ice_bag = 1.25profit_margin = .2number_of_bags = 500The variables cost_of_ice_bag, profit_margin and number_of_bags now contain the information provided in the word problem. We can check the value of a variable by typing its name into a cell, and we can combine variables using arithmetic operations to create other variables.
Tip: While typing the name of an existing variable in a code cell within Jupyter, you can type the first few characters and press the
Tabkey to autocomplete the variable's name. Try typingproin a code cell below and pressTabto autocomplete toprofit_margin.
profit_margin0.2profit_per_bag = cost_of_ice_bag * profit_marginprofit_per_bag0.25total_profit = number_of_bags * profit_per_bagtotal_profit125.0If you try to see the value of a variable that has not been defined i.e. given a value using the assignment statement variable_name = value, then Python shows an error.
net_profit---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/tmp/ipython-input-2924770564.py in <cell line: 0>()
----> 1 net_profit
NameError: name 'net_profit' is not definedStoring and manipulating data using appropriately named variables is a great way to explain what your code does.
Let's display the result of the word problem using a friendly message. We can do this using the print function.
Functions: A function is a reusable set of instructions. A function takes one or more inputs, performs certain operations, and often returns an output. Python provides many in-built functions like
print("The grocery store makes a total profit of $", total_profit)The grocery store makes a total profit of $ 125.0
"this is some text"), numbers, variables, mathematical expressions etc. We'll learn more about variables & functions in the next section.
Creating a code cell for each variable or mathematical operation can get tedious. Fortunately, Jupyter allows you write multiple lines of code within a single code cell. Let's rewrite the solution to our word problem within a single cell.
# Store input data in variables
cost_of_ice_bag = 1.25
profit_margin = .2
number_of_bags = 500
# Perform the required calculations
profit_per_bag = cost_of_ice_bag * profit_margin
total_profit = number_of_bags * profit_per_bag
# Display the result
print("The grocery store makes a total profit of $", total_profit)The grocery store makes a total profit of $ 125.0
Note that we're using the # character to add comments within our code.
Comments: Comments and blank lines are ignored during execution, but they are useful for providing information to other humans (including yourself) about what the code does. Comments can be inline (at the end of some code), on a separate line, or even span multiple lines.
Inline and single line comments start with #, whereas multi-line comments begin and end with three quotes i.e """. Here are some examples of code comments:
my_favorite_number = 1 # an inline comment# This comment gets its own line
my_least_favorite_number = 3"""This is a multi-line comment.
Write as little or as much as you'd like.
Comments are really helpful for people reading
your code, but try to keep them short & to-the-point.
Also, if you use good variable names, then your code is
often self explanatory, and you may not even need comments!
"""
a_neutral_number = 5Evaluating conditions using Python
Apart from arithmetic operations, Python also provides several oprations for comparing numbers & variables.
| Operator | Description |
|---|---|
== | Check if operands are equal |
!= | Check if operands are not equal |
> | Check if left operand is greater than right operand |
< | Check if left operand is less than right operand |
>= | Check if left operand is greater than or equal to right operand |
<= | Check if left operand is less than or equal to right operand |
The result of a comparision operation is either True or False (note the uppercase T and F). These are special keywords in Python. Let's try out some experiment with comparision operators.
my_favorite_number = 1
my_least_favorite_number = 5
a_neutral_number = 3# Equality check - True
my_favorite_number == 1True# Equality check - False
my_favorite_number == my_least_favorite_numberFalse# Not equal check - True
my_favorite_number != a_neutral_numberTrue# Not equal check - False
a_neutral_number != 3False# Greater than check - True
my_least_favorite_number > a_neutral_numberTrue# Greater than check - False
my_favorite_number > my_least_favorite_numberFalse# Less than check - True
my_favorite_number < 10True# Less than check - False
my_least_favorite_number < my_favorite_numberFalse# Greater than or equal check - True
my_favorite_number >= 1True# Greater than or equal check - False
my_favorite_number >= 3False# Less than or equal check - True
3 + 6 <= 9True# Less than or equal check - False
my_favorite_number + a_neutral_number <= 3FalseJust like arithmetic operations, the result of a comparison opration can also be stored in a variable.
cost_of_ice_bag = 1.25
is_ice_bag_expensive = cost_of_ice_bag >= 10
print("Is the ice bag expensive?", is_ice_bag_expensive)Is the ice bag expensive? False
Combining conditions with logical operators
The logical operators and, or and not operate upon conditions and True & False values (also known as booleans). and and or operate on two conditions, whereas not operates on a single condition.
The and operator returns True when both the conditions evalute to True. Otherwise it returns False.
a | b | a and b |
|---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
my_favorite_number1my_favorite_number > 0 and my_favorite_number <= 3Truemy_favorite_number < 0 and my_favorite_number <= 3Falsemy_favorite_number > 0 and my_favorite_number >= 3FalseTrue and FalseFalseTrue and TrueTrueThe or operator returns True if at least one of the conditions evalute to True. It returns False only if both conditions are False.
a | b | a or b |
|---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
a_neutral_number = 3a_neutral_number == 3 or my_favorite_number < 0Truea_neutral_number != 3 or my_favorite_number < 0Falsemy_favorite_number < 0 or TrueTrueFalse or FalseFalseThe not operator returns False if a condition is True and True if the condition is False.
not a_neutral_number == 3Falsenot my_favorite_number < 0Truenot FalseTruenot TrueFalseLogical operators can be combined to form complex conditions. Use round brackets or parantheses ( and ) to indicate the order in which logical operators should be applied.
(2 > 3 and 4 <= 5) or not (my_favorite_number < 0 and True)Truenot (True and 0 < 1) or (False and True)FalseIf parantheses are not used, logical operators are applied from left to right.
not True and 0 < 1 or False and TrueFalseExperiment with arithmetic, conditional and logical operators in Python using the interactive nature of Jupyter notebook. We will learn more about variables and functions in future tutorials.
Adding text styles using Markdown
Adding explanations using text cells (like this one) is great way to make your notebook informative for other readers, and for yourself, if you need to refer back to it in the future. Double click on a text cell within Jupyter to edit it. In the edit mode, you'll notice that the text looks a little different (for instance the heading has a ## prefix. This text is writted using Markdown, a simple way to add styles to your text. Execute this cell to see the output without the special characters. You can switch back and forth between the source and the output to see how to create a specific style.
For, instance, you can use one or more # characters at the start of a line to create headers of different sizes:
Header 1
Header 2
Header 3
Header 4
To create a bulleted or numbered list, simply start a line with * or 1..
A bulleted list:
- Item 1
- Item 2
- Item 3
A numbered list:
- Apple
- Banana
- Pineapple
You can make some text bold using ** e.g. this is some bold text, or make it italic using * e.g. this is some italic text. You can also create links e.g. this is a link. Images are easily embedded too:

Another really nice feature of Markdown is ability to include blocks of code. Note that code blocks inside Markdown cells cannot be executed.
# Perform the required calculations
profit_per_bag = cost_of_ice_bag * profit_margin
total_profit = number_of_bags * profit_per_bag
# Display the result
print("The grocery store makes a total profit of $", total_profit)
You can learn the full syntax of Markdown here: https://learnxinyminutes.com/docs/markdown/
Further Reading and References
Following are some resources to learn about more arithmetic, conditional and logical operations in Python:
- Python Tutorial at W3Schools: https://www.w3schools.com/python/
- Practical Python Programming: https://dabeaz-course.github.io/practical-python/Notes/Contents.html
- Python official documentation: https://docs.python.org/3/tutorial/index.html
Now that you have taken your first steps with Python, you are ready to move on to the next tutorial.
A Quick Tour of Variables and Data Types in Python

This tutorial series is a beginner-friendly introduction to programming and data analysis using the Python programming language. 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.
This tutorial covers the following topics:
- Storing information using variables
- Primitive data types in Python: Integer, Float, Boolean, None and String
- Built-in data structures in Python: List, Tuple and Dictionary
- Methods and operators supported by built-in data types
Storing information using variables
Computers are useful for two purposes: storing information (also known as data) and performing operations on stored data. While working with a programming language such as Python, data is stored in variables. You can think of variables are containers for storing data. The data stored within a variable is called its value. Creating variables in Python is pretty easy, as we've already seen in the previous tutorial.
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.
color1, color2, color3 = "red", "green", "blue"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 = color5 = color6 = "magenta"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 = 10counter = counter + 1counter11The pattern var = var op something (where op is an arithmetic operator like +, -, *, /) is very common, so Python provides a shorthand syntax for it.
counter = 10# Same as `counter = counter + 4`
counter += 4counter14Variable names can be short (a, x, y, etc.) or descriptive ( my_favorite_color, profit_margin, the_3_musketeers, etc.). However, you must follow these rules while naming Python variables:
- 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, andA_VARIABLEare all different variables.
Here are some valid variable names:
a_variable = 23
is_today_Saturday = False
my_favorite_car = "Delorean"
the_3_musketeers = ["Athos", "Porthos", "Aramis"] 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.
a variable = 23 File "<ipython-input-20-b4f9daa715a5>", line 1
a variable = 23
^
SyntaxError: invalid syntax
is_today_$aturday = False File "<ipython-input-21-3785425ca227>", line 1
is_today_$aturday = False
^
SyntaxError: invalid syntax
my-favorite-car = "Delorean" File "<ipython-input-22-829f5ed5b10b>", line 1
my-favorite-car = "Delorean"
^
SyntaxError: cannot assign to operator
3_musketeers = ["Athos", "Porthos", "Aramis"] File "<ipython-input-23-41d8638a15bb>", line 1
3_musketeers = ["Athos", "Porthos", "Aramis"]
^
SyntaxError: invalid decimal literal
Built-in data types in Python
Any data or information stored within a Python variable has a type. You can view the type of data stored within a variable using the type function.
a_variable23type(a_variable)intis_today_SaturdayFalsetype(is_today_Saturday)boolmy_favorite_car'Delorean'type(my_favorite_car)strthe_3_musketeers['Athos', 'Porthos', 'Aramis']type(the_3_musketeers)listPython has several built-in data types for storing different kinds of information in variables. Following are some commonly used data types:
- Integer
- Float
- Boolean
- None
- String
- List
- Tuple
- 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 = 2020current_year2020type(current_year)intUnlike 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 = -23374038374832934334234317348343a_large_negative_number-23374038374832934334234317348343type(a_large_negative_number)intFloat
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.141592653589793238pi3.141592653589793type(pi)floatNote 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.0a_number3.0type(a_number)floatanother_number = 4.another_number4.0type(another_number)floatFloating point numbers can also be written using the scientific notation with an "e" to indicate the power of 10.
one_hundredth = 1e-2one_hundredth0.01type(one_hundredth)floatavogadro_number = 6.02214076e23avogadro_number6.02214076e+23type(avogadro_number)floatYou 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.0float(a_large_negative_number)-2.3374038374832935e+31int(pi)3int(avogadro_number)602214075999999987023872While performing arithmetic operations, integers are automatically converted to floats if any of the 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)floattype(45 * 3)inttype(10/3)floattype(10/2)floattype(10//2)intBoolean
Booleans represent one of 2 values: True and False. Booleans have the type bool.
is_today_Sunday = Trueis_today_SundayTruetype(is_today_Saturday)boolBooleans are generally the result of a comparison operation, e.g., ==, >=, etc.
cost_of_ice_bag = 1.25
is_ice_bag_expensive = cost_of_ice_bag >= 10is_ice_bag_expensiveFalsetype(is_ice_bag_expensive)boolBooleans are automatically converted to ints when used in arithmetic operations. True is converted to 1 and False is converted to 0.
5 + False53. + True4.0Any 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):
- The value
Falseitself - The integer
0 - The float
0.0 - The empty value
None - The empty text
"" - The empty list
[] - The empty tuple
() - The empty dictionary
{} - The empty set
set() - The empty range
range(0)
Everything else evaluates to True (a value that evaluates to True is often called a truthy value).
bool(False)Falsebool(0)Falsebool(0.0)Falsebool(None)Falsebool("")Falsebool([])Falsebool(())Falsebool({})Falsebool(set())Falsebool(range(0))Falsebool(True), bool(1), bool(2.0), bool("hello"), bool([1,2]), bool((2,3)), bool(range(10))(True, True, True, True, True, True, True)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 = Nonetype(nothing)NoneTypeString
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)strYou can use single quotes inside a string written with double quotes, and vice versa.
my_favorite_movie = "One Flew over the Cuckoo's Nest" my_favorite_movie"One Flew over the Cuckoo's Nest"my_favorite_pun = 'Thanks for explaining the word "many" to me, it means a lot.'my_favorite_pun'Thanks for explaining the word "many" to me, it means a lot.'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 \"This changes everything\"."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?"
Dad: "No sun."'''yet_another_pun'Son: "Dad, can you tell me what a solar eclipse is?" \nDad: "No sun."'Multiline strings are best displayed using the print function.
print(yet_another_pun)Son: "Dad, can you tell me what a solar eclipse is?"
Dad: "No sun."
a_music_pun = """
Two windmills are standing in a field and one asks the other,
"What kind of music do you like?"
The other says,
"I'm a big metal fan."
"""print(a_music_pun)
Two windmills are standing in a field and one asks the other,
"What kind of music do you like?"
The other says,
"I'm a big metal fan."
You can check the length of a string using the len function.
len(my_favorite_movie)31Note 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'len(multiline_string)3A string can be converted into a list of characters using list function.
list(multiline_string)['a', '\n', 'b']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 todayTrue'Sun' in todayFalseTwo 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.
full_name = "Derek O'Brien"greeting = "Hello"greeting + full_name"HelloDerek O'Brien"greeting + " " + full_name + "!" # additional space"Hello Derek 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".capitalize() # changes first character to uppercase'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.
another_day = today.replace("Satur", "Wednes")another_day'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(",")['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']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 some space in the middle.. "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
# Template for output message
output_template = """If a grocery store sells ice bags at $ {} per bag, with a profit margin of {} %,
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 {} %,
then the total profit it makes by selling {} ice bags is $ {}.
# Inserting values into the string
total_profit = cost_of_ice_bag * profit_margin * number_of_bags
output_message = output_template.format(cost_of_ice_bag, profit_margin*100, number_of_bags, total_profit)
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 margin of " + profit_margin---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<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
TypeError: can only concatenate str (not "float") to str"If a grocery store sells ice bags at $ " + str(cost_of_ice_bag) + ", with a profit margin of " + str(profit_margin)'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'the_3_musketeers = ["Athos", "Porthos", "Aramis"]
str(the_3_musketeers)"['Athos', 'Porthos', 'Aramis']"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"Falsefirst_name == "John"Truefirst_name != "Jane"TrueList
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.
fruits = ['apple', 'banana', 'cherry']fruits['apple', 'banana', 'cherry']type(fruits)listLet's try creating a list containing values of different data types, including another list.
a_list = [23, 'hello', None, 3.14, fruits, 3 <= 5]a_list[23, 'hello', None, 3.14, ['apple', 'banana', 'cherry'], True]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)3print("Number of fruits:", len(fruits))Number of fruits: 3
len(a_list)6len(empty_list)0You can access an element from the list using its index, e.g., fruits[2] returns the element at index 2 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]---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-152-7ceeafd384d7> in <module>
----> 1 fruits[3]
IndexError: list index out of rangefruits[4]---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-153-b8c91da6ba3a> in <module>
----> 1 fruits[4]
IndexError: list index out of rangeYou 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]'apple'fruits[-4]---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-157-1cb2d66442ee> in <module>
----> 1 fruits[-4]
IndexError: list index out of rangeYou can also access a range of values from the list. The result is itself a list. Let us look at some examples.
a_list = [23, 'hello', None, 3.14, fruits, 3 <= 5]a_list[23, 'hello', None, 3.14, ['apple', 'banana', 'cherry'], True]len(a_list)6a_list[2:5][None, 3.14, ['apple', 'banana', 'cherry']]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.,
list_a[2:10] - Try leaving out the start or end index of a range, e.g.,
a_list[2:]ora_list[:5] - Try using negative indices for the range, e.g.,
a_list[-2:-5]ora_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!
You can also change the value at a specific index within a list using the assignment operation.
fruits['apple', 'banana', 'cherry']fruits[1] = 'blueberry'fruits['apple', 'blueberry', 'cherry']A new value can be added to the end of a list using the append method.
fruits.append('dates')fruits['apple', 'blueberry', 'cherry', 'dates']A new value can also be inserted at a specific index using the insert method.
fruits.insert(1, 'banana')fruits['apple', 'banana', 'blueberry', 'cherry', 'dates']You can remove a value from a list using the remove method.
fruits.remove('blueberry')fruits['apple', 'banana', 'cherry', 'dates']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['apple', 'banana', 'cherry', 'dates']fruits.pop(1)'banana'fruits['apple', 'cherry', 'dates']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 fruitsFalse'cherry' in fruitsTrueTo combine two or more lists, use the + operator. This operation is also called concatenation.
fruits['apple', 'cherry']more_fruits = fruits + ['pineapple', 'tomato', 'guava'] + ['dates', 'banana']more_fruits['apple', 'cherry', 'pineapple', 'tomato', 'guava', 'dates', 'banana']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['apple', 'cherry', 'pineapple', 'tomato', 'guava', 'dates', 'banana']# Modify the copy
more_fruits_copy.remove('pineapple')
more_fruits_copy.pop()
more_fruits_copy['apple', 'cherry', 'tomato', 'guava', 'dates']# Original list remains unchanged
more_fruits['apple', 'cherry', 'pineapple', 'tomato', 'guava', 'dates', 'banana']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['apple', 'cherry', 'pineapple', 'tomato', 'guava', 'dates', 'banana']more_fruits_not_a_copy = more_fruitsmore_fruits_not_a_copy.remove('pineapple')
more_fruits_not_a_copy.pop()'banana'more_fruits_not_a_copy['apple', 'cherry', 'tomato', 'guava', 'dates']more_fruits['apple', 'cherry', 'tomato', 'guava', 'dates']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):
- Reverse the order of elements in a list
- Add the elements of one list at the end of another list
- Sort a list of strings in alphabetical order
- Sort a list of numbers in decreasing order
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.
Let's try some experiments with tuples.
fruits = ('apple', 'cherry', 'dates')# check no. of elements
len(fruits)3# get an element (positive index)
fruits[0]'apple'# get an element (negative index)
fruits[-2]'cherry'# check if it contains an element
'dates' in fruitsTrue# try to change an element
fruits[0] = 'avocado'---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-195-eea1d48cc8b5> in <module>
1 # try to change an element
----> 2 fruits[0] = 'avocado'
TypeError: 'tuple' object does not support item assignment# try to append an element
fruits.append('blueberry')---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-196-e5ea20adaaf8> in <module>
1 # try to append an element
----> 2 fruits.append('blueberry')
AttributeError: 'tuple' object has no attribute 'append'# try to remove an element
fruits.remove('apple')---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-197-37543d45b6b4> in <module>
1 # try to remove an element
----> 2 fruits.remove('apple')
AttributeError: 'tuple' object has no attribute 'remove'You can also skip the parantheses ( and ) while creating a tuple. Python automatically converts comma-separated values into a tuple.
the_3_musketeers = 'Athos', 'Porthos', 'Aramis'the_3_musketeers('Athos', 'Porthos', 'Aramis')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_tuple4Tuples are often used to create multiple variables with a single statement.
point = (3, 4)point_x, point_y = pointpoint_x3point_y4You can convert a list into a tuple using the tuple function, and vice versa using the list function
tuple(['one', 'two', 'three'])('one', 'two', 'three')list(('Athos', 'Porthos', 'Aramis'))['Athos', 'Porthos', 'Aramis']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.
a_tuple = 23, "hello", False, None, 23, 37, "hello"help(a_tuple.count)Help on built-in function count:
count(value, /) method of builtins.tuple instance
Return number of occurrences of value.
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.indexTry 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.
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 = {
'name': 'John Doe',
'sex': 'Male',
'age': 32,
'married': True
}person1{'name': 'John Doe', 'sex': 'Male', 'age': 32, 'married': True}Dictionaries can also be created using the dict function.
person2 = dict(name='Jane Judy', sex='Female', age=28, married=False)person2{'name': 'Jane Judy', 'sex': 'Female', 'age': 28, 'married': False}type(person1)dictKeys can be used to access values using square brackets [ and ].
person1['name']'John Doe'person1['married']Trueperson2['name']'Jane Judy'If a key isn't present in the dictionary, then a KeyError is thrown.
person1['address']---------------------------------------------------------------------------
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 person1True'address' in person1FalseYou can change the value associated with a key using the assignment operator.
person2['married']Falseperson2['married'] = Trueperson2['married']TrueThe assignment operator can also be used to add new key-value pairs to the dictionary.
person1{'name': 'John Doe', 'sex': 'Male', 'age': 32, 'married': True}person1['address'] = '1, Penny Lane'person1{'name': 'John Doe',
'sex': 'Male',
'age': 32,
'married': True,
'address': '1, Penny Lane'}To remove a key and the associated value from a dictionary, use the pop method.
person1.pop('address')'1, Penny Lane'person1{'name': 'John Doe', 'sex': 'Male', 'age': 32, 'married': True}Dictionaries also provide methods to view the list of keys, values, or key-value pairs inside it.
person1.keys()dict_keys(['name', 'sex', 'age', 'married'])person1.values()dict_values(['John Doe', 'Male', 32, True])person1.items()dict_items([('name', 'John Doe'), ('sex', 'Male'), ('age', 32), ('married', True)])person1.items()[1]---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-239-b9fb361f2a9e> in <module>
----> 1 person1.items()[1]
TypeError: 'dict_items' object is not subscriptableThe 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
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
updatemethod. - 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:
- Python official documentation: https://docs.python.org/3/tutorial/index.html
- Python Tutorial at W3Schools: https://www.w3schools.com/python/
- Practical Python Programming: https://dabeaz-course.github.io/practical-python/Notes/Contents.html
Questions for Revision
Try answering the following questions to test your understanding of the topics covered in this notebook:
- What is a variable in Python?
- How do you create a variable?
- How do you check the value within a variable?
- How do you create multiple variables in a single statement?
- How do you create multiple variables with the same value?
- How do you change the value of a variable?
- How do you reassign a variable by modifying the previous value?
- What does the statement
counter += 4do? - What are the rules for naming a variable?
- Are variable names case-sensitive? Do
a_variable,A_Variable, andA_VARIABLErepresent the same variable or different ones? - What is Syntax? Why is it important?
- What happens if you execute a statement with invalid syntax?
- How do you check the data type of a variable?
- What are the built-in data types in Python?
- What is a primitive data type?
- What are the primitive data types available in Python?
- What is a data structure or container data type?
- What are the container types available in Python?
- What kind of data does the Integer data type represent?
- What are the numerical limits of the integer data type?
- What kind of data does the float data type represent?
- How does Python decide if a given number is a float or an integer?
- How can you create a variable which stores a whole number, e.g., 4 but has the float data type?
- How do you create floats representing very large (e.g., 6.023 x 10^23) or very small numbers (0.000000123)?
- What does the expression
23e-12represent? - Can floats be used to store numbers with unlimited precision?
- What are the differences between integers and floats?
- How do you convert an integer to a float?
- How do you convert a float to an integer?
- What is the result obtained when you convert 1.99 to an integer?
- What are the data types of the results of the division operators
/and//? - What kind of data does the Boolean data type represent?
- Which types of Python operators return booleans as a result?
- What happens if you try to use a boolean in arithmetic operation?
- How can any value in Python be covered to a boolean?
- What are truthy and falsy values?
- What are the values in Python that evaluate to False?
- Give some examples of values that evaluate to True.
- What kind of data does the None data type represent?
- What is the purpose of None?
- What kind of data does the String data type represent?
- What are the different ways of creating strings in Python?
- What is the difference between strings creating using single quotes, i.e.
'and'vs. those created using double quotes, i.e."and"? - How do you create multi-line strings in Python?
- What is the newline character,
\n? - What are escaped characters? How are they useful?
- How do you check the length of a string?
- How do you convert a string into a list of characters?
- How do you access a specific character from a string?
- How do you access a range of characters from a string?
- How do you check if a specific character occurs in a string?
- How do you check if a smaller string occurs within a bigger string?
- How do you join two or more strings?
- What are "methods" in Python? How are they different from functions?
- What do the
.lower,.upperand.capitalizemethods on strings do? - How do you replace a specific part of a string with something else?
- How do you split the string "Sun,Mon,Tue,Wed,Thu,Fri,Sat" into a list of days?
- How do you remove whitespace from the beginning and end of a string?
- What is the string
.formatmethod used for? Can you give an example? - What are the benefits of using the
.formatmethod instead of string concatenation? - How do you convert a value of another type to a string?
- How do you check if two strings have the same value?
- Where can you find the list of all the methods supported by strings?
- What is a list in Python?
- How do you create a list?
- Can a Python list contain values of different data types?
- Can a list contain another list as an element within it?
- Can you create a list without any values?
- How do you check the length of a list in Python?
- How do you retrieve a value from a list?
- What is the smallest and largest index you can use to access elements from a list containing five elements?
- What happens if you try to access an index equal to or larger than the size of a list?
- What happens if you try to access a negative index within a list?
- How do you access a range of elements from a list?
- How many elements does the list returned by the expression
a_list[2:5]contain? - What do the ranges
a_list[:2]anda_list[2:]represent? - How do you change the item stored at a specific index within a list?
- How do you insert a new item at the beginning, middle, or end of a list?
- How do you remove an item from al list?
- How do you remove the item at a given index from a list?
- How do you check if a list contains a value?
- How do you combine two or most lists to create a larger list?
- How do you create a copy of a list?
- Does the expression
a_new_list = a_listcreate a copy of the lista_list? - Where can you find the list of all the methods supported by lists?
- What is a Tuple in Python?
- How is a tuple different from a list?
- Can you add or remove elements in a tuple?
- How do you create a tuple with just one element?
- How do you convert a tuple to a list and vice versa?
- What are the
countandindexmethod of a Tuple used for? - What is a dictionary in Python?
- How do you create a dictionary?
- What are keys and values?
- How do you access the value associated with a specific key in a dictionary?
- What happens if you try to access the value for a key that doesn't exist in a dictionary?
- What is the
.getmethod of a dictionary used for? - How do you change the value associated with a key in a dictionary?
- How do you add or remove a key-value pair in a dictionary?
- How do you access the keys, values, and key-value pairs within a dictionary?