0% found this document useful (0 votes)
5 views16 pages

Programming Class Exercises Overview

This document contains exercises and questions related to programming concepts, including variable assignments, mathematical functions, selection statements, loops, strings, lists, tuples, and dictionaries. Each section provides specific tasks such as evaluating expressions, writing code snippets, and analyzing outputs. The exercises are designed to reinforce understanding of programming fundamentals and syntax.

Uploaded by

Glory Ifiegbu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

Programming Class Exercises Overview

This document contains exercises and questions related to programming concepts, including variable assignments, mathematical functions, selection statements, loops, strings, lists, tuples, and dictionaries. Each section provides specific tasks such as evaluating expressions, writing code snippets, and analyzing outputs. The exercises are designed to reinforce understanding of programming fundamentals and syntax.

Uploaded by

Glory Ifiegbu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Programming Class Exercises

(Set 2: Analyzing Programs)

Chapter 2 – Introductory Programming

2.8 What is wrong in the following statement? 2 = a


2.9 What is x, y, and z after the following statement? x = y = z = 0
2.10 Assume that a = 1 and b = 2. What is a and b after the following statement? a, b = b, a
2.12 If today is Tuesday, what day of the week will it be in 100 days?
2.14 How would you write the following arithmetic expression in Python?

Chapter 3 – Mathematical Functions and Strings

3.1 Evaluate the following functions:


(a) [Link](4) (j) [Link](-2.5)
(b) [Link](2 * [Link]) (k) round(3.5)
(c) [Link](2 * [Link]) (l) round(-2.5)
(d) min(2, 2, 1) (m) [Link](2.5)
(e) [Link](math.e) (n) [Link](2.5)
(f) [Link](1) (o) [Link](2.5)
(g) max(2, 3, 4) (p) round(-2.5)
(h) abs(-2.5) (q) round(2.6)
(i) [Link](-2.5) (r) round([Link](-2.5))
3.19 Show the printout of the following statements:
print(format(57.467657, "9.3f"))
print(format(12345678.923, "9.1f"))
print(format(57.4, ".2f"))
print(format(57.4, "10.2f"))
3.20 Show the printout of the following statements:
print(format(57.467657, "9.3e"))
print(format(12345678.923, "9.1e"))
print(format(57.4, ".2e"))
print(format(57.4, "10.2e"))
3.21 Show the printout of the following statements:
print(format(5789.467657, "9.3f"))
print(format(5789.467657, "<9.3f"))
print(format(5789.4, ".2f"))
print(format(5789.4, "<.2f"))
print(format(5789.4, ">9.2f"))
3.22 Show the printout of the following statements:
print(format(0.457467657, "9.3%"))
print(format(0.457467657, "<9.3%"))
3.23 Show the printout of the following statements:
print(format(45, "5d"))
print(format(45, "<5d"))
print(format(45, "5x"))
print(format(45, "<5x"))

1
3.24 Show the printout of the following statements:
print(format("Programming is fun", "25s"))
print(format("Programming is fun", "<25s"))
print(format("Programming is fun", ">25s"))

Chapter 4 – Selection Statements

4.2 Can the following conversions be allowed? If so, find the converted result.
i = int(True)
j = int(False)
b1 = bool(4)
b2 = bool(0)
4.3 How do you generate a random integer i such that 0 <= i < 20?
4.4 How do you generate a random integer i such that 10 <= i < 20?
4.5 How do you generate a random integer i such that 10 <= i <= 50
4.6 How do you generate a random integer 0 or 1?
4.7 Write an if statement that assigns 1 to x if y is greater than 0.
4.8 Write an if statement that increases pay by 3% if score is greater than 90.
4.9 Write an if statement that increases pay by 3% if score is greater than 90, otherwise it increases pay by 1%.
4.10 What is the printout of the code in (a) and (b) if number is 30 and 35, respectively?

Draw a flowchart diagram for the following equivalent programs:

4.11 Suppose x = 3 and y = 2; show the output, if any, of the following code. What is the output if x = 3 and y = 4?
What is the output if x = 2 and y = 2? Draw a flowchart for the code.

2
4.14 Which of the following statements are equivalent? Which ones are correctly indented?

