Exam practice
Every question from the end of every unit, with hints and answers to open. After you check an answer, mark how you did, and come back to the ones you didn’t get.
59 questions
Unit 7 · Concept of Programming
1. Answer these questions
Explain programming languages with their types.
Answer
A programming language is a language, with its own words and rules (syntax), used to write instructions that tell a computer what to do and how to do it. Programs, from operating systems to apps and games, are written in programming languages such as Python, Java and C. There are two main types:
- Low-level languages are close to the machine. Machine language is written in 0s and 1s, which the processor understands directly; assembly language uses short codes such as
ADDandMOV, translated by an assembler. They run fast but are hard to write, read and correct, and each works only on one kind of processor. - High-level languages are close to human language and maths, such as Python, Java, C, C++ and JavaScript. They are easy to learn, write, read and debug, and run on different computers, but must be translated into machine code by a compiler or an interpreter before they run.
Differentiate between compiler and interpreter.
Answer
| Compiler | Interpreter |
|---|---|
| translates the whole program into machine code at once | translates and runs the program line by line |
| shows the errors it finds together, after reading the whole program; nothing runs until they are fixed | stops at the first error it meets, while running |
| the compiled program runs faster | the program runs slower |
| makes a separate machine-code (executable) file | makes no separate file |
| e.g. GCC (for C and C++) | e.g. the Python interpreter |
Define algorithm and flowchart.
Answer
An algorithm is a set of step-by-step instructions, written in simple language, for solving a particular problem or doing a particular task. It begins with Start and ends with Stop, and each step is clear and in order.
A flowchart is the pictorial (graphical) representation of an algorithm: its steps drawn with standard shapes (oval, parallelogram, rectangle, diamond…) joined by arrows that show the order and direction of flow.
Write five symbols used in a flowchart, with their functions.
Answer
| Symbol | Name | Function |
|---|---|---|
| oval (rounded rectangle) | terminal | marks the Start and Stop of a flowchart |
| parallelogram | input/output | reads input or displays output |
| rectangle | process | a calculation or processing step |
| diamond | decision | checks a condition; two ways out, Yes and No |
| arrow | flow line | shows the direction of flow, which step comes next |
| small circle | connector | joins parts of a flowchart |
(Any five of these.)
Create an algorithm to find whether a given number is odd or even. Also make a flowchart from the algorithm.
Answer
Algorithm:
Step 1: StartStep 2: Read a number nStep 3: Is n % 2 == 0? (Is the remainder of n ÷ 2 equal to 0?) If Yes: display "Even" If No: display "Odd"Step 4: StopFlowchart:
Explain Python programming with its features.
Answer
Python is a high-level, general-purpose programming language created by Guido van Rossum and first released in 1991. It is interpreted, free and open source, and is used in web development, data science, artificial intelligence, automation, game development and cyber security. Its code uses indentation instead of braces, which makes it neat and readable. Its features:
- Easy to read and write: simple syntax close to English.
- Beginner-friendly: short programs do useful things, so it is a good first language.
- Versatile: suits small scripts as well as big web, data and AI projects.
- Extensive standard library: ready-made code for maths, dates, files and much more.
- Rich ecosystem: many free libraries and frameworks made by its community.
- Free, open source and portable: runs on Windows, macOS and Linux.
Describe the use of input/output statements in Python.
Answer
Input/output (I/O) statements let a program interact with its user.
- input() reads data from the user: it shows a prompt, waits for the user to type and press Enter, and gives back what was typed, as a string. For numbers it is used with
int()orfloat():age = int(input("Enter your age: ")). - print() displays output on the screen: text, numbers, variables and results, several at once separated by commas:
print("Your age is", age).
So input() brings data into the program and print() shows the results.
Define formatted string literals. Demonstrate their use in a simple program where the user inputs their name and the output is displayed as “Hello (user_name)! Welcome to our program”.
Answer
Formatted string literals (f-strings) are strings with an f before the opening quote, inside which variables or expressions are written in curly braces { }; Python puts each one’s value in its place. They are the newest and most used way of formatting strings in Python.
user_name = input("Enter your name: ")print(f"Hello {user_name}! Welcome to our program")Output
Enter your name: SonamHello Sonam! Welcome to our programExplain the data types with examples.
Answer
A data type is the kind of a value, which decides what can be done with it. Python’s basic data types:
- Integer (int): whole numbers, positive, negative or zero:
age = 15,-3,0. - Float (float): numbers with a decimal point:
height = 5.7,3.14,-0.5. - String (str): text in quotes, letters, digits and symbols:
name = "Sanjog","Python@". - Boolean (bool): only
TrueorFalse:is_student = True.
Python also has collection types, such as the list ([10, 20, 30]) and the dictionary ({"name": "Sanjog"}).
Describe typecasting with its types.
Answer
Type casting is converting a value from one data type to another, for example the string "25" from input() into the integer 25. It is of two types:
- Implicit type casting (automatic): Python converts by itself when an expression needs it, so no data is lost. In
z = 10 + 5.5, the integer 10 is converted to a float andzis 15.5. - Explicit type casting: the programmer converts on purpose with
int(),float()orstr():int(4.5)gives 4,float(4)gives 4.0,str(11)gives"11", andint(input("Enter a number: "))makes the user’s input a number.
List the types of operators. Explain any one of them in detail with examples.
Answer
Python’s main types of operators are arithmetic, relational (comparison), logical and assignment operators.
Arithmetic operators do mathematical calculations:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
addition | 5 + 3 |
8 |
- |
subtraction | 7 - 2 |
5 |
* |
multiplication | 4 * 6 |
24 |
/ |
division | 10 / 4 |
2.5 |
// |
floor division | 10 // 4 |
2 |
% |
modulus (remainder) | 10 % 4 |
2 |
** |
exponent | 3 ** 2 |
9 |
For example, print(17 % 5) prints 2, the remainder of 17 ÷ 5, and n % 2 == 0 checks whether n is even.
(Any one type, explained with examples, earns the marks; relational operators compare two values and give True or False, logical operators and, or, not combine conditions, and assignment operators such as = and += store values.)
Explain a conditional statement with an example.
Answer
A conditional statement is a decision-making statement: it checks a condition and runs a block of code only if the condition is True, so the program chooses what to do. Python’s conditional statements are if, if-else, if-elif-else and nested if. The block under each is indented.
For example, an if-else statement:
marks = int(input("Enter your marks: "))if marks >= 40: print("You passed.")else: print("You failed.")Output
Enter your marks: 58You passed.If the condition marks >= 40 is True, the if block runs; otherwise the else block runs.
Define iteration. Differentiate between the for loop and the while loop.
Answer
Iteration is the process of repeating a set of instructions again and again, a given number of times or until a condition is met. It is done with loops; Python has the for loop and the while loop.
| for loop | while loop |
|---|---|
| used when the number of repetitions is known | used when the number of repetitions is not known in advance |
| repeats once for each item of a sequence (a range, a list, a string) | repeats as long as its condition is True |
| the loop variable is set and changed by the loop itself | the variable is set before the loop and changed inside it |
| ends by itself when the sequence is finished | runs for ever if its condition never becomes False |
e.g. for i in range(5): |
e.g. while count <= 5: |
Differentiate between list and dictionary.
Answer
| List | Dictionary |
|---|---|
| stores elements in a sequence | stores data in key:value pairs |
written in square brackets [ ] |
written in curly braces { } |
| elements are accessed by index (from 0) | values are accessed by key |
| elements have positions, and may repeat | keys are unique (a repeated key replaces the old value) |
added with append(), removed by index with del |
added as d[key] = value, removed by key with del |
Here are the elements of a list:
[Kathmandu, Biratnagar, Nepalgunj, Pokhara, Butwal, Birendranagar, Mahendranagar, Balefi]
- a.Add the list item Malangawa.
- b.Remove the list item Balefi.
- c.Print the list items one by one using a loop.
Answer
cities = ["Kathmandu", "Biratnagar", "Nepalgunj", "Pokhara", "Butwal", "Birendranagar", "Mahendranagar", "Balefi"]cities.append("Malangawa") # a. add Malangawa at the enddel cities[7] # b. remove Balefi, the element at index 7for city in cities: # c. print the items one by one print(city)Output
KathmanduBiratnagarNepalgunjPokharaButwalBirendranagarMahendranagarMalangawaThe city names are strings, so they need quotes. Balefi is the eighth element, at index 7. cities.remove("Balefi") would also work: it removes an element by its value.
2. Write the technical terms
- a.A set of instructions to perform a specific task.
- b.The set of rules for writing a program.
- c.A language translator that reads and translates program code into machine code line by line.
- d.The graphical or pictorial representation of a program’s steps.
- e.Text added to source code to give information or an explanation, which the Python interpreter ignores.
- f.A data type that has only the values True and False.
- g.A special symbol used to check the relationship between two variables.
- h.The values or entities that operators act on in programming.
- i.A decision-making control structure that helps a program choose what to do.
- j.The process of repeating a task until a specified condition is met.
Answer
- a.program
- b.syntax
- c.interpreter
- d.flowchart
- e.comment
- f.Boolean (bool)
- g.relational (comparison) operator
- h.operands
- i.conditional statement
- j.iteration (a loop)
4. Write the full forms
- i.LLL
- ii.HLL
- iii.I/O
- iv.IDE
Answer
- i.LLL: Low-Level Language
- ii.HLL: High-Level Language
- iii.I/O: Input/Output
- iv.IDE: Integrated Development Environment
Input and output
Write a program that asks the user for their name and greets them by name.
Answer
name = input("What is your name? ")print(f"Namaste, {name}! Nice to meet you.")Output
What is your name? AakritiNamaste, Aakriti! Nice to meet you.Write a program that reads the three sides of a triangle and prints its area.
Answer
With sides a, b and c, Heron’s formula gives the area: first the half-perimeter s = (a + b + c) ÷ 2, then area = √(s(s − a)(s − b)(s − c)).
import matha = float(input("Enter side a: "))b = float(input("Enter side b: "))c = float(input("Enter side c: "))s = (a + b + c) / 2area = math.sqrt(s * (s - a) * (s - b) * (s - c))print("The area of the triangle is", area)Output
Enter side a: 3Enter side b: 4Enter side c: 5The area of the triangle is 6.0Check: a 3-4-5 triangle has a right angle, so its area is ½ × 3 × 4 = 6. (The three sides must be able to make a triangle: each less than the other two added together.)
Write a program that reads a radius and prints the area and the circumference of the circle.
Answer
radius = float(input("Enter the radius: "))area = 3.14159 * radius ** 2circumference = 2 * 3.14159 * radiusprint("Area:", round(area, 2))print("Circumference:", round(circumference, 2))Output
Enter the radius: 7Area: 153.94Circumference: 43.98Area = πr², circumference = 2πr. round(…, 2) keeps two decimal places.
Write a program that reads three integers and prints their sum and average.
Answer
n1 = int(input("Enter the first number: "))n2 = int(input("Enter the second number: "))n3 = int(input("Enter the third number: "))total = n1 + n2 + n3average = total / 3print("Sum:", total)print("Average:", round(average, 2))Output
Enter the first number: 10Enter the second number: 20Enter the third number: 35Sum: 65Average: 21.67Write a program that reads the diameter of a circle and prints its area and circumference.
Answer
diameter = float(input("Enter the diameter: "))radius = diameter / 2area = 3.14159 * radius ** 2circumference = 3.14159 * diameterprint("Area:", round(area, 2))print("Circumference:", round(circumference, 2))Output
Enter the diameter: 14Area: 153.94Circumference: 43.98The radius is half the diameter, and the circumference is π × diameter.
Constant values and operators
Write a program that reads a radius and finds the area and the circumference of the circle, keeping π as a constant.
Answer
A constant is a value that doesn’t change while the program runs. Python has no special keyword for it; by custom, a constant’s name is written in capitals.
PI = 3.14159 # a constantradius = float(input("Enter the radius: "))print("Area:", round(PI * radius * radius, 2))print("Circumference:", round(2 * PI * radius, 2))Output
Enter the radius: 3.5Area: 38.48Circumference: 21.99(Python’s math.pi is π to 15 decimal places: import math, then math.pi.)
Write a program to show the use of arithmetic operators: add, subtract, multiply, divide, square and find the remainder (modulus) of two numbers.
Answer
a = int(input("Enter the first number: "))b = int(input("Enter the second number: "))print("Sum:", a + b)print("Difference:", a - b)print("Product:", a * b)print("Quotient:", a / b)print("Square of the first:", a ** 2)print("Square of the second:", b ** 2)print("Remainder:", a % b)Output
Enter the first number: 17Enter the second number: 5Sum: 22Difference: 12Product: 85Quotient: 3.4Square of the first: 289Square of the second: 25Remainder: 2Write a program to show the use of comparison operators between two variables, with ==, <=, >= and !=.
Answer
x = 12y = 20print("x == y:", x == y)print("x <= y:", x <= y)print("x >= y:", x >= y)print("x != y:", x != y)Output
x == y: Falsex <= y: Truex >= y: Falsex != y: TrueEach comparison gives a Boolean, True or False.
if…else statements
Write a program that uses an if statement to check whether a given number is positive.
Answer
number = float(input("Enter a number: "))if number > 0: print("The number is positive.")Output
Enter a number: 42The number is positive.Write a program that takes a person’s age as input and checks whether they are eligible to vote. (The voting age is 18 and above.)
Answer
age = int(input("Enter your age: "))if age >= 18: print("You are eligible to vote.")else: print("You are not eligible to vote yet.")Output
Enter your age: 19You are eligible to vote.Write a program to check whether a given number is even or odd, using an if-else statement.
Answer
number = int(input("Enter a number: "))if number % 2 == 0: print(number, "is even.")else: print(number, "is odd.")Output
Enter a number: 3636 is even.Write a program that reads two numbers and finds the smaller.
Answer
a = float(input("Enter the first number: "))b = float(input("Enter the second number: "))if a < b: print("The smaller number is", a)else: print("The smaller number is", b)Output
Enter the first number: 8.5Enter the second number: 3The smaller number is 3.0If the two are equal, the else prints b, which is equally right.
Write a program that takes a student’s marks as input and says whether the student passed or failed. (40 or more is a pass.)
Answer
marks = float(input("Enter the marks: "))if marks >= 40: print("Passed")else: print("Failed")Output
Enter the marks: 39FailedWrite a program that takes three numbers as input and displays the smallest.
Answer
a = float(input("Enter the first number: "))b = float(input("Enter the second number: "))c = float(input("Enter the third number: "))if a <= b and a <= c: smallest = aelif b <= a and b <= c: smallest = belse: smallest = cprint("The smallest number is", smallest)Output
Enter the first number: 14Enter the second number: 6Enter the third number: 9The smallest number is 6.0(min(a, b, c) does the same in one line.)
Make a program like a traffic light, using an if-elif-else statement. Ask the user for a color: green means “Go”, red means “Stop”, orange means “Be ready”, and any other color is “Invalid color”.
Answer
color = input("Enter the color of the light: ").lower()if color == "green": print("Go")elif color == "red": print("Stop")elif color == "orange": print("Be ready")else: print("Invalid color")Output
Enter the color of the light: OrangeBe ready.lower() turns what the user typed into small letters, so Orange, ORANGE and orange all match "orange".
Write a program that reads the practical and the theory marks of Computer and says whether the student passed or failed. Also check that the user has entered valid marks, for both theory and practical.
Answer
Take, as an example, theory out of 50 and practical out of 50, with a pass at 40% of each: 20 marks. (Change the numbers to your school’s.) A student must pass both.
theory = float(input("Enter the theory marks (out of 50): "))practical = float(input("Enter the practical marks (out of 50): "))if theory < 0 or theory > 50 or practical < 0 or practical > 50: print("Invalid marks: each must be from 0 to 50.")elif theory >= 20 and practical >= 20: print("Pass")else: print("Fail")Output
Enter the theory marks (out of 50): 34Enter the practical marks (out of 50): 42PassThe validity check comes first: marks such as 65 or −3 are reported as invalid, not judged pass or fail. Try 18 and 45: the student fails, because the theory is below 20.
for loops
Write a program to print the numbers from 1 to 15.
Answer
for n in range(1, 16): print(n)Output
123456789101112131415Write a program that reads a name and prints it 20 times.
Answer
name = input("Enter a name: ")for i in range(20): print(name)Output
Enter a name: PasangPasangPasangPasangPasangPasangPasangPasangPasangPasangPasangPasangPasangPasangPasangPasangPasangPasangPasangPasangPasangrange(20) gives 20 numbers (0 to 19), so the loop runs 20 times.
Write a program to print the squares of the numbers from 1 to 5 using a for loop.
Answer
for n in range(1, 6): print("The square of", n, "is", n ** 2)Output
The square of 1 is 1The square of 2 is 4The square of 3 is 9The square of 4 is 16The square of 5 is 25Write a program to print the first 20 odd numbers.
Answer
for n in range(1, 40, 2): print(n)Output
13579111315171921232527293133353739Odd numbers go up in twos from 1; the 20th is 2 × 20 − 1 = 39, so the range stops before 40.
Write a program that takes an integer as input and prints its multiplication table.
Answer
n = int(input("Enter a number: "))for i in range(1, 11): print(n, "x", i, "=", n * i)Output
Enter a number: 77 x 1 = 77 x 2 = 147 x 3 = 217 x 4 = 287 x 5 = 357 x 6 = 427 x 7 = 497 x 8 = 567 x 9 = 637 x 10 = 70while loops
Write a program to print the numbers from 1 to 20 using a while loop.
Answer
n = 1while n <= 20: print(n) n += 1Output
1234567891011121314151617181920Write a program to print the first 30 even numbers using a while loop.
Answer
count = 1while count <= 30: print(count * 2) count += 1Output
24681012141618202224262830323436384042444648505254565860The counter counts the even numbers printed (1 to 30), and each one is twice the counter.
Write a program to calculate the factorial of a given number using a while loop.
Answer
n = int(input("Enter a number: "))factorial = 1i = 1while i <= n: factorial *= i i += 1print("The factorial of", n, "is", factorial)Output
Enter a number: 6The factorial of 6 is 7206! = 1 × 2 × 3 × 4 × 5 × 6 = 720. For 0 the loop doesn’t run at all and the answer is 1, which is right: 0! = 1.
Write a program to print the sum of the first 20 odd numbers using a while loop.
Answer
total = 0count = 0odd = 1while count < 20: total += odd odd += 2 count += 1print("The sum of the first 20 odd numbers is", total)Output
The sum of the first 20 odd numbers is 400A neat check: the sum of the first n odd numbers is always n²: 1 + 3 = 4, 1 + 3 + 5 = 9… and 20² = 400.
Write a program that reads a number with several digits and displays the sum of its digits.
Answer
number = int(input("Enter a number: "))total = 0while number > 0: total += number % 10 number //= 10print("The sum of the digits is", total)Output
Enter a number: 4096The sum of the digits is 194 + 0 + 9 + 6 = 19. % 10 takes the last digit and //= 10 removes it, as in practice tasks 27 and 28.
Lists
Write a Python program to create a list of 5 integers and print the list.
Answer
numbers = [12, 7, 45, 3, 28]print(numbers)Output
[12, 7, 45, 3, 28]Write a Python program to print the second and fourth elements of a list.
Answer
rivers = ["Koshi", "Gandaki", "Karnali", "Mahakali", "Bagmati"]print("Second:", rivers[1])print("Fourth:", rivers[3])Output
Second: GandakiFourth: MahakaliIndexes start at 0, so the second element is at index 1 and the fourth at index 3.
Write a Python program to append a new element to the end of a list and print the updated list.
Answer
rivers = ["Koshi", "Gandaki", "Karnali"]rivers.append("Mahakali")print(rivers)Output
['Koshi', 'Gandaki', 'Karnali', 'Mahakali']Write a Python program to print the first three elements of a list using slicing.
Answer
Slicing takes a part of a list: list[start:stop] gives the elements from index start up to, but not including, index stop, just as range() stops before its end.
peaks = ["Everest", "Kangchenjunga", "Lhotse", "Makalu", "Cho Oyu"]print(peaks[0:3])Output
['Everest', 'Kangchenjunga', 'Lhotse']peaks[:3] means the same: a missing start is 0.
Write a Python program to print the length of a list.
Answer
peaks = ["Everest", "Kangchenjunga", "Lhotse", "Makalu", "Cho Oyu"]print("Length of the list:", len(peaks))Output
Length of the list: 5Write a Python program to go through a list and print each element.
Answer
peaks = ["Everest", "Kangchenjunga", "Lhotse", "Makalu", "Cho Oyu"]for peak in peaks: print(peak)Output
EverestKangchenjungaLhotseMakaluCho OyuWrite a Python program to create a list of the squares of the numbers from 1 to 10 using a list comprehension.
Answer
A list comprehension builds a list in one line, from a for loop written inside the square brackets: [expression for item in sequence].
squares = [n ** 2 for n in range(1, 11)]print(squares)Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]It does the same as this longer loop:
squares = []for n in range(1, 11): squares.append(n ** 2)print(squares)Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]Write a Python program to remove the third element from a list and print the updated list.
Answer
fruits = ["apple", "banana", "orange", "grapes", "mango"]del fruits[2] # the third element is at index 2print(fruits)Output
['apple', 'banana', 'grapes', 'mango']Dictionaries
Write a Python program to create a dictionary with 3 key:value pairs and print it.
Answer
capitals = {"Koshi": "Biratnagar", "Gandaki": "Pokhara", "Karnali": "Birendranagar"}print(capitals)Output
{'Koshi': 'Biratnagar', 'Gandaki': 'Pokhara', 'Karnali': 'Birendranagar'}The keys are three of Nepal’s provinces, and the values their capitals.
Write a Python program to print the value of a particular key in a dictionary.
Answer
capitals = {"Koshi": "Biratnagar", "Gandaki": "Pokhara", "Karnali": "Birendranagar"}print("The capital of Gandaki is", capitals["Gandaki"])Output
The capital of Gandaki is PokharaWrite a Python program to add a new key:value pair to a dictionary and print the updated dictionary.
Answer
capitals = {"Koshi": "Biratnagar", "Gandaki": "Pokhara", "Karnali": "Birendranagar"}capitals["Madhesh"] = "Janakpur"print(capitals)Output
{'Koshi': 'Biratnagar', 'Gandaki': 'Pokhara', 'Karnali': 'Birendranagar', 'Madhesh': 'Janakpur'}Write a Python program to remove a key:value pair from a dictionary using the del statement and print the updated dictionary.
Answer
capitals = {"Koshi": "Biratnagar", "Gandaki": "Pokhara", "Karnali": "Birendranagar"}del capitals["Karnali"]print(capitals)Output
{'Koshi': 'Biratnagar', 'Gandaki': 'Pokhara'}Write a Python program to go through a dictionary and print all its keys.
Answer
capitals = {"Koshi": "Biratnagar", "Gandaki": "Pokhara", "Karnali": "Birendranagar"}for province in capitals: print(province)Output
KoshiGandakiKarnaliWrite a Python program to create a dictionary whose keys are the numbers 1 to 5 and whose values are their squares, using a dictionary comprehension.
Answer
A dictionary comprehension is like a list comprehension, in curly braces, with a key and a value: {key: value for item in sequence}.
squares = {n: n ** 2 for n in range(1, 6)}print(squares)Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}Write a Python program to check whether a particular key exists in a dictionary.
Answer
The in operator checks whether a key is in a dictionary, and gives True or False.
capitals = {"Koshi": "Biratnagar", "Gandaki": "Pokhara", "Karnali": "Birendranagar"}key = input("Enter a province: ")if key in capitals: print(key, "is in the dictionary. Its capital is", capitals[key])else: print(key, "is not in the dictionary.")Output
Enter a province: BagmatiBagmati is not in the dictionary.Write a Python program to merge two dictionaries and print the result.
Answer
fees = {"Grade 9": 1500, "Grade 10": 1800}more_fees = {"Grade 11": 2500, "Grade 12": 2800}merged = fees.copy() # a copy, so fees itself stays as it wasmerged.update(more_fees) # add every pair of more_feesprint(merged)Output
{'Grade 9': 1500, 'Grade 10': 1800, 'Grade 11': 2500, 'Grade 12': 2800}update() adds the second dictionary’s pairs to the first; a key in both takes the second’s value. In Python 3.9 and later, merged = fees | more_fees does the same in one step.
