Python Workbook for Beginners - CS Playground
Python Workbook for Beginners - CS Playground
#1 Hello World
#2 Comments in Code
2.1. Variable
#3 Variable Assignment
2.2. Number
#4 Integer
2.3. Boolean
2.4. String
#9 Length of String
#12 Addition
#13 Subtraction
#14 Multiplication
#15 Division
#19 Concatenation
#20 Search
3. DATA STRUCTURE
3.1. List
3.3. Tuple
#34 Creating Tuple
3.4. Dictionary
3.6. Set
#48 Creating Set 1
4. CONDITIONAL STATEMENTS
4.1. If Statement
5. LOOPS
6. FUNCTION
6.5. Lambda
7. LIBRARY
OceanofPDF.com
Python Workbook for Beginners
OceanofPDF.com
1. WRITING FIRTST CODE
#1 Hello World
Exercise ★
●●● 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.
OceanofPDF.com
#2 Comments in Code
Exercise ★
●●● Input
print("Hello World")
●●● Output
Hello World
Note
OceanofPDF.com
2. DATA TYPE AND VARIABLE
2.1. Variable
#3 Variable Assignment
Exercise ★
●●● Input
fruit = "apple"
fruit = "orange"
●●● Output
apple
orange
Note
#4 Integer
Exercise ★
●●● Input
num = 12345
num = -12345
●●● Output
12345
-12345
Note
●●● Input
num = 1.2345
num = -1.2345
●●● Output
1.2345
-1.2345
Note
●●● Input
print(True)
print(False)
●●● Output
True
False
Note
The Boolean data type allows you to choose between two values (True and
False).
OceanofPDF.com
2.4. String
●●● Input
print("apple pie")
print('apple pie')
●●● Output
apple pie
apple pie
Note
OceanofPDF.com
#8 Displaying Various Data Type
Exercise ★
●●● Input
●●● Output
Note
You just have to separate multiple things using the comma to print them in
a single print command.
OceanofPDF.com
#9 Length of String
Exercise ★★
●●● Input
●●● Output
Note
OceanofPDF.com
#10 Accessing Character
Exercise ★★
●●● Input
first = my_string[0]
last = my_string[-1]
●●● 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.
OceanofPDF.com
Column: Index
OceanofPDF.com
2.5. String Slicing
●●● Input
print(my_string[0:5])
print(my_string[6:9])
●●● Output
apple
pie
Note
#12 Addition
Exercise ★
●●● Input
print(5 + 8)
●●● Output
13
Note
OceanofPDF.com
#13 Subtraction
Exercise ★
●●● Input
print(15 - 7)
●●● Output
Note
You can subtract one number from another using the - operator.
OceanofPDF.com
#14 Multiplication
Exercise ★
●●● Input
print(30 * 5)
●●● Output
150
Note
OceanofPDF.com
#15 Division
Exercise ★
●●● Input
print(30 / 10)
●●● Output
3.0
Note
OceanofPDF.com
2.7. Comparison Operator
●●● Input
print(5 > 3)
# 5 is greater than 3
print(5 < 3)
# 5 is less than 3
print(5 >= 3)
print(5 is 3)
print(5 == 3)
●●● Output
True
False
True
False
False
False
False
True
Note
OceanofPDF.com
2.8. Assignment Operator
Assign a value to a variable and replace that value with another value.
Solution
●●● Input
my_num = 123
my_num = 321
●●● Output
123
321
Note
Variables are mutable, so you can change their values at any time.
OceanofPDF.com
2.9. Logical Operator
●●● Input
num = 6
●●● Output
True
True
False
Note
OceanofPDF.com
2.10. String Operation
#19 Concatenation
Exercise ★
●●● Input
first_string = "apple"
print(full_string)
print("ha" * 3)
●●● Output
apple pie
hahaha
Note
●●● Input
print("apple" in my_string)
# "apple" exists!
print("orange" in my_string)
●●● Output
True
False
Note
3.1. List
●●● Input
print(my_list)
print(my_list[1])
print(len(my_list))
●●● Output
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.
OceanofPDF.com
#22 List Slicing
Exercise ★★
●●● Input
print(my_list[2:4])
print(my_list[0::2])
●●● Output
['orange', 'grape']
Note
You can slice the list and display the sublists using the index that identifies
the range.
OceanofPDF.com
#23 Number in Range
Exercise ★★
●●● Input
num_seq = range(0, 6)
# A sequence from 0 to 5
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().
OceanofPDF.com
#24 Nested List
Exercise ★★
●●● Input
print(my_list)
●●● Output
Note
OceanofPDF.com
#25 Sequential Indexing
Exercise ★★
Access the elements and the character of the string in the nested list.
Solution
●●● Input
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.
OceanofPDF.com
#26 Merging List
Exercise ★
●●● Input
num_A = [1, 2, 3, 4, 5]
print(merged_list)
●●● Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Note
OceanofPDF.com
3.2. Common List Operation
●●● Input
my_list.append("orange")
my_list.append("grape")
print(my_list)
●●● Output
Note
You can add a new element to the end of the list using the append()
method.
OceanofPDF.com
#28 Inserting Element
Exercise ★★
●●● Input
my_list.insert(1, "banana")
print(my_list)
●●● Output
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.
OceanofPDF.com
#29 Removing Last Element
Exercise ★★
●●● Input
last_list = my_list.pop()
print(last_list)
print(my_list)
●●● Output
grape
Note
You can remove the last element from the list using the pop() operation.
OceanofPDF.com
#30 Removing Particular Element
Exercise ★★
●●● Input
print(my_list)
my_list.remove("banana")
print(my_list)
●●● Output
Note
You can remove a particular element from the list using the remove()
method.
OceanofPDF.com
#31 Find Index of Element
Exercise ★★
●●● Input
print(my_list.index("banana"))
●●● Output
Note
You can find the index of a given value in a list using the index() method.
OceanofPDF.com
#32 Verify Existence of Element
Exercise ★★
●●● Input
print("banana" 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.
OceanofPDF.com
#33 List Sort
Exercise ★★
●●● Input
num_list.sort()
print(num_list)
fruit_list.sort()
print(fruit_list)
●●● Output
Note
Create a tuple and apply the indexing and slicing operations to it.
Solution
●●● Input
print(my_tup)
print(len(my_tup)) # Length
print(my_tup[1]) # Indexing
print(my_tup[2:]) # Slicing
●●● Output
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 ().
OceanofPDF.com
#35 Merging Tuple
Exercise ★
●●● Input
print(my_tup3)
●●● Output
Note
OceanofPDF.com
#36 Nested Tuple
Exercise ★★
●●● Input
print(my_tup3)
●●● Output
Note
Instead of merging the two tuples, you can create a nested tuple with these
two tuples.
OceanofPDF.com
#37 Find Index of Element
Exercise ★★
●●● Input
print(my_tup.index("orange"))
●●● Output
Note
You can find the index of a given value in a tuple using the index() method.
OceanofPDF.com
#38 Verify Existence of Element
Exercise ★★
●●● Input
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.
OceanofPDF.com
3.4. Dictionary
●●● Input
print(phone_book)
●●● Output
Note
●●● Input
print(phone_book)
●●● Output
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.
OceanofPDF.com
#41 Accessing Value
Exercise ★★
●●● Input
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.
OceanofPDF.com
3.5. Dictionary Operation
●●● Input
print(phone_book)
phone_book["Emma"] = 857
# New entry
print(phone_book)
phone_book["Emma"] = 846
# Updating entry
print(phone_book)
●●● Output
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.
OceanofPDF.com
#43 Removing Entry
Exercise ★★★
●●● Input
print(phone_book)
del phone_book["Bob"]
print(phone_book)
●●● Output
Note
OceanofPDF.com
#44 Using Removed Entry
Exercise ★★★
●●● Input
susan = phone_book.pop("Susan")
print(susan)
print(phone_book)
●●● Output
638
Note
If you want to use the removed values, the pop() method will work better.
OceanofPDF.com
#45 Length of Dictionary
Exercise ★★★
●●● Input
print(len(phone_book))
●●● Output
Note
As with lists and tuples, you can calculate the length of the dictionary
using the len() method.
OceanofPDF.com
#46 Checking Key Existence
Exercise ★★★
●●● Input
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.
OceanofPDF.com
#47 Copying Content of Dictionary
Exercise ★★★
●●● Input
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.
OceanofPDF.com
3.6. Set
●●● Input
print(my_set)
●●● Output
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.
OceanofPDF.com
#49 Creating Set 2
Exercise ★★
●●● Input
print(my_set)
●●● Output
Note
You can create a set in a different way using the set() constructor.
OceanofPDF.com
#50 Length of Set
Exercise ★★
●●● Input
●●● Output
Note
OceanofPDF.com
#51 Adding Element
Exercise ★★★
●●● 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.
OceanofPDF.com
#52 Removing Element
Exercise ★★★
●●● Input
print(my_set)
my_set.discard(4.8)
print(my_set)
my_set.remove(True)
print(my_set)
●●● Input
{'apple', True, 3}
{'apple', 3}
Note
You can remove a particular element from the set using the discard() or
remove() operation.
OceanofPDF.com
3.7. Set Theory Operation
●●● Input
print(set_A | set_B)
print(set_A.union(set_B))
●●● Output
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.
OceanofPDF.com
#54 Intersection of Sets
Exercise ★★★
●●● Input
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.
OceanofPDF.com
#55 Difference of Sets
Exercise ★★★
●●● Input
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.
OceanofPDF.com
3.8. Data Structure Conversion
●●● Input
my_list = list(my_tup)
print(my_list)
my_list = list(my_set)
print(my_list)
my_list = list(my_dict)
print(my_list)
●●● Output
[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.
OceanofPDF.com
#57 Converting to Tuple
Exercise ★★★
●●● Input
my_tup = tuple(my_list)
print(my_tup)
my_tup = tuple(my_set)
print(my_tup)
my_tup = tuple(my_dict)
print(my_tup)
●●● Output
(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.
OceanofPDF.com
#58 Converting to Set
Exercise ★★★
●●● Input
my_set = set(my_list)
print(my_set)
my_set = set(my_tup)
print(my_set)
my_set = set(my_dict)
print(my_set)
●●● Output
{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.
OceanofPDF.com
#59 Converting to Dictionary
Exercise ★★★
●●● Input
my_dict = dict(my_list)
print(my_dict)
my_dict = dict(my_tup)
print(my_dict)
my_dict = dict(my_set)
print(my_dict)
●●● Output
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.
OceanofPDF.com
4. CONDITIONAL STATEMENTS
4.1. If Statement
If the condition is True, execute the code. If not, skip the code and move
on.
Solution
●●● Input
num = 3
if num == 3:
if num > 3:
●●● Output
Note
●●● Input
a = 10
b = 5
c = 30
if a > b or a > c:
●●● Output
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.
OceanofPDF.com
#62 Nested If Statement
Exercise ★★★
●●● Input
num = 65
●●● Output
Note
●●● Input
num = 70
else:
●●● Output
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.
OceanofPDF.com
4.3. If Elif Else Statement
Check the state of a traffic signal and generates the appropriate response.
Solution
●●● Input
light = "Red"
if light == "Green":
print("Go")
print("Caution")
print("Stop")
else:
print("Incorrect")
●●● Output
Stop
Note
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.
OceanofPDF.com
5. LOOPS
●●● Input
●●● Output
1
2
3
4
5
Note
●●● Input
num_list = [1, 2, 3, 4, 5]
print(num_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.
OceanofPDF.com
5.2. Nested For Loop
●●● Input
n = 10
for n1 in num_list:
for n2 in num_list:
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.
OceanofPDF.com
#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
found = False
for n1 in num_list:
for n2 in num_list:
if(n1 + n2 == n):
found = True
break
if found:
●●● Output
4 6
Note
You can break the loop whenever you need to using the break statement.
OceanofPDF.com
#70 Continue Statement
Exercise ★★★
●●● Input
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.
OceanofPDF.com
#71 Pass Statement
Exercise ★★★
●●● Input
if num == 3:
pass
else:
print(num)
●●● Output
Note
The pass statement does nothing for the execution of the code.
OceanofPDF.com
5.3. While Loop
●●● Input
num = 1
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.
OceanofPDF.com
#73 While Else
Exercise ★★★
●●● Input
num = 1
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.
OceanofPDF.com
#74 Break Statement
Exercise ★★★
Display the numbers in order from 1, and stop execution when the number
reaches 5.
Solution
●●● Input
num = 1
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.
OceanofPDF.com
#75 Continue Statement
Exercise ★★★
●●● Input
num = 0
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.
OceanofPDF.com
#76 Pass Statement
Exercise ★★★
●●● Input
num = 0
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.
OceanofPDF.com
6. FUNCTION
●●● Input
print(minimum)
●●● Output
10
Note
OceanofPDF.com
#78 Max function
Exercise ★★
●●● Input
print(maximum)
●●● Output
40
Note
OceanofPDF.com
Column: Why Use Function?
OceanofPDF.com
6.2. Built-In String Function
●●● Input
print(my_string.find("Hello"))
print(my_string.find("Goodbye"))
●●● 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.
OceanofPDF.com
#80 Replacing String
Exercise ★★
●●● Input
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.
OceanofPDF.com
#81 Changing Letter Case
Exercise ★★
●●● 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.
OceanofPDF.com
6.3. Type Conversion
●●● 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.
OceanofPDF.com
#83 Converting Data to Float
Exercise ★★
●●● 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.
OceanofPDF.com
#84 Converting Data to String
Exercise ★★
●●● Input
print(str(False))
●●● Output
False
123 is a string
Note
OceanofPDF.com
6.4. User-defined Function
●●● Input
def my_print_function():
# No parameters
print("apple")
print("orange")
print("grape")
# Function ended
●●● 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.
OceanofPDF.com
#86 Function Parameter
Exercise ★★★
Create a function to compare two numbers and print the smaller number.
Solution
●●● Input
print(first)
else:
print(second)
num1 = 12
num2 = 53
minimum(num1, num2)
●●● Output
12
Note
Create a function to compare two numbers and return the smaller value.
Solution
●●● Input
return first
else:
return second
num1 = 12
num2 = 53
●●● Output
12
Note
You can return something from a function using the return statement.
OceanofPDF.com
6.5. Lambda
●●● Input
print(triple(11))
●●● 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.
OceanofPDF.com
#89 Lambda Syntax 2
Exercise ★★
●●● Input
●●● Output
GOT
Note
It is a simple lambda that takes the first character of three strings and
concatenates them.
OceanofPDF.com
#90 If Else Statement
Exercise ★★★
●●● Input
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.
OceanofPDF.com
7. LIBRARY
●●● Input
import datetime
date_today = datetime.date.today()
# Current date
print(date_today)
time_today = datetime.datetime.now()
print(time_today.strftime("%H:%M:%S"))
# Current time
2021-01-10
10:12:30
Note
OceanofPDF.com
#92 Importing Individual Class
Exercise ★★★
●●● Input
# Current date
print(date_today)
2021-01-10
Note
If you want to extract only a specific class from a module, you can use the
from keyword.
OceanofPDF.com
#93 Importing and Naming Module
Exercise ★★★
●●● 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
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.
OceanofPDF.com