0% found this document useful (0 votes)
8 views21 pages

Practice Questions Introduction to Python

The document contains a series of practice questions related to Python programming, covering topics such as file extensions, variable names, operators, string manipulation, error handling, and control flow. It includes multiple-choice questions, code analysis, and error identification tasks. Additionally, it features a BMI calculation exercise requiring a Python program implementation.
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)
8 views21 pages

Practice Questions Introduction to Python

The document contains a series of practice questions related to Python programming, covering topics such as file extensions, variable names, operators, string manipulation, error handling, and control flow. It includes multiple-choice questions, code analysis, and error identification tasks. Additionally, it features a BMI calculation exercise requiring a Python program implementation.
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
You are on page 1/ 21

practice questions

i. What is the correct extension for a Python file?

a) .python b) .pl c) .py d) .p

ii. What value does the following expression evaluate to? 2.0+9*((3*12)–6)/10
a) 29 b) 29.0 c) 33.0 d) None of these
iii. Which of the following is NOT a valid variable name in Python?

a) _name b) name1 c) 1name d) b and c

iv. How many operands are there in the following arithmetic expression? 6*35+8−25

a) 4 b) 3 c) 5 d) 8

v. In Python an identifier is _____________ .


a) Machine dependent b) Keyword c) Case sensitive d) Constant

vi. Which of the following operator is truncation division operator?


a) / b) % c) ÷ d) //

vii. How do you create a string in Python?


a) by enclosing text in quotes (' or ") b) by using square brackets []
c) by using curly braces {} d) by using the String() function
viii. The operators is and is not are examples of which type of operators?
a) Identity b) Comparison c) Membership d) Unary

ix. Which method converts all characters in a string to uppercase?


a) upper() b) capitalize() c) toUpper() d) isupper()
x. Which of the following function is used to read data from the keyboard?

a) function() b) get_input() c) input() d) int()

xi. which of the following is not a keyword in Python?

a) pass b) eval c) assert d) nonlocal

xii. What is the correct syntax for slicing a string to get the first three characters?

a) string [0:3] b) string (0,3) c) string {0:3} d) string [1:4]

xiii. Incorrect Indentation results in _____________.


a) SyntaxError b) NameError c) IndentationError d) TypeError

xiv. Which of the following statements about comments in Python is FALSE?

a) Comments are ignored by the interpreter


b) Single-line comments can be written using #
c) Multi-line comments can be enclosed in triple quotes
d) Comments help make code run faster

xv. Which of the following will result in an error?


a) int('10.8') b) float(10) c) int(10) d) float(10.8)

xvi. What is the output of the following expression: a) float(22//3+3/3)


8 b) 8.0 c) −8.3 d) 8.333
xvii. What is the maximum length of an identifier in Python?
a) 80 characters b) 256 characters c) 100 characters d) none of the mentioned

xviii. Which of the following is correct about Python?


a) Python is a high-level, interpreted, interactive and object-oriented language
b) Python is designed to be highly readable
c) It uses English keywords frequently and has fewer syntactical constructions
d) All of the above

xix. How many binary operators are there in the following arithmetic expression? -
6+10/(23+56)
a) 2 b) 3 c) 4 d) 1

xx. Which of the following best describes the main difference between a compiler and an
interpreter?
a) A compiler translates the entire code at once, whereas an interpreter executes code line
by line.
b) A compiler processes code line by line, while an interpreter compiles the entire code at
once.
c) A compiler generates an independent executable file, while an interpreter requires
source code every time it runs.
d) Interpreted languages generally offer easier debugging compared to compiled
languages.

Code Analysis Questions

2. What will be the output of the following Python statement(s)/code?


i. print(1 > 2 and 9 > 6)

ii. num1 = 20
num2 = 10/4
answer = num1 % 8 // num2
print(f“The final answer is : {answer}”)

iii. a,b,c = 1000, 2000, 3000.0


print(a – b - c)