4.17 What is the output of the following code if number is 14, 15, and 30?

4.18 Are the following two statements equivalent?

4.19 What is wrong in the following code?

4.20 Assuming that x is 1, show the result of the following Boolean expressions.
True and (3 > 4)
not (x > 0) and (x > 0)
(x > 0) or (x < 0)
(x != 0) or (x == 0)
(x >= 0) or (x < 0)
(x != 1) == not (x == 1)
4.31 Suppose that when you run the following program you enter the input 2, 3, 6 from the console. What is the
output?
x, y, z = eval(input("Enter three numbers: "))
print("sorted" if x < y and y < z else "not sorted")
4.32 Rewrite the following if statements using a conditional (ternary) expression:

4.33 Rewrite the following conditional (ternary) expressions using if/else statements:
(a) score = 3 * scale if x > 10 else 4 * scale
(b) tax = income * 0.2 if income > 10000 else income * 0.17 + 1000
(c) print(i if number % 3 == 0 else j)

3
4.36 Evaluate the following expressions:
2 * 2 - 3 > 2 and 4 – 2 > 5
2 * 2 - 3 > 2 or 4 – 2 > 5
4.37 Is (x > 0 and x < 10) the same as ((x > 0) and (x < 10))?
Is (x > 0 or x < 10) the same as ((x > 0) or (x < 10))?
Is (x > 0 or x < 10 and y < 0) the same as (x > 0 or (x < 10 and y < 0))?

Chapter 5 – Loops

5.3 How many times are the following loop bodies repeated? What is the printout of each loop?

5.4 Show the errors in the following code:

5.5 Suppose the input is 2 3 4 5 0 (one number per line). What is the output of the following code?

5.6 Suppose the input is 2 3 4 5 0 (one number per line). What is the output of the following code?

5.8 Convert the following for loop statement to a while loop:


sum = 0
for i in range(1001):
sum = sum + i

4
5.9 Can you always convert any while loop into a for loop? Convert the following while loop into a for loop.
i=1
sum = 0
while sum < 10000:
sum = sum + i
i += 1
5.11 Show the output of the following programs.

5.13 What is the keyword break for? What is the keyword continue for? Will the following program terminate? If
so, give the output.

5.14 The for loop on the left is converted into the while loop on the right. What is wrong? Correct it.

5.16 After the break statement in (a) is executed in the following loop, which statement is executed? Show the
output. After the continue statement in (b) is executed in the following loop, which statement is executed? Show
the output.

5
Chapter 8 – Strings and special functions

8.1 Suppose that s1, s2, s3, and s4 are four strings, given as follows:
s1 = "Welcome to Python"
s2 = s1
s3 = "Welcome to Python"
s4 = "to"
What are the results of the following expressions?
a. s1 == s2
b. [Link]('o')
c. id(s1) == id(s2)
d. id(s1) == id(s3)
e. s1 <= s4
f. s2 >= s4
g. s1 != s4
h. [Link]()
i. [Link](s4)
j. s1[4]
k. s1[4 : 8]
l. 4 * s4
m. len(s1)
n. max(s1)
o. min(s1)
p. s1[-4]
q. [Link]()
r. [Link]('o')
s. [Link]("o")
t. [Link]("o")
u. [Link]()
v. s1 + s1
8.4 Let s1 be " Welcome " and s2 be " welcome ". Write the code for the following statements:
(a) Check whether s1 is equal to s2 and assign the result to a Boolean variable isEqual.
(b) Check whether s1 is equal to s2, ignoring case, and assign the result to a Boolean variable isEqual.
(c) Check whether s1 has the prefix AAA and assign the result to a Boolean variable b.
(d) Check whether s1 has the suffix AAA and assign the result to a Boolean variable b.
(e) Assign the length of s1 to a variable x.
(f) Assign the first character of s1 to a variable x.
(g) Create a new string s3 that combines s1 with s2.
(h) Create a substring of s1 starting from index 1.
(i) Create a substring of s1 from index 1 to index 4.
(j) Create a new string s3 that converts s1 to lowercase.
(k) Create a new string s3 that converts s1 to uppercase.
(l) Create a new string s3 that trims whitespace characters on both ends of s1.
(m) Replace e with E in s1.
(n) Assign the index of the first occurrence of character e in s1 to a variable x.
(o) Assign the index of the last occurrence of string abc in s1 to a variable x.
8.5 Does any method in the string object change the contents of the string?
8.6 Suppose string s is an empty string; what is len(s)?
8.7 How do you determine whether a character is in lowercase or uppercase?
8.8 How do you determine whether a character is alphanumeric?

