BRIEF CONTENTS
1. WRITING FIRTST CODE
#1 Hello World
#2 Comments in Code
2. DATA TYPE AND VARIABLE
2.1. Variable
#3 Variable Assignment
2.2. Number
#4 Integer
#5 Floating Point Number
2.3. Boolean
#6 Boolean Data Type
2.4. String
#7 String Data Type
#8 Displaying Various Data Type
#9 Length of String
#10 Accessing Character
Column: Index
2.5. String Slicing
#11 String Slicing
2.6. Arithmetic Operator
#12 Addition
#13 Subtraction
#14 Multiplication
#15 Division
2.7. Comparison Operator
#16 Comparison Operator
2.8. Assignment Operator
#17 Assigning Value
2.9. Logical Operator
#18 Logical Expression
2.10. String Operation
#19 Concatenation
#20 Search
3. DATA STRUCTURE
3.1. List
#21 Creating List
#22 List Slicing
#23 Number in Range
#24 Nested List
#25 Sequential Indexing
#26 Merging List
3.2. Common List Operation
#27 Adding Element
#28 Inserting Element
#29 Removing Last Element
#30 Removing Particular Element
#31 Find Index of Element
#32 Verify Existence of Element
#33 List Sort
3.3. Tuple
#34 Creating Tuple
#35 Merging Tuple
#36 Nested Tuple
#37 Find Index of Element
#38 Verify Existence of Element
3.4. Dictionary
#39 Creating Dictionary 1
#40 Creating Dictionary 2
#41 Accessing Value
3.5. Dictionary Operation
#42 Adding/Updating Entry
#43 Removing Entry
#44 Using Removed Entry
#45 Length of Dictionary
#46 Checking Key Existence
#47 Copying Content of Dictionary
3.6. Set
#48 Creating Set 1
#49 Creating Set 2
#50 Length of Set
#51 Adding Element
#52 Removing Element
3.7. Set Theory Operation
#53 Union of Sets
#54 Intersection of Sets
#55 Difference of Sets
3.8. Data Structure Conversion
#56 Converting to List
#57 Converting to Tuple
#58 Converting to Set
#59 Converting to Dictionary
4. CONDITIONAL STATEMENTS
4.1. If Statement
#60 Flow of If Statement
#61 Condition with Logical Operator
#62 Nested If Statement
4.2. If Else Statement
#63 If Else Statement
4.3. If Elif Else Statement
#64 If Elif Else Statement
#65 Multiple Elif Statement
5. LOOPS
5.1. For Loop
#66 Looping Through Range
#67 Looping Through List
5.2. Nested For Loop
#68 Nested For Loop
#69 Break Statement
#70 Continue Statement
#71 Pass Statement
5.3. While Loop
#72 While Loop
#73 While Else
#74 Break Statement
#75 Continue Statement
#76 Pass Statement
6. FUNCTION
6.1. Built-in Math function
#77 Min function
#78 Max function
Column: Why Use Function?
6.2. Built-In String Function
#79 Finding String
#80 Replacing String
#81 Changing Letter Case
6.3. Type Conversion
#82 Converting Data to Integer
#83 Converting Data to Float
#84 Converting Data to String
6.4. User-defined Function
#85 Creating Function
#86 Function Parameter
#87 Return Statement
6.5. Lambda
#88 Lambda Syntax 1
#89 Lambda Syntax 2
#90 If Else Statement
7. LIBRARY
7.1. Python Standard Library
#91 Importing Datetime Module
Column: Python Standard Library
#92 Importing Individual Class
#93 Importing and Naming Module
Python Workbook for Beginners
1. WRITING FIRTST CODE
#1 Hello World
Exercise ★
Display the words "Hello World" on your screen.
Solution
●●● Input
print("Hello World")
●●● Output
Hello World
Note
Since Python is one of the most readable languages, you can print
data to the screen simply by using the print statement.
#2 Comments in Code
Exercise ★
Write your comments in the code.
Solution
●●● Input
print("Hello World")
# This line prints Hello World
●●● Output
Hello World
Note
Comments can be written using the # character. Comments do not
affect the code in any way. Comments are used to describe what is
going on in the code.
2. DATA TYPE AND VARIABLE
2.1. Variable
#3 Variable Assignment
Exercise ★
Assign a script to a variable and display the script.
Solution
●●● Input
fruit = "apple"
# Assigning a script to a variable
print(fruit)
fruit = "orange"
# Assigning a new script
print(fruit)
●●● Output
apple
orange
Note
You can assign a value to a variable using the = operator. Variable
is mutable. Therefore, the value of a variable can always be
replaced.
2.2. Number
#4 Integer
Exercise ★
Display the positive and negative whole numbers.
Solution
●●● Input
num = 12345
# Assigning an integer to a variable
print(num)
num = -12345
# Assigning a new integer
print(num)
●●● Output
12345
-12345
Note
The integer data type basically represents whole numbers.
#5 Floating Point Number
Exercise ★
Display the positive and negative decimal numbers.
Solution
●●● Input
num = 1.2345
# Assigning a positive float to a variable
print(num)
num = -1.2345
# Assigning a negative float to a variable
print(num)
●●● Output
1.2345
-1.2345
Note
A floating point number (float) is a positive or negative decimal
number.
2.3. Boolean
#6 Boolean Data Type
Exercise ★
Display the Boolean data type.
Solution
●●● Input
print(True)
print(False)
#The first letter of a bool needs to be capitalized
●●● Output
True
False
Note
The Boolean data type allows you to choose between two values
(True and False).
2.4. String
#7 String Data Type
Exercise ★
Display the string data type.
Solution
●●● Input
print("apple pie")
# Double quotation marks
print('apple pie')
# Single quotation marks
●●● Output
apple pie
apple pie
Note
The string is a collection of characters enclosed in single or double
quotation marks.
#8 Displaying Various Data Type
Exercise ★
Display the various data types in a single print command.
Solution
●●● Input
print(10, 2.5, "Hello World")
●●● Output
10 2.5 Hello World
Note
You just have to separate multiple things using the comma to print
them in a single print command.
#9 Length of String
Exercise ★★
Display the length of a string.
Solution
●●● Input
my_string = "apple pie"
# 9 characters including space
print(len(my_string))
●●● Output
Note
The length of a string can be checked using the len statement.
#10 Accessing Character
Exercise ★★
Display the character in a string.
Solution
●●● Input
my_string = "apple pie"
first = my_string[0]
# Accessing the first character
print(first)
last = my_string[-1]
# Accessing the last character
print(last)
●●● Output
Note
Each character in the string can be accessed using its index. The
index must be enclosed in square brackets [] and added to the
string. Negative indexes start at the opposite end of the string. -1
index corresponds to the last character.
Column: Index
In a string, every character is given a numerical index based
on its position in the string.
The index of the first character in a string starts at 0.
Python strings are indexed from 0 to n-1, where n is the length
of the string.
2.5. String Slicing
#11 String Slicing
Exercise ★★
Display the substring of a string.
Solution
●●● Input
my_string = "apple pie"
print(my_string[0:5])
# From the start till before the 5th index
print(my_string[6:9])
# From the 6th till before the 9th index
●●● Output
apple
pie
Note
Slicing is the process of getting a part of a string (substring) using
the index of the string.
2.6. Arithmetic Operator
#12 Addition
Exercise ★
Add two numbers.
Solution
●●● Input
print(5 + 8)
●●● Output
13
Note
You can add two numbers together using the + operator.
#13 Subtraction
Exercise ★
Subtract one number from the other.
Solution
●●● Input
print(15 - 7)
●●● Output
Note
You can subtract one number from another using the - operator.
#14 Multiplication
Exercise ★
Multiply two numbers.
Solution
●●● Input
print(30 * 5)
●●● Output
150
Note
You can multiply two numbers together using the * operator.
#15 Division
Exercise ★
Divide one number by another.
Solution
●●● Input
print(30 / 10)
●●● Output
3.0
Note
You can divide one number by another using the / operator.
2.7. Comparison Operator
#16 Comparison Operator
Exercise ★
Compare the values using comparison operators.
Solution
●●● Input
print(5 > 3)
# 5 is greater than 3
print(5 < 3)
# 5 is less than 3
print(5 >= 3)
# 5 is greater than or equal to 3
print(5 <= 3)
# 5 is less than or equal to 3
print(5 is 3)
# Both have the same value
print(5 is not 5)
# Both have different values
print(5 == 3)
# Both are equal
print(5 != 3)
# Both are not equal
●●● Output
True
False
True
False
False
False
False
True
Note
The result of the comparison is always bool. If the comparison is
correct, the value of bool will be True. Otherwise, the value will be
False.
2.8. Assignment Operator
#17 Assigning Value
Exercise ★
Assign a value to a variable and replace that value with another
value.
Solution
●●● Input
my_num = 123
# Assigning the value
print(my_num)
my_num = 321
# Replacing with another value
print(my_num)
●●● Output
123
321
Note
Variables are mutable, so you can change their values at any time.
2.9. Logical Operator
#18 Logical Expression
Exercise ★★
Manipulate the logic of Boolean expressions using the logical
operators.
Solution
●●● Input
num = 6
print(num > 4 and num < 8)
# returns True because 6 is greater than 4 AND 6 is less than
8
print(num > 4 or num < 5)
# returns True because one of the conditions are true
# 6 is greater than 4, but 6 is not less than 5
print(not(num > 4))
# returns False because not is used to reverse the result
●●● Output
True
True
False
Note
Logical expressions are formed using Booleans and logical
operators.
2.10. String Operation
#19 Concatenation
Exercise ★
Merge two strings together.
Multiply a string.
Solution
●●● Input
first_string = "apple"
second_string = " pie"
full_string = first_string + second_string
print(full_string)
print("ha" * 3)
●●● Output
apple pie
hahaha
Note
You can merge two strings together using the + operator.
You can multiply a string into a repeating pattern using the *
operator.
#20 Search
Exercise ★★
Check if a particular substring is present in the string.
Solution
●●● Input
my_string = "apple pie"
print("apple" in my_string)
# "apple" exists!
print("orange" in my_string)
# Check whether "orange" exists in my_string
●●● Output
True
False
Note
The in keyword can be used to check if a particular substring is
present in another string. If the substring is found, the operation
returns True.
3. DATA STRUCTURE
3.1. List
#21 Creating List
Exercise ★★
Create a list and access the value.
Display the number of element in the list.
Solution
●●● Input
my_list = ["apple", "orange", 5, 2.5, True]
print(my_list)
print(my_list[1])
print(len(my_list))
●●● Output
['apple', 'orange', 5, 2.5, True]
orange
Note
The list can contain elements of different data types in a single
container. The elements of the list are enclosed in square brackets
[]. The elements in the list are numbered from 0 by the index to
identify them.
The Python list method len() returns the number of elements in
the list.
#22 List Slicing
Exercise ★★
Slice the list to display the sublist.
Solution
●●● Input
my_list = ["apple", "banana", "orange", "grape", "strawberry"]
print(my_list[2:4])
print(my_list[0::2])
# slice(start, stop, step)
●●● Output
['orange', 'grape']
['apple', 'orange', 'strawberry']
Note
You can slice the list and display the sublists using the index that
identifies the range.
#23 Number in Range
Exercise ★★
Display a series of numbers in the specified range.
Solution
●●● Input
num_seq = range(0, 6)
# A sequence from 0 to 5
print(list(num_seq))
num_seq = range(3, 11, 2)
# A sequence from 3 to 10 with a step of 2
print(list(num_seq))
●●● Output
[0, 1, 2, 3, 4, 5]
[3, 5, 7, 9]
Note
You can indicate the range by specifying the first and last numbers
using the range().
#24 Nested List
Exercise ★★
Create the lists inside another list.
Solution
●●● Input
my_list = [[1, "apple"], [2, "orange"], [3, "grape"]]
print(my_list)
●●● Output
[[1, 'apple'], [2, 'orange'], [3, 'grape']]
Note
You can put lists within the list.
#25 Sequential Indexing
Exercise ★★
Access the elements and the character of the string in the nested
list.
Solution
●●● Input
my_list = [[1, "apple"], [2, "orange"], [3, "grape"]]
print(my_list[1])
print(my_list[1][1])
# Accessing 'orange'
print(my_list[1][1][0])
# Accessing 'o'
●●● Output
[2, 'orange']
orange
Note
You can access the elements and the character of the string in the
nested list using the concept of sequential indexing. Each level of
indexing allows you to go one step deeper into the list and access
any element of a complex list.
#26 Merging List
Exercise ★
Merge two lists together.
Solution
●●● Input
num_A = [1, 2, 3, 4, 5]
num_B = [6, 7, 8, 9, 10]
merged_list = num_A + num_B
print(merged_list)
●●● Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Note
You can easily merge lists using the + operator.
3.2. Common List Operation
#27 Adding Element
Exercise ★★
Add a new element at the end of a list using.
Solution
●●● Input
my_list = [] # Empty list
my_list.append("apple")
my_list.append("orange")
my_list.append("grape")
print(my_list)
●●● Output
['apple', 'orange', ‘grape']
Note
You can add a new element to the end of the list using the
append() method.
#28 Inserting Element
Exercise ★★
Insert a new element at a particular index in the list.
Solution
●●● Input
my_list = ["apple", "orange", "grape"]
my_list.insert(1, "banana")
# Inserting 2 at the 1 index.
print(my_list)
●●● Output
['apple', 'banana', 'orange', ‘grape']
Note
You can insert an element at a specific index of a list using the
insert() method. If there is already a value at that index, the
entire list after that value will be moved one step to the right.
#29 Removing Last Element
Exercise ★★
Remove the last element from the list.
Solution
●●● Input
my_list = ["apple", "banana", "orange", "grape"]
last_list = my_list.pop()
print(last_list)
print(my_list)
●●● Output
grape
['apple', 'banana', ‘orange']
Note
You can remove the last element from the list using the pop()
operation.
#30 Removing Particular Element
Exercise ★★
Remove a particular element from a list.
Solution
●●● Input
my_list = ["apple", "banana", "orange", "grape"]
print(my_list)
my_list.remove("banana")
print(my_list)
●●● Output
['apple', 'banana', 'orange', 'grape']
['apple', 'orange', ‘grape']
Note
You can remove a particular element from the list using the
remove() method.
#31 Find Index of Element
Exercise ★★
Find the index of a given value in a list.
Solution
●●● Input
my_list = ["apple", "banana", "orange", "grape"]
print(my_list.index("banana"))
# It is at the 1st index
●●● Output
Note
You can find the index of a given value in a list using the index()
method.
#32 Verify Existence of Element
Exercise ★★
Verify the existence of an element in a list.
Solution
●●● Input
my_list = ["apple", "banana", "orange", "grape"]
print("banana" in my_list)
print("pineapple" not in my_list)
●●● Output
True
True
Note
If you just want to check for the presence of an element in a list, you
can use the in operator.
#33 List Sort
Exercise ★★
Sort alphabetically or numerically depending on the content of a list.
Solution
●●● Input
num_list = [10, 21, 13, 25.7, 50, 100, 4]
num_list.sort()
print(num_list)
fruit_list = ["banana", "orange", "grape","apple"]
fruit_list.sort()
print(fruit_list)
●●● Output
[4, 10, 13, 21, 25.7, 50, 100]
['apple', 'banana', 'grape', ‘orange']
Note
You can sort the list alphabetically or numerically according to its
contents using the sort() method.
3.3. Tuple
#34 Creating Tuple
Exercise ★★
Create a tuple and apply the indexing and slicing operations to it.
Solution
●●● Input
my_tup = ("apple", "red", "Washington", 3)
print(my_tup)
print(len(my_tup)) # Length
print(my_tup[1]) # Indexing
print(my_tup[2:]) # Slicing
●●● Output
('apple', 'red', 'Washington', 3)
red
('Washington', 3)
Note
A tuple is very similar to a list, but you can't change the contents. In
other words, tuples are immutable. The contents of a tuple are
enclosed in parentheses ().
#35 Merging Tuple
Exercise ★
Merge two tuples.
Solution
●●● Input
my_tup1 = ("apple", "orange")
my_tup2 = ("grape", "banana")
my_tup3 = my_tup1 + my_tup2
print(my_tup3)
●●● Output
('apple', 'orange', 'grape', 'banana')
Note
You can merge two tuples using the + operator.
#36 Nested Tuple
Exercise ★★
Create a nested tuple with the two tuples.
Solution
●●● Input
my_tup1 = ("apple", "orange")
my_tup2 = ("grape", "banana")
my_tup3 = (my_tup1, my_tup2)
print(my_tup3)
●●● Output
(('apple', 'orange'), ('grape', 'banana'))
Note
Instead of merging the two tuples, you can create a nested tuple
with these two tuples.
#37 Find Index of Element
Exercise ★★
Find the index of a given value in a tuple.
Solution
●●● Input
my_tup = ("apple", "orange", "grape", "banana")
print(my_tup.index("orange"))
●●● Output
Note
You can find the index of a given value in a tuple using the
index() method.
#38 Verify Existence of Element
Exercise ★★
Verify the existence of an element in a tuple.
Solution
●●● Input
my_tup = ("apple", "orange", "grape", "banana")
print("orange" in my_tup)
print("pineapple" in my_tup)
●●● Output
True
False
Note
You can verify the existence of an element in a tuple using the in
operator.
3.4. Dictionary
#39 Creating Dictionary 1
Exercise ★★
Create a simple phone book using the dictionary data structure.
Solution
●●● Input
phone_book = {"Bob": 746,"Susan": 638,"Eric": 548}
print(phone_book)
●●● Output
{'Eric': 548, 'Susan': 638, 'Bob': 746}
Note
A dictionary stores information in key-value pairs. Dictionaries are
unordered because the entries are not stored in a linear structure.
In Python, the contents of the dictionary must be placed in
parentheses {}.
#40 Creating Dictionary 2
Exercise ★★
Create a simple phone book in a different way.
Solution
●●● Input
phone_book = dict(Bob=746, Susan=638, Eric=548)
# Keys will automatically be converted to strings
print(phone_book)
●●● Output
{'Eric': 548, 'Bob': 746, 'Susan': 638}
Note
If the key is a simple string, you can build a dictionary using the
dict() constructor. In that case, the value will be assigned to the key
using the = operator.
#41 Accessing Value
Exercise ★★
Access a value in the dictionary.
Solution
●●● Input
phone_book = {"Bob": 746,"Susan": 638,"Eric": 548}
print(phone_book["Susan"])
print(phone_book.get("Eric"))
●●● Output
638
548
Note
You can access the value by enclosing the key in square brackets
[]. Alternatively, you can use the get() method.
3.5. Dictionary Operation
#42 Adding/Updating Entry
Exercise ★★★
Add and update the entry in the dictionary.
Solution
●●● Input
phone_book = {"Bob": 746,"Susan": 638,"Eric": 548}
print(phone_book)
phone_book["Emma"] = 857
# New entry
print(phone_book)
phone_book["Emma"] = 846
# Updating entry
print(phone_book)
●●● Output
{'Susan': 638, 'Eric': 548, 'Bob': 746}
{'Susan': 638, 'Emma': 857, 'Eric': 548, 'Bob': 746}
{'Susan': 638, 'Emma': 846, 'Eric': 548, 'Bob': 746}
Note
You can add a new entry to the dictionary by simply assigning a
value to the key. Python will create the entry automatically. If a
value already exists for this key, it will be updated.
#43 Removing Entry
Exercise ★★★
Remove an entry in the dictionary.
Solution
●●● Input
phone_book = {"Bob": 746,"Susan": 638,"Eric": 548}
print(phone_book)
del phone_book["Bob"]
print(phone_book)
●●● Output
{'Bob': 746, 'Eric': 548, 'Susan': 638}
{'Eric': 548, 'Susan': 638}
Note
You can remove an entry by using the del keyword.
#44 Using Removed Entry
Exercise ★★★
Use the removed value in a dictionary.
Solution
●●● Input
phone_book = {"Bob": 746,"Susan": 638,"Eric": 548}
susan = phone_book.pop("Susan")
print(susan)
print(phone_book)
●●● Output
638
{'Eric': 548, 'Bob': 746}
Note
If you want to use the removed values, the pop() method will work
better.
#45 Length of Dictionary
Exercise ★★★
Calculate the length of the dictionary.
Solution
●●● Input
phone_book = {"Bob": 746,"Susan": 638,"Eric": 548}
print(len(phone_book))
●●● Output
Note
As with lists and tuples, you can calculate the length of the
dictionary using the len() method.
#46 Checking Key Existence
Exercise ★★★
Check if a key exists in a dictionary.
Solution
●●● Input
phone_book = {"Bob": 746,"Susan": 638,"Eric": 548}
print("Susan" in phone_book)
print("Emma" in phone_book)
●●● Output
True
False
Note
You can check whether a key exists in the dictionary or not using
the in keyword.
#47 Copying Content of Dictionary
Exercise ★★★
Copy the contents of one dictionary to another.
Solution
●●● Input
first_phone_book = {"Bob": 746,"Susan": 638,"Eric": 548}
second_phone_book = {"Emma": 749, "Liam": 640, "Olivia": 759}
# Add second_phone_book to first_phone_book
first_phone_book.update(second_phone_book)
print(first_phone_book)
●●● Output
{'Susan': 638, 'Bob': 746, 'Emma': 749, 'Eric': 548, 'Liam': 640, 'Olivia':
759}
Note
You can copy the contents of one dictionary to another dictionary
using the update() operation.
3.6. Set
#48 Creating Set 1
Exercise ★
Collect various data items in the set.
Solution
●●● Input
my_set = {"apple", 3, 4.8, True}
print(my_set)
●●● Output
{True, 3, 4.8, 'apple'}
Note
The contents of the set are encapsulated in curly braces {}. The set
is an unordered collection of data items. The data is not indexed,
and you cannot use indexes to access the elements. The set is best
used when you simply need to keep track of the existence of items.
#49 Creating Set 2
Exercise ★★
Create a set in a different way.
Solution
●●● Input
my_set = set( {"apple", 3, 4.8, True})
print(my_set)
●●● Output
{True, 3, 4.8, 'apple'}
Note
You can create a set in a different way using the set() constructor.
#50 Length of Set
Exercise ★★
Calculate the length of the set.
Solution
●●● Input
my_set = {"apple", 3, 4.8, True}
print(len(my_set)) # Length of the set
●●● Output
Note
You can calculate the length of a set using the len().
#51 Adding Element
Exercise ★★★
Add a single element to an empty set.
Add multiple elements to the set.
Solution
●●● Input
my_set = set()
print(my_set)
my_set.add(1)
print(my_set)
my_set.update([2, 3, 4, 5])
print(my_set)
●●● Output
set()
{1}
{1, 2, 3, 4, 5}
Note
You can add a single element using the add() method. To add
multiple elements you have to use update(). The set does not
allow duplicates, so you cannot enter the same data or data
structure.
#52 Removing Element
Exercise ★★★
Removing a particular element from the set.
Solution
●●● Input
my_set = set({"apple", 3, 4.8, True})
print(my_set)
my_set.discard(4.8)
print(my_set)
my_set.remove(True)
print(my_set)
●●● Input
{'apple', True, 3, 4.8}
{'apple', True, 3}
{'apple', 3}
Note
You can remove a particular element from the set using the
discard() or remove() operation.
3.7. Set Theory Operation
#53 Union of Sets
Exercise ★★★
Unite two sets.
Solution
●●● Input
set_A = {"Liam", "Eric", "Bob"}
set_B = {"Emma", "Olivia", "Sophia"}
print(set_A | set_B)
print(set_A.union(set_B))
●●● Output
{'Emma', 'Eric', 'Liam', 'Bob', 'Sophia', 'Olivia'}
{'Emma', 'Eric', 'Liam', 'Bob', 'Sophia', 'Olivia'}
Note
You can unite the sets using either the pipe operator, |, or the
union() method. The set is unordered, so the order of the
contents of the outputs does not matter.
#54 Intersection of Sets
Exercise ★★★
Intersect two sets.
Solution
●●● Input
set_A = {"Liam", "Eric", "Emma","Bob"}
set_B = {"Emma", "Olivia", "Liam","Sophia"}
print(set_A & set_B)
print(set_A.intersection(set_B))
●●● Output
{'Liam', 'Emma'}
{'Liam', 'Emma'}
Note
You can perform intersection of two sets using either the & operator
or the intersection() method.
#55 Difference of Sets
Exercise ★★★
Find the difference between two sets.
Solution
●●● Input
set_A = {"Liam", "Eric", "Emma", "Bob"}
set_B = {"Emma", "Olivia", "Liam", "Sophia"}
print(set_A - set_B)
print(set_A.difference(set_B))
print(set_B - set_A)
print(set_B.difference(set_A))
●●● Output
{'Bob', 'Eric'}
{'Bob', 'Eric'}
{'Sophia', 'Olivia'}
{'Sophia', ‘Olivia'}
Note
You can find the difference between two sets using either the -
operator or the difference() method.
3.8. Data Structure Conversion
#56 Converting to List
Exercise ★★★
Convert a tuple, set, or dictionary to a list.
Solution
●●● Input
my_tup = ("apple", "orange", "grape")
my_set = {"apple", "orange", "grape"}
my_dict = {1: "apple", 2: "orange", 3: "grape"}
my_list = list(my_tup)
# Converting from tuple
print(my_list)
my_list = list(my_set)
# Converting from set
print(my_list)
my_list = list(my_dict)
# Converting from dictionary
print(my_list)
●●● Output
['apple', 'orange', 'grape']
['apple', 'orange', 'grape']
[1, 2, 3]
Note
You can convert a tuple, set, or dictionary to a list using the list()
constructor. In the case of a dictionary, only the keys will be
converted to a list.
#57 Converting to Tuple
Exercise ★★★
Convert a list, set, or dictionary to a tuple.
Solution
●●● Input
my_list = ["apple", "orange", "grape"]
my_set = {"apple", "orange", "grape"}
my_dict = {1: "apple", 2: "orange", 3: "grape"}
my_tup = tuple(my_list)
# Converting from list
print(my_tup)
my_tup = tuple(my_set)
# Converting from set
print(my_tup)
my_tup = tuple(my_dict)
# Converting from dictionary
print(my_tup)
●●● Output
('apple', 'orange', 'grape')
('grape', 'orange', 'apple')
(1, 2, 3)
Note
You can convert any data structure into a tuple using the tuple()
constructor. In the case of a dictionary, only the keys will be
converted to a tuple.
#58 Converting to Set
Exercise ★★★
Convert a list, tuple, or dictionary to a set.
Solution
●●● Input
my_list = ["apple", "orange", "grape"]
my_tup = ("apple", "orange", "grape")
my_dict = {1: "apple", 2: "orange", 3: "grape"}
my_set = set(my_list)
# Converting from list
print(my_set)
my_set = set(my_tup)
# Converting from tuple
print(my_set)
my_set = set(my_dict)
# Converting from dictionary
print(my_set)
●●● Output
{'apple', 'orange', 'grape'}
{'apple', 'orange', 'grape'}
{1, 2, 3}
Note
You can create the set from any other data structure using the
set() constructor. In the case of dictionary, only the keys will be
converted to the set.
#59 Converting to Dictionary
Exercise ★★★
Convert a list, tuple, or set to a dictionary.
Solution
●●● Input
my_list = [[1,"apple"], [2,"orange"], [3, "grape"]]
my_tup = ((1, "apple"), (2, "orange"), (3, "grape"))
my_set = {(1, "apple"), (2, "orange"), (3, "grape")}
my_dict = dict(my_list)
# Converting from list
print(my_dict)
my_dict = dict(my_tup)
# Converting from tuple
print(my_dict)
my_dict = dict(my_set)
# Converting from set
print(my_dict)
●●● Output
{1: 'apple', 2: 'orange', 3: 'grape'}
{1: 'apple', 2: 'orange', 3: 'grape'}
{1: 'apple', 2: 'orange', 3: 'grape'}
Note
You can convert a list, tuple, or set to a dictionary using the dict()
constructor. The dict() constructor requires key-value pairs, not
just values.
4. CONDITIONAL STATEMENTS
4.1. If Statement
#60 Flow of If Statement
Exercise ★★
If the condition is True, execute the code. If not, skip the code and
move on.
Solution
●●● Input
num = 3
if num == 3:
# The condition is true
print("The number is equal to 3")
# The code is executed
if num > 3:
# The condition is false
print("The number is greater than 3")
# The code is not executed
●●● Output
The number is equal to 3
Note
You can verify the value of an integer using the if statement.
#61 Condition with Logical Operator
Exercise ★★★
Create more complex conditions with logical operators.
Solution
●●● Input
a = 10
b = 5
c = 30
if a > b and c > a:
print("Both conditions are True")
if a > b or a > c:
print("At least one of the conditions is True")
●●● Output
Both conditions are True
At least one of the conditions is True
Note
The first if statement uses the and operator, so if both conditions
are met, the code will be executed. The second if statement uses
the or operator, so if either condition is met, the code will be
executed.
#62 Nested If Statement
Exercise ★★★
Make complex conditions using the nested if statements.
Solution
●●● Input
num = 65
if num >= 0 and num <= 100:
if num >= 50 and num <= 75:
if num >= 60 and num <= 70:
print("The number is in the 60-70 range")
●●● Output
The number is in the 60-70 range
Note
You can put an if statement inside another if statement. In other
words, by nesting, you can create complex conditions in your
program. Each nested if statement needs to be indented further.
4.2. If Else Statement
#63 If Else Statement
Exercise ★★★
Execute a different set of operations in case the if condition turns
out to be False.
Solution
●●● Input
num = 70
if num <= 50:
print("The number is less than or equal to 50")
else:
print("The number is greater than 50")
●●● Output
The number is greater than 50
Note
If the condition turns out to be False, the code after the else:
keyword will be executed. Thus, we can now perform two different
actions based on the value of the condition. The else keyword will
be at the same indentation level as the if keyword. Its body will be
indented one tab to the right, just like the if statement.
4.3. If Elif Else Statement
#64 If Elif Else Statement
Exercise ★★★
Check the state of a traffic signal and generates the appropriate
response.
Solution
●●● Input
light = "Red"
if light == "Green":
print("Go")
elif light == "Yellow":
print("Caution")
elif light == "Red":
print("Stop")
else:
print("Incorrect")
●●● Output
Stop
Note
The if-elif-else statement makes it easy to create multiple
conditions. The elif indicates that if the previous condition fails,
try this condition.
#65 Multiple Elif Statement
Exercise ★★★
Check whether the value of an integer is in the range and prints the
word in English.
Solution
●●● Input
num = 3
if num == 0:
print("Zero")
elif num == 1:
print("One")
elif num == 2:
print("Two")
elif num == 3:
print("Three")
elif num == 4:
print("Four")
elif num == 5:
print("Five")
●●● Output
Three
Note
The if-elif statement can end with the elif block without the
else block at the end.
5. LOOPS
5.1. For Loop
#66 Looping Through Range
Question ★★
Display the numbers 1 through 5.
Solution
●●● Input
for i in range(1, 6):
# A sequence from 1 to 5
print(i)
●●● Output
1
2
3
4
5
Note
In Python, the built-in range() function can be used to create a
sequence of integers. This sequence can be iterated through a
loop. The end value is not included in the list.
#67 Looping Through List
Exercise ★★★
Double each value in the list.
Solution
●●● Input
num_list = [1, 2, 3, 4, 5]
print(num_list)
for i in range(0, len(num_list)):
# Iterator traverses to the last index of the list
num_list[i] = num_list[i] * 2
print(num_list)
●●● Output
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
Note
The list can iterate over its indices using the for loop.
5.2. Nested For Loop
#68 Nested For Loop
Exercise ★★★
Display two elements whose sum is equal to10.
Solution
●●● Input
n = 10
num_list = [10, 4, 3, 6, 8, 13, 26]
for n1 in num_list:
for n2 in num_list:
# Now we have two iterators
if(n1 + n2 == n): # n1 + n2 = 10
print(n1, n2)
●●● Output
4 6
6 4
Note
In the code above, you can check each element in combination with
another element to see if n1 + n2 is equal to 10.
#69 Break Statement
Exercise ★★★
Display two elements whose sum is equal to 10 and stop it when
the pair is found once.
Solution
●●● Input
n = 10
num_list = [10, 4, 3, 6, 8, 13, 26]
found = False
# This bool will become true once a pair is found
for n1 in num_list:
for n2 in num_list:
if(n1 + n2 == n):
found = True
# Set found to True
break
# Break inner loop if a pair is found
if found:
print(n1, n2) # Print the pair
break
# Break outer loop if a pair is found
●●● Output
4 6
Note
You can break the loop whenever you need to using the break
statement.
#70 Continue Statement
Exercise ★★★
Display the numbers 1 through 5 except for 3.
Solution
●●● Input
for num in range(1,6):
if num == 3:
continue
print(num)
●●● Output
Note
If you use the continue statement, the remaining iterations will be
skipped and the loop will proceed to the next iteration.
#71 Pass Statement
Exercise ★★★
Display the numbers 1 through 5 except for 3.
Solution
●●● Input
for num in range(1,6):
if num == 3:
pass
else:
print(num)
●●● Output
Note
The pass statement does nothing for the execution of the code.
5.3. While Loop
#72 While Loop
Exercise ★★
Display the numbers 1 through 5.
Solution
●●● Input
num = 1
while num <= 5:
print(num)
num = num + 1
●●● Output
Note
In the for loop, the number of iterations is fixed. On the other
hand, the while loop repeats a specific set of operations as long
as a specific condition is true.
#73 While Else
Exercise ★★★
Display the numbers 1 through 5, and display "Done" when
finished.
Solution
●●● Input
num = 1
while num <= 5:
print(num)
num = num + 1
else:
print("Done")
●●● Output
Done
Note
In the above code, the numbers 1 through 5 will be displayed first. If
num is 6, the while condition will fail and the else condition will
be triggered.
#74 Break Statement
Exercise ★★★
Display the numbers in order from 1, and stop execution when the
number reaches 5.
Solution
●●● Input
num = 1
while num <= 10:
if num == 5:
break
print(num)
num += 1
# num = num + 1
●●● Output
Note
In the above code, num is displayed in order starting from 1, and
when num reaches 5, the loop stops executing using the break
statement.
#75 Continue Statement
Exercise ★★★
Display the numbers 1 through 5 except for 3.
Solution
●●● Input
num = 0
while num < 5:
num += 1
# num = num + 1
if num == 3:
continue
print(num)
●●● Output
Note
In the above example, the loop prints the numbers 1 through 5
except for 3. When num is 3, that command will be skipped and the
next command will be executed using the continue statement.
#76 Pass Statement
Exercise ★★★
Display the numbers 1 through 5 except for 3.
Solution
●●● Input
num = 0
while num < 5:
num += 1
# num = num + 1
if num == 3:
pass
else:
print(num)
●●● Output
Note
The pass statement does nothing for the execution of the code.
6. FUNCTION
6.1. Built-in Math function
#77 Min function
Exercise ★★
Find the minimum value between two integers.
Solution
●●● Input
minimum = min(10, 40)
print(minimum)
●●● Output
10
Note
You can find the minimum using the min() function.
#78 Max function
Exercise ★★
Find the maximum value between two integers.
Solution
●●● Input
maximum = max(10, 40)
print(maximum)
●●● Output
40
Note
You can find the maximum using the max() function.
Column: Why Use Function?
Reusability: Function can be used over and over again. There
is no need to write redundant code.
Simplicity: Function is easy to use and make the code
readable. You only need to know the input and the purpose of
the function without paying attention to the inner workings.
6.2. Built-In String Function
#79 Finding String
Exercise ★★
Find a substring in a string.
Solution
●●● Input
my_string = "Hello World!"
print(my_string.find("Hello"))
# First instance of 'Hello' occurs at index 0
print(my_string.find("Goodbye"))
#-1 is a conventional value that represents a None
●●● Output
-1
Note
The find() method returns the index of the first occurrence of the
substring, if found. If it is not found, it returns -1.
#80 Replacing String
Exercise ★★
Replace a part of a string with another string.
Solution
●●● Input
my_string = "Hello World!"
new_string = my_string.replace("Hello", "Goodbye")
print(my_string)
print(new_string)
●●● Output
Hello World!
Goodbye World!
Note
You can be used to replace a part of a string with another string
using the replace() method. The original string will not be
changed. Instead, a new string containing the replaced substring
will be returned.
#81 Changing Letter Case
Exercise ★★
Change the letter case of a string.
Solution
●●● Input
print("Hello World!".upper())
print("Hello World!".lower())
●●● Output
HELLO WORLD!
hello world!
Note
You can easily convert a string to upper case using the upper()
method and to lower case using the lower() method.
6.3. Type Conversion
#82 Converting Data to Integer
Exercise ★★
Convert a data to the integer.
Solution
●●● Input
print(int("5") * 10)
# String to integer
print(int(18.5))
# Float to integer
print(int(False))
# Bool to integer
●●● Output
50
18
Note
You can convert a data to the integer using the int() function.
#83 Converting Data to Float
Exercise ★★
Convert a data to the floating-point number.
Solution
●●● Input
print(float(13))
print(float(True))
●●● Output
13.0
1.0
Note
You can convert a data to the floating-point number using the
float() function.
#84 Converting Data to String
Exercise ★★
Convert a data to the string.
Solution
●●● Input
print(str(False))
print(str(123) + ' is a string')
●●● Output
False
123 is a string
Note
You can convert a data to a string using the str() function.
6.4. User-defined Function
#85 Creating Function
Exercise ★★★
Create a plain function that prints three lines of text.
Solution
●●● Input
def my_print_function():
# No parameters
print("apple")
print("orange")
print("grape")
# Function ended
# Calling the function in the program multiple times
my_print_function()
●●● Output
apple
orange
grape
Note
You can create a function using the def keyword. The function can
be called in your code using its name and empty parentheses.
#86 Function Parameter
Exercise ★★★
Create a function to compare two numbers and print the smaller
number.
Solution
●●● Input
def minimum(first, second):
if (first < second):
print(first)
else:
print(second)
num1 = 12
num2 = 53
minimum(num1, num2)
●●● Output
12
Note
The position of the parameters is important. In the above example,
the value of num1 is the first parameter, so it is assigned to the first
position. Similarly, the value of num2 is assigned to the second
parameter.
#87 Return Statement
Exercise ★★★
Create a function to compare two numbers and return the smaller
value.
Solution
●●● Input
def minimum(first, second):
if (first < second):
return first
else:
return second
num1 = 12
num2 = 53
result = minimum(num1, num2)
# Storing the value returned by the function
print(result)
●●● Output
12
Note
You can return something from a function using the return
statement.
6.5. Lambda
#88 Lambda Syntax 1
Exercise ★★
Triple a value of the parameter and return this new value.
Solution
●●● Input
triple = lambda num : num * 3
# Assigning the lambda to a variable
print(triple(11))
# Calling the lambda and giving it a parameter
●●● Output
33
Note
The function is named using the def keyword, but the lambda is a
special class that does not require a function name to be specified.
The lambda is an anonymous function that returns data in some
form.
#89 Lambda Syntax 2
Exercise ★★
Take the first character of three strings and concatenate them.
Solution
●●● Input
concat_strings = lambda a, b, c: a[0] + b[0] + c[0]
print(concat_strings("Game", "Of", "Thrones"))
●●● Output
GOT
Note
It is a simple lambda that takes the first character of three strings
and concatenates them.
#90 If Else Statement
Exercise ★★★
Compare a number to 100 using the conditional statement.
Solution
●●● Input
my_function = lambda num: "High" if num > 100 else "Low"
print(my_function(110))
print(my_function(60))
●●● Output
High
Low
Note
The lambda cannot have multi-line expressions. This means that
code must be able to be written on a single line. Therefore, the
lambda is suitable for short, one-line function.
7. LIBRARY
7.1. Python Standard Library
#91 Importing Datetime Module
Exercise ★★★
Display the current date and time.
Solution
●●● Input
import datetime
# Importing modules at the beginning of the program is a good practice
date_today = datetime.date.today()
# Current date
print(date_today)
time_today = datetime.datetime.now()
print(time_today.strftime("%H:%M:%S"))
# Current time
●●● Output Example
2021-01-10
10:12:30
Note
The datetime module contains a number of methods related to
the current date and time. The datetime.date and
datetime.datetime are classes of the datetime module.
Column: Python Standard Library
The Python Standard Library, PSL, is a collection of a set of
predefined modules and methods that help you perform
specific tasks in Python.
The library contains a number of useful utilities that can save
you a lot of time.
In order to use the methods of a module, you need to import
the module into your code. This can be done using the
import keyword.
#92 Importing Individual Class
Exercise ★★★
Use a particular class from the module.
Solution
●●● Input
from datetime import date
# Now we only have the methods of the date class
date_today = date.today()
# Current date
print(date_today)
●●● Output Example
2021-01-10
Note
If you want to extract only a specific class from a module, you can
use the from keyword.
#93 Importing and Naming Module
Exercise ★★★
Import and Give your own name to the module.
Solution
●●● Input
import datetime as dt
date_today = dt.date.today()
# Current date
print(date_today)
time_today = dt.datetime.now()
print(time_today.strftime("%H:%M:%S"))
# Current time
●●● Output Example
2021-01-10
10:12:30
Note
You can also give your own name to the module you are importing
by using the as keyword.