iv. length(“Hello World!”)

v. first_name = ‘chikondi’
print(first_name[0:5])

vi. first_name = ‘chikondi’


print(first_name[0::2])

vii. last_name = ‘james’


print(last_name[::-1])

viii. sentence = "Python is fun"


words = sentence.split()
print(words)

ix. print('new' 'line')

x. text = “The University of Science & Technology”


result = text.replace("The", "Malawi")
result = result.replace("&", "and") result =
result.lower().replace(" ", "_") print(result)

3. With a proper example, explain the meaning of a logic error in Python.

4. Identify the errors in the following Python code snippets and suggest how to correct them
using a table format as shown below.
NB: Do not rewrite the entire code, just fix the errors by modifying the necessary line(s).

Line # Possible Error or description Suggested Fix


2 SyntaxError – The variable name should be customer_id = 100
on the left and the value on the right hand
side of the assignment operator
32
i
. print(“Temperature in Fahrenheit:” + Fahrenheit)
Temperature conversion program
c
e
l
s
ii.
i
u
s

2
5
f
a
h
r
e
n
h
e
i
t

(
c
e
l
c
i
u
s

9
/
5
)

+
A circle program
re
pie = 3.14
a
of radius = input(“Enter the Radius of the circle:”)
a
print(“The area of the circle is”, pi x radius x radius

iii. Item price calculator program

program_name = “Discount calculator” 100 =


“Customer ID” itemPrice = 100

Discount = “10”
final_price = itemPrice - discount print(“The final price
is”, final_price)

5. BMI (Body Mass Index) is a numerical value derived from a person's weight and height. It is used as a

simple screening tool to classify individuals into different weight categories, such as underweight, normal

weight, overweight, or obese. It is calculated using the formula:


=
(ℎ ℎ )
Write a Python program that asks any user for their first name, last name, weight (in kg), height (in

meters) and calculate and display the user’s full name (in a proper format i.e., only first letter of first name

and last name should be displayed in upper cases regardless of how the user entered them) and their BMI

as shown in the sample output below. (16 marks)

------BMI Calculator------
User : Chimwemwe Chosatha
Weight : 80 kgs
Height : 1.5 m
--------------------------
BMI : 35.55555555555556
--------------------------
1. What happens if the condition in an if statement is False?
a) The code block under if is executed.
b) The code block under else is executed.
c) The code block under if is skipped.
d) The program crashes.
2. What keyword is used to start a conditional statement in Python?
a) when b) if
c) check d) condition
3. What is the result of (5 > 3) and (2 < 1)?
a) True b) False
c) 5 d) None
4. Which statement is used to handle multiple conditions in Python?
a) if b) if-else
c) if-elif-else d) switch
5. What is the output of the following code?
x = 10
if x > 5:
print(“Greater”)
else:
print(“Smaller”)
a) Greater b) Smaller
c) 10 d) None
6. What is the output of the following code?
x=5
if x < 5:
print("Less")
elif x == 5:
print("Equal")
else:
print("Greater")
a) Less b) Equal
c) Greater d) None
7. What is a nested if statement?
a) An if statement inside another if statement.
b) An if statement with multiple elif blocks.
c) An if statement without an else block.
d) An if statement that repeats itself.
8. How is the level of nesting indicated in Python?
a) Using curly braces {}. b) Using parentheses ().
c) Using indentation. d) Using semicolons ;

9. What is the output of the following code?


x = 10
y=5
if x > y:
if x == 10:
print("x is 10")
else:
print("x is not 10")
else:
print("y is greater")
a) x is 10 b) x is not 10
c) y is greater d) None

10. What is the output of the following code if the user enters "hello"?
word = input('Enter your word: ')
if len(word) < 5:
print("Less than 5")
elif len(word) > 5:
print("Greater than 5")
else:
print("Equal to 5")
a) Less than 5 b) Greater than 5
c) Equal to 5 d) None