6
Chapter 10 – Lists

10.1 How do you create an empty list and a list with the three integers 1, 32, and 2?
10.2 Given lst = [30, 1, 12, 14, 10, 0], how many elements are in lst?
What is the index of the first element in lst?
What is the index of the last element in lst?
What is lst[2]?
What is lst[-2]?
10.3 Given lst = [30, 1, 2, 1, 0], what is the list after applying each of the following statements? Assume that each
line of code is independent.
[Link](40)
[Link](1, 43)
[Link]([1, 43])
[Link](1)
[Link](1)
[Link]()
[Link]()
[Link]()
[Link](lst)
10.4 Given lst = [30, 1, 2, 1, 0], what is the return value of each of the following statements?
[Link](1)
[Link](1)
len(lst)
max(lst)
min(lst)
sum(lst)
10.5 Given list1 = [30, 1, 2, 1, 0] and list2 = [1, 21, 13], what is the return value of each of the following
statements?
list1 + list2
2 * list2
list2 * 2
list1[1 : 3]
list1[3]
10.6 Given list1 = [30, 1, 2, 1, 0], what is the return value of each of the following statements?
[x for x in list1 if x > 1]
[x for x in range(0, 10, 2)]
[x for x in range(10, 0, -2)]
10.7 Given list1 = [30, 1, 2, 1, 0] and list2 = [1, 21, 13], what is the return value of each of the following
statements?
list1 < list2
list1 <= list2
list1 == list2
list1 != list2
list1 > list2
list1 >= list2
10.8 Indicate true or false for the following statements:
(a) Every element in a list must have the same type.
(b) A list’s size is fixed after it is created.
(c) A list can have duplicate elements.
(d) The elements in a list can be accessed via an index operator.

7
10.12 Write statements to do the following:
(a) Create a list with 100 Boolean False values.
(b) Assign the value 5.5 to the last element in the list.
(c) Display the sum of the first two elements.
(d) Compute the sum of the first five elements in the list.
(e) Find the minimum element in the list.
(f) Randomly generate an index and display the element of this index in the list.
10.13 What happens when your program attempts to access a list element with an invalid index?
10.14 What is the output of the following code?
lst = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
lst[i] = lst[i - 1]
print(lst)
10.15 What is the output of the following code?
list1 = list(range(1, 10, 2))
list2 = list1
list1[0] = 111
print(list1)
print(list2)
10.16 What is the output of the following code?
list1 = list(range(1, 10, 2))
list2 = [] + list1
list1[0] = 111
print(list1)
print(list2)
10.19 Show the output of the following two programs:

Chapter 14 – Tuples and Dictionaries

14.1 What are the differences between a list and a tuple? How do you create a tuple from a list? How do you create
a list from a tuple?
14.2 What is wrong in the following code?
t = (1, 2, 3)
[Link](4)
[Link](0)
t[0] = 1
14.3 Is the following code correct?
t1 = (1, 2, 3, 7, 9, 0, 5)
t2 = (1, 2, 5)
t1 = t2
8
14.4 Show the printout of the following code:
t = (1, 2, 3, 7, 9, 0, 5)
print(t)
print(t[0])
print(t[1: 3])
print(t[-1])
print(t[ : -1])
print(t[1 : -1])
14.5 Show the printout of the following code:
t = (1, 2, 3, 7, 9, 0, 5)
print(max(t))
print(min(t))
print(sum(t))
print(len(t))
14.6 Show the printout of the following code:
t1 = (1, 2, 3, 7, 9, 0, 5)
t2 = (1, 3, 22, 7, 9, 0, 5)
print(t1 == t2)
print(t1 != t2)
print(t1 > t2)
print(t1 < t2)
14.18 How do you create an empty dictionary?
14.19 Which of the following dictionaries are created correctly?
d = {1:[1, 2], 3:[3, 4]}
d = {[1, 2]:1, [3, 4]:3}
d = {(1, 2):1, (3, 4):3}
d = {1:"john", 3:"peter"}
d = {"john":1, "peter":3}
14.20 Each item in a dictionary has two parts. What are they called?
14.21 Suppose a dictionary named students is {"john":3, "peter":2}. What do the following statements do?
(a) students["susan"] = 5
(b) students["peter"] = 5
(c) students["peter"] += 5
(d) del students["peter"]
14.22 Suppose a dictionary named students is {"john":3, "peter":2}. What do the following statements do?
(a) print(len(students))
(b) print([Link]())
(c) print([Link]())
(d) print([Link]())
14.23 Show the output of the following code:
def main():
d = {"red":4, "blue":1, "green":14, "yellow":2}
print(d["red"])
print(list([Link]()))
print(list([Link]()))
print("blue" in d)
print("purple" in d)
d["blue"] += 10
print(d["blue"])
main() # Call the main function

