Dokumen.pub Python Workbook for Beginners 93 Coding and Programming Exercises for Software Development Engineer Crash Course Practice Questions and Answers Software Development Engineer Workbook 1
Dokumen.pub Python Workbook for Beginners 93 Coding and Programming Exercises for Software Development Engineer Crash Course Practice Questions and Answers Software Development Engineer Workbook 1
#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
#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.
#2 Comments in Code
Exercise ★
●●● Input
print("Hello World")
●●● Output
Hello World
Note
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).
2.4. String
●●● Input
print("apple pie")
●●● Output
apple pie
apple pie
Note
●●● Input
●●● Output
Note
You just have to separate multiple things using the comma to print
them in a single print command.
#9 Length of String
Exercise ★★
●●● Input
●●● Output
Note
●●● 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.
Column: Index
●●● Input
print(my_string[0:5])
●●● Output
apple
pie
Note
#12 Addition
Exercise ★
●●● Input
print(5 + 8)
●●● Output
13
Note
●●● Input
print(15 - 7)
●●● Output
Note
You can subtract one number from another using the - operator.
#14 Multiplication
Exercise ★
●●● Input
print(30 * 5)
●●● Output
150
Note
●●● Input
print(30 / 10)
●●● Output
3.0
Note
●●● Input
print(5 > 3)
# 5 is greater than 3
print(5 < 3)
# 5 is less than 3
print(5 >= 3)
●●● Output
True
False
True
False
False
False
False
True
Note
●●● Input
my_num = 123
my_num = 321
●●● Output
123
321
Note
Variables are mutable, so you can change their values at any time.
2.9. Logical Operator
●●● Input
num = 6
●●● Output
True
True
False
Note
#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
●●● 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.
#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().
#24 Nested List
Exercise ★★
●●● Input
print(my_list)
●●● Output
Note
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.
#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
●●● 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.
#28 Inserting Element
Exercise ★★
●●● Input
my_list.insert(1, "banana")
●●● Output
Note
●●● 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.
#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.
#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.
#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.
#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 ().
#35 Merging Tuple
Exercise ★
●●● Input
print(my_tup3)
●●● Output
Note
●●● Input
print(my_tup3)
●●● Output
Note
Instead of merging the two tuples, you can create a nested tuple
with these two tuples.
#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.
#38 Verify Existence of Element
Exercise ★★
●●● Input
print("orange" in my_tup)
print("pineapple" in my_tup)
●●● Output
True
False
Note
●●● 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.
#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.
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
●●● Input
print(phone_book)
del phone_book["Bob"]
print(phone_book)
●●● Output
Note
●●● 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.
#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.
#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.
#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
●●● 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.
#49 Creating Set 2
Exercise ★★
●●● Input
print(my_set)
●●● Output
Note
You can create a set in a different way using the set() constructor.
#50 Length of Set
Exercise ★★
●●● Input
●●● Output
Note
●●● 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 ★★★
●●● 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.
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.
#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.
#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.
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.
#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.
#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.
#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.
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
●●● 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.
4.3. If Elif Else Statement
●●● 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.
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.
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.
#69 Break Statement
Exercise ★★★
●●● Input
n = 10
found = False
for n2 in num_list:
if(n1 + n2 == n):
found = True
●●● Output
4 6
Note
You can break the loop whenever you need to using the break
statement.
#70 Continue Statement
Exercise ★★★
●●● Input
if num == 3:
continue
print(num)
●●● Output
Note
●●● Input
if num == 3:
pass
else:
print(num)
●●● Output
Note
The pass statement does nothing for the execution of the code.
5.3. While Loop
●●● Input
num = 1
print(num)
num = num + 1
●●● Output
Note
●●● Input
num = 1
print(num)
num = num + 1
else:
print("Done")
●●● Output
Done
Note
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
●●● Input
num = 0
num += 1
# num = num + 1
if num == 3:
continue
print(num)
●●● Output
Note
●●● 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.
6. FUNCTION
●●● Input
print(minimum)
●●● Output
10
Note
●●● Input
print(maximum)
●●● Output
40
Note
●●● 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.
#80 Replacing String
Exercise ★★
●●● Input
print(my_string)
print(new_string)
●●● Output
Hello World!
Goodbye World!
Note
●●● 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
●●● 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 ★★
●●● Input
print(float(13))
print(float(True))
●●● Output
13.0
1.0
Note
●●● Input
print(str(False))
●●● Output
False
123 is a string
Note
●●● 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 ★★★
●●● Input
print(first)
else:
print(second)
num1 = 12
num2 = 53
minimum(num1, num2)
●●● Output
12
Note
●●● Input
return first
else:
return second
num1 = 12
num2 = 53
●●● Output
12
Note
●●● 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.
#89 Lambda Syntax 2
Exercise ★★
●●● Input
●●● Output
GOT
Note
●●● Input
print(my_function(110))
print(my_function(60))
●●● Output
High
Low
Note
●●● 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
●●● 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.
#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.