11. What will be the output of the code:


a) i = 0
b) while i < 5:
c) print(i)
d) i += 1
e) if i == 3:
f) break
g) else:
h) print(0)

a)1 b) 0 1 2 0
c) 0 1 2 d) 2
12. What will be the output of the code:
a) x = 'abcd'
b) for i in range(len(x)):
c) print(i, end= “ ”)

a) abc b) 1 2 3 4
c) a b c d d) 0 1 2 3
13. What is the output of the following code?
a) count = 1
b) while count < 3:
c) print(count)
d) count += 1

a) 1 2 3 b) 1 2
c) 1 d) 2 3
14. Which of the following is true about the for loop in Python?
a) It is used only for numeric ranges
b) It must include a break statement
c) It is used for iterating over sequences like lists, tuples, and strings
d) It executes only once
15. What is the role of the pass statement in Python loops?
a) Terminates the loop b) Skips an iteration
c) Does nothing d) Repeats the last iteration
16. Which of the following will create an infinite loop?
a) for i in range(5): print(i) b) while True: print("Hi")
c) while i < 5: print(i); i += 1 d) for i in range(1, 5): continue
17. In a for loop like for i in range(3):, what values will i take?
a) 0, 1, 2 b) 1, 2, 3
c) 0, 1, 2, 3 d) 1, 2
18. What will be printed by the following code?
a) for i in range(4):
b) if i == 2:
c) continue
d) print(i)
a) 0 1 2 3 b) 0 1 3
c) 2 3 d) 0 1 2

19. Choose the correct syntax for a for loop in Python.


a) for (i = 0; i < 5; i++): b) for i in 0 to 5:
c) for i in range(5): d) foreach i in range(5)
20. What will this code print:
for i in range(2):
for j in range(2):
if j == 1:
break
print(i, j)
a) (0,0) (0,1) (1,0) (1,1) b) (0,0) (1,0)
c) (0,1) (1,1) d) (0,0) (0,1)

21. Which line correctly calls a function in Python?


a) function_name argument1, argument2 b) function_name(argument1, argument2)
c) function_name = (argument1, argument2) d)call function_name(argument1, argument2)
22. Which of these is not a valid function name?
a) calculate_sum b) print123
c) 1stFunction c) totalAmount
23. Which keyword is used to define a function in Python?

a) func b) define
c) def d) function

24. What will the following code output?

def greet(name):
return "Hello " + name
print(greet("Sam"))

a) Hello b) greet Sam


c) Hello Sam d) Error

25. What will be the output of the following code?


def x():
a = 10
return a ** 2

def y():
b = x()
return b // 40
a) 10 b) 100
c) 2 d) 2.5

26. Which of these will correctly pass an arbitrary number of arguments to a function?

a) def fun(*args) b) def fun(args*)


c) def fun(**args) d) def fun(args)

27. What will the following code print?

def add(x, y=5):


return x + y
print(add(3))

a) 3 b) 5
c) 8 d) Error

28. What type of value does the following function return?


def is_even(x):
return x % 2 == 0
a) Complex b) Integer
c) Boolean d) Float
29. What is the result of this function call?

def fruits(**kwargs):
return kwargs["apple"]
print(fruits(apple=5, orange=10))

a) {'apple': 5, 'orange': 10} b) 5


c) 10 d) Error

30. Which variable has local scope in this example?


def multiply():
result = 4 * 5
return result

a) multiply b) result
c) def d) 4

31. What symbol is used to define a list in Python?

a) () b) {}
c) [] d) <>

32. Which method adds a new item at the end of a list?

a) insert() b) add()
c) append() d) extend()
33. Given numbers = [10, 20, 30, 40, 50], what does numbers[1:4] return?

a) [10, 20, 30] b) [20, 30, 40]


c) [30, 40, 50] c) [20, 30, 40, 50]
34. Which code snippet creates a new list containing squares of numbers from 1 to 5?