9
14.24 Show the output of the following code:
def main():
d = {}
d["susan"] = 50
d["jim"] = 45
d["joan"] = 54
d["susan"] = 51
d["john"] = 53
print(len(d))
main() # Call the main function
14.25 For a dictionary d, you can use d[key] or [Link](key) to return the value for the key. What are the differences
between them?

Chapter 6 - Funtions

6.1 What are the benefits of using a function?


6.2 How do you define a function? How do you invoke a function?
6.4 True or false? A call to a None function is always a statement itself, but a call to a value-returning function is
always a component of an expression.
6.5 Can you have a return statement in a None function? Does the return statement in the following function
cause syntax errors?
def xFunction(x, y):
print(x + y)
return
6.6 Define the terms function header, parameter, and argument.
6.7 Write function headers for the following functions (and indicate whether the function returns a value):
■ Computing a sales commission, given the sales amount and the commission rate.
■ Printing the calendar for a month, given the month and year.
■ Computing a square root.
■ Testing whether a number is even, and returning true if it is.
■ Printing a message a specified number of times.
■ Computing the monthly payment, given the loan amount, number of years, and annual interest rate.
■ Finding the corresponding uppercase letter, given a lowercase letter.

6.8 Identify and correct the errors in the following program:

10
6.9 Show the output of the following code:

6.10 What error will occur when you run the following code?

6.11 Compare positional arguments and keyword arguments.


6.12 Suppose a function header is as follows:
def f(p1, p2, p3, p4):
Which of the following calls are correct?
f(1, p2 = 3, p3 = 4, p4 = 4)
f(1, p2 = 3, 4, p4 = 4)
f(p1 = 1, p2 = 3, 4, p4 = 4)
f(p1 = 1, p2 = 3, p3 = 4, p4 = 4)
f(p4 = 1, p2 = 3, p3 = 4, p1 = 4)
6.13 What is pass-by-value?
6.14 Can the argument have the same name as its parameter?
6.15 Show the result of the following programs:

11
6.16 For (a) in the preceding question, show the contents of the stack just before the function max is invoked, just
as max is entered, just before max is returned, and right after max is returned.
6.17 What is the printout of the following code?

6.18 What is wrong in the following code?


1 def function():
2 x = 4.5
3 y = 3.4
4 print(x)
5 print(y)
6
7 function()
8 print(x)
9 print(y)
6.20 Show the printout of the following code:
def f(w = 1, h = 2):
print(w, h)
f()
f(w = 5)
f(h = 24)
f(4, 5)
6.21 Identify and correct the errors in the following program:
1 def main():
2 nPrintln(5)
3
4 def nPrintln(message = "Welcome to Python!", n):
5 for i in range(n):
6 print(message)
7
8 main() # Call the main function
6.22 What happens if you define two functions in a module that have the same name?

12
6.23 Can a function return multiple values? Show the printout of the following code:
1 def f(x, y):
2 return x + y, x - y, x * y, x / y
3
4 t1, t2, t3, t4 = f(9, 5)
5 print(t1, t2, t3, t4)
6.24 Write an expression that returns a random integer between 34 and 55, inclusively.
6.25 Write an expression that returns a random character between B and M, inclusively.
6.26 Write an expression that returns a random number between 6.5 and 56.5 (excluding 56.5).
6.27 Write an expression that returns a random lowercase letter.