a) [x*x for x in range(1,6)] b) [x^2 for x in range(1,6)]


c) [x** for x in range(1,6)] c) [x for x in range(1,6)]
35. What is the result of the following slice operation?

numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:5:2])

a) [1, 2, 3, 4] b) [1, 3, 5]
36. Which of the following can be used as a dictionary key?
a) A list of integers b) Another dictionary
c) A tuple of integers d) A set

37. How do you access the element "dog" from:

pets = [["cat", "dog"], ["fish", "hamster"]]?

a) pets[0][1] b)pets[1][0]
c) pets[1][1] d)pets[0][0]
38. What is the result of this dictionary operation?

d = {'a': 1, 'b': 2, 'a': 3}


print(d)

a) {'a': 1, 'b': 2} b) {'a': 3, 'b': 2}


c) Error d) {'a': 1, 'a': 3, 'b': 2}

39. What is the correct way to define a dictionary?

a) my_dict = ('key': 'value') b) my_dict = ['key': 'value']


c) my_dict = {'key': 'value'} d) my_dict = <'key': 'value'>
40. Consider the following code. What does it return?

a = [1, 2, 3]
b=a
b[0] = 10
print(a)

a) [1, 2, 3] b) [10, 2, 3]
c) [1, 2, 10] d) Error

1. Describe what the following code does. What input will cause it to print “Access Granted”?
username = input("Enter username: ")
password = input("Enter password: ")

if username == "admin" and password == "1234":


print("Access Granted")
else:
print("Access Denied")
Answer: The program checks if the username is "admin" and the password is "1234".It prints "Access Granted"
only if both match.

2. Rewrite the following nested if statement using logical operators:


if age >= 18:
if country == "Malawi":
print("Eligible to vote")
Answer: if age >= 18 and country == "Malawi":
print("Eligible to vote")
3. What will be the output of the following code?
a.

i=1
while i < 5:
print(i)
i += 1

Answer:
1
2
3
4

b.
for i in range(5):
if i == 2:
continue
print(i)
Answer:
0
1
3
4
4. Given the following dictionary, what will be the output?

student = {"name": "Alice", "age": 20, "course": "sed"}


print(student.keys())
Answer: dict_keys(['name', 'age', 'course'])

5. Predict the Output of the following Python program:


x = ["Malawi", "Botswana", "Zimbabwe", [43,55,66,77]]
for i in x:
break
print(i)
Answer: Malawi
6. Create a function sum_list(lst) that returns the sum of all numbers in a list (use loops to solve this problem).

Answer:
def sum_list(lst):
total = 0
for num in lst:
total += num
return total
7. What will this function return, and why?

def mystery(a, b):


return a * b
print(mystery("Hi", 3))
Answer: HiHiHi
The string "Hi" is multiplied 3 times, resulting in "HiHiHi".

Choose the most appropriate answer.

1. What will be the output of the following code?


x=5
y=0
if x % 2 == 1 and y == 0:
print("Odd and Zero")
else:
print("Condition failed")
a) Odd and Zero b) Odd
c) Zero d) Condition failed
2. Which of the following correctly checks if a number is both greater than 10 and not equal to 15?
a) num > 10 and num != 15 b) num > 10 or num != 15
c) num < 10 and num != 15 d) num >= 10 or num == 15
3. What is the output of the following Python snippet?
count = 3
while count < 3:
print(count)
count += 1
a) 3 b) 0
c) No output d) Error
4. Given x = 12, what does x // 5 return?
a) 2.4 b) 2
c) 3 d) 2.0
5. What is the correct syntax for a function in Python?
a) function myFunc(): b) def myFunc:
c) def myFunc(): d) func myFunc()
6. What will be the output of the following code?

x=7
if x > 5 and not x < 10:
print("Condition met")
else:
print("Condition not met")

a) Condition met b) Condition not met


c) Error d) None
7. What is the correct syntax for an `if-elif-else` ladder in Python?

a) if...elseif...else b) if...elif...else
c) if...else if...else d) if...then...else

8. What is the output of this code?

age = 20
country = "Malawi"
if age > 18 or country != "Zambia":
print("Allowed")
else:
print("Denied")

a) Allowed b) Denied
c) Error d) None

9. How many times will the following loop execute?


for i in range(2, 10, 2):
print(i)

a) 3 b) 4
c) 5 d) 6

10. What is the output of this nested loop?


for i in range(2):
for j in range(2):
print(i + j, end=" ")

a) 0 1 1 2 b) 0 1 2 3
c) 0 1 1 2 d) 0 1 1 2

11. What does the `continue` statement do in a loop?

a) Terminates the loop b) Skips the current iteration


c) Repeats the last iteration d) Skips the loop entirely

12. Which of the following will result in an infinite loop?

a) for i in range(10): print(i) b) while True: print("Hello")


c) for i in range(1, 3): continue d) while False: pass

13. What is the output of the following?

x = [10, 20, 30]


x[1] = x[1] + x[2]
print(x)

a) [10, 50, 30] b) [10, 20, 30]


c) [10, 30, 30] d) [10, 20, 50]

14. Which of the following methods removes an item from a list?

a) pop() b) remove()
c) del d) All of the above

15. What is the output of the following list comprehension?

result = [x for x in range(5) if x % 2 == 0]


print(result)

a) [1, 2, 3, 4] b) [0, 2, 4]
c) [2, 4] d) [1, 3]

16. Which of the following is NOT a mutable data type?

a) list b) dictionary
c) tuple d) set

17. What does this code return?

a = [1, 2, 3]
b = a[:]
b[0] = 10
print(a)

a) [1, 2, 3] b) [10, 2, 3]
c) [1, 10, 3] d) Error

18. What is the output of the following code?

data = {"a": 1, "b": 2}


data["a"] += 3
print(data["a"])

a) 1 b) 2
c) 3 d) 4

19. What does the following code output?

items = {1, 2, 3, 2, 1}
print(len(items))

a) 5 b) 4
c) 3 d) 2

20. What will be the output?

x=5
if x > 3:
print("A")
elif x > 2:
print("B")
else:
print("C")

a) A b) B
c) C d) A B

21. Which of the following statements is True about lists?

a) Lists are immutable b) Lists are defined using ()


c) List elements can be of different data types d) Lists cannot be nested

22. What does `range(1, 10, 3)` generate?

a) [1, 2, 3, 4, 5, 6, 7, 8, 9] b) [1, 4, 7]
c) [1, 5, 9] d) [1, 3, 6, 9]

23. Choose the correct way to create a dictionary from two lists:

a) dict([1, 2], [3, 4]) b) dict(zip([1, 2], [3, 4]))


c) dict((1, 3), (2, 4)) d) dict[1:3, 2:4]

24. What will be the output of this function?

def repeat(msg, times):


return msg * times
print(repeat("Go", 2))

a) Go Go b) GoGo
c) Go2 d) Error

25. What will this return?

nums = [1, 2, 3, 4]
squares = [n**2 for n in nums if n % 2 == 0]
print(squares)

a) [1, 4, 9, 16] b) [2, 4]


c) [4, 16] d) [1, 9]

26. What is the output of the following code?

x=7
if x % 2 == 0:
print("Even")
else:
print("Odd")

a) 7 b) Even
c) Odd d) Error

27. Which of the following is a valid Python list comprehension to get squares of even numbers from 0 to 10?

a) [x^2 for x in range(11) if x%2==0]


b) b) [x*x for x in range(11) if x%2==0]
c) {x*x for x in range(11) if x%2==0}
d) d) list(x*x for x in range(11) if x%2==0)

28. What is the output of this code?

x = [1, 2, 3]
x.append([4,5])
print(x)

a) [1, 2, 3, 4, 5] b) [1, 2, 3, [4, 5]]


c) 1 2 3 4 5 c) [1, 2, 3, (4, 5)]

29. What data structure is created by this code?


mydata = {(1, 2): "pair", 3: "odd"}

a) Set b) Tuple
c) Dictionary d) List

30. Which of the following best describes a set in Python?

a) Ordered, mutable, allows duplicates


b) Unordered, mutable, no duplicates
c) Ordered, immutable, no duplicates
d) Unordered, immutable, allows duplicates

31. What is the output?

count = 0
while count < 5:
if count == 3:
break
print(count)
count += 1

a) 0 1 2 3 4 b) 0 1 2
c) 1 2 3 d) 0 1 2 3

32. What is the result of this code?

nums = [2, 4, 6]
print(nums[::-1])

a) [2, 4, 6] b) [6, 4, 2]
c) Error d) [2, 6, 4]

33. What does the `pass` statement do in Python?

a) Skips current loop b)Terminates the loop


c) Placeholder for future code d)Ignores errors

34. Which statement correctly tests if a key exists in a dictionary?

a) key in dict.keys() b) dict.has_key(key)


c) key in dict d) dict.contains(key)

35. What is the output?

for i in range(1, 4):


for j in range(i):
print("*", end="")
print()

a) *** b) * ** ***
c) *\n**\n*** d) Error

36. What is the result of tuple("abc")?

a) ('abc') b) ['a', 'b', 'c']


c) ('a', 'b', 'c') d) ('a,b,c')

37. What is the purpose of enumerate()?

a) Sorts items in a list b) Finds the index of items


c) Adds an index while iterating d) Converts strings to integers

38. What is the output of this code?

mylist = [10, 20, 30]


print(mylist[1:])

a) [10, 20, 30] b) [20, 30]


c) [10, 20] d) 30

39. Which of the following methods adds all elements from one list to another?

a) list1.add(list2) b) list1.append(list2)
c) list1.extend(list2) d) list1.merge(list2)

40. What is the output of this code?

for i in range(3):
for j in range(2):
print(i + j, end=" ")

a) 0 1 1 2 2 3 b) 0 1 2 3 4 5
c) 1 2 3 4 5 6 d) 0 1 1 2 2 3

SHORT ANSWER PRACTICE QUESTIONS


6. Write a Python program that accepts a number from the user and checks whether it is a prime number or not.
7. Consider the list:
nums = [3, 6, 9, 12]
Write code to:
a) Add number 15 to the list.
b) Replace 9 with 0.
c) Print the length of the list.

8. Write a Python function called, is_even(num), that returns True if the number is even, else returns False.
Then write a loop that prints whether each number from 1 to 10 is even or not.

9. Given the following dictionary:


student = {
"name": "John",
"age": 22,
"department": "CS"
}
a) Add a key "year" with value 2025.
b) Update "age" to 23.
c) Print all the keys in the dictionary.

10. Write a Python program that accepts a string and prints the number of vowels in the string.

1.A microsoft word document has a file name extension as .doc, .txt or .docx.
What is the file name extension for a Python file?

2.Study the arithmetic expression below and answer the questions that follow.
9*35+10−8
What is the result to the expression above?
How many operands and how many arithmetic operators does the expression have?

3. How many binary operators are there in the following arithmetic expression?
-7+57/(49+101)

4.Give an example of each of the following types of operators in Python


i)Identity operators
ii) Comparison operators
iii) Membership operators

5.Which of the following best describes an identifier in Python?


a) An identifier is machine dependent
b) An identifier is a Keyword
c) An identifier is case sensitive
d) An identifier is constant
6. What is the maximum length of an identifier in Python?

7.What will be the output


for the following

(i)

class_president = Blessings’
print(class_president [0:5])

(ii)
class_president =‘Blessings’
print(class_president [0::2])

(iii.) class_president =
‘Blessings’
print(class_president [::-1])

(iv) print('learning'
'python')

You might also like