Chapter 15 – Recursion

15.1 What is a recursive function?


15.2 How many times would the factorial function in Listing 15.1 be invoked for factorial(6)?
15.3 Write a recursive mathematical definition for computing 2n for a positive integer n.
15.4 Write a recursive mathematical definition for computing xn for a positive integer n and a real number x.
15.5 Write a recursive mathematical definition for computing 1 + 2 + 3 + …+ n for a positive integer.
15.6 What is an infinite recursion? What is a direct recursion? What is an indirect recursion?

15.7 How many times would the fib function in Listing 15.2 be invoked for fib(6)?
15.8 Show the output of the following programs and identify their base cases and recursive calls.

15.9 Describe the characteristics of recursive functions.


15.10 Show the call stacks for isPalindrome("abcba") using the functions defined in Listing 15.3.
15.11 Show the output of the following two programs:

15.12 What is wrong in the following function?

13
Chapter 13 - File Input /Output

13.1 How do you open a file for reading, for writing, and for appending, respectively?
13.2 What is wrong about creating a file object using the following statement?
infile = open("c:\book\[Link]", "r")
13.3 When you open a file for reading, what happens if the file does not exist? When you open a file for writing,
what happens if the file already exists?
13.4 How do you determine whether a file exists?
13.5 What method do you use to read 30 characters from a file?
13.6 What method do you use to read all data into a string?
13.7 What method do you use to read a line?
13.8 What method do you use to read all lines into a list?
13.9 Will your program have a runtime error if you invoke read() or readline() at the end of the file?
13.10 When reading data, how do you know if it is the end of the file?
13.11 What function do you use to write data to a file?
13.12 How do you denote a raw string literal in the program?
13.13 How do you write and read numeric data?
13.14 How do you display a file dialog for opening a file?
13.15 How do you display a file dialog for saving a file?
13.16 How do you open a Web page from a Python program?
13.17 What function can be used to return a raw string from a normal string?

Chapter 13: Exception Handling

13.18 Suppose that statement2 causes an exception in the following try-except block:
try:
statement1
statement3
except Exception1:
# Handle exception 1
except Exception2:
# Handle exception 2
statement4
Answer the following questions:
■ Will statement3 be executed?
■ If the exception is not caught, will statement4 be executed?
■ If the exception is caught in the except block, will statement4 be executed?

13.19 What is displayed when the following program is run?


try:
list = 10 * [0]
x = list[10]
print("Done ")
except IndexError:
print("Index out of bound")

14
13.20 What is displayed when the following program is run?
def main():
try:
f()
print("After the function call")
except ZeroDivisionError:
print("Divided by zero!")
except:
print("Exception")
def f():
print(1 / 0)
main() # Call the main function
13.21 What is displayed when the following program is run?
def main():
try:
f()
print("After the function call")
except IndexError:
print("Index out of bound")
except:
print("Exception in main")
def f():
try:
s ="abc"
print(s[3])
except ZeroDivisionError:
print("Divided by zero!")
main() # Call the main function
13.22 Suppose that statement2 causes an exception in the following statement:
try:
statement1
statement3
except Exception1:
# Handle exception
except Exception2:
# Handle exception
except Exception3:
# Handle exception
finally:
statement4
statement5
Answer the following questions:
■ Will statement5 be executed if the exception is not caught?
■ If the exception is of type Exception3, will statement4 be executed, and will statement5 be executed?
13.23 How do you raise an exception in a function?
13.24 What are the benefits of using exception handling?

15
13.25 What is displayed when the following program is run?
try:
lst = 10 * [0]
x = lst[9]
print("Done")
except IndexError:
print("Index out of bound")
else:
print("Nothing is wrong")
finally:
print("Finally we are here")
print("Continue")
13.27 What is wrong in the following code?
try:
# Some code here
...
except ArithmeticError:
print("ArithmeticError")
except ZeroDivisionError:
print("ZeroDivisionError")
print("Continue")
13.28 How do you define a custom exception class?

[END]

16

You might also like