0% found this document useful (0 votes)
84 views18 pages

Ch-03: Programming Fundamentals

Unit 3: Programming Fundamentals of Class 12 (Federal Board) introduces students to the basic concepts and principles of computer programming. This unit helps learners understand how programs are written, executed, and used to solve real-world problems. It explains key programming concepts such as syntax, semantics, variables, data types, operators, and expressions, providing a foundation for developing logical and structured code. Students learn about the structure of a program, including input, processing, and output statements, as well as the use of control structures like sequence, selection, and iteration to manage program flow. The unit also introduces the concept of modular programming through the use of functions or procedures, which enhance program readability and reusability. Emphasis is placed on writing clear, efficient, and error-free code by understanding debugging and testing techniques. By the end of this unit, students are equipped with the essential skills and logical thinking required to write simple programs and prepare for more advanced programming concepts in future studies.

Uploaded by

shahzad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
0% found this document useful (0 votes)
84 views18 pages

Ch-03: Programming Fundamentals

Unit 3: Programming Fundamentals of Class 12 (Federal Board) introduces students to the basic concepts and principles of computer programming. This unit helps learners understand how programs are written, executed, and used to solve real-world problems. It explains key programming concepts such as syntax, semantics, variables, data types, operators, and expressions, providing a foundation for developing logical and structured code. Students learn about the structure of a program, including input, processing, and output statements, as well as the use of control structures like sequence, selection, and iteration to manage program flow. The unit also introduces the concept of modular programming through the use of functions or procedures, which enhance program readability and reusability. Emphasis is placed on writing clear, efficient, and error-free code by understanding debugging and testing techniques. By the end of this unit, students are equipped with the essential skills and logical thinking required to write simple programs and prepare for more advanced programming concepts in future studies.

Uploaded by

shahzad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
You are on page 1/ 18

Computer Science Federal Board Class-12

Chapter
Programming
03 Fundamentals
SHORT QUESTION AND ANSWERS
1. What is a programming paradigm?
Ans: A programming paradigm is a fundamental style or approach to building the
structure and elements of computer programs. It's a way of classifying
programming languages based on their features and how they solve
problems.
2. Name some common programming paradigms.
Ans: Some common programming paradigms include:
 Imperative
 Declarative
 Object-Oriented
 Functional
 Logic
3. What is the core idea behind the Imperative Paradigm?
Ans: The imperative paradigm focuses on how a program operates, explicitly
detailing the steps (statements, commands) that change the program's state.
It's like providing a recipe with precise instructions.
4. What is the core idea behind the Declarative Paradigm?
Ans: The declarative paradigm focuses on what the program should accomplish,
without specifying the exact control flow or steps. It's about describing the
desired result, and the system figures out how to achieve it.
5. Briefly explain Object-Oriented Programming (OOP).
Ans: OOP is a paradigm based on the concept of "objects," which can contain data
(attributes) and code (methods) that operate on that data. It emphasizes
concepts like encapsulation, inheritance, and polymorphism.
6. What is the key characteristic of Functional Programming?
Ans: Functional programming treats computation as the evaluation of
mathematical functions and avoids changing state and mutable data. It
emphasizes pure functions, immutability, and recursion.

1|Page
Computer Science Federal Board Class-12

2|Page
Computer Science Federal Board Class-12

7. How does the Logic Programming Paradigm approach problem-solving?


Ans: Logic programming expresses programs in terms of facts and rules, and then
uses a logical inference engine to find solutions. It's often used for artificial
intelligence and expert systems.
8. Can a programming language support multiple paradigms? Give an example.
Ans: Yes, many modern programming languages are multi-paradigm, meaning they
support features from several paradigms. Python is a good example,
supporting imperative, object-oriented, and functional styles.
9. What is the main benefit of understanding different programming
paradigms?
Ans: Understanding different paradigms allows programmers to choose the most
appropriate approach for a given problem, write more efficient and
maintainable code, and better understand the design principles behind
various languages and systems.
10. What is the difference between a programming paradigm and a
programming language?
Ans: A programming paradigm is a style or methodology of programming, while a
programming language is a tool or notation used to implement programs,
which often adheres to one or more paradigms.
11. What is Functional Programming (FP)?
Ans: Functional Programming is a programming paradigm that treats computation
as the evaluation of mathematical functions and avoids changing state and
mutable data. It emphasizes applying functions, immutability, and recursion.
12. What is a "pure function" in FP?
Ans: A pure function is a function that, given the same inputs, will always return
the same output, and has no side effects (it doesn't modify any external state
or have observable interactions with the outside world beyond returning a
value).
13. What are "side effects" in the context of FP, and why are they avoided?
Ans: Side effects are any observable changes to the program's state that occur
outside the return value of a function (e.g., modifying a global variable,
printing to console, writing to a file). They are avoided in FP because they

3|Page
Computer Science Federal Board Class-12

make programs harder to reason about, test, and parallelize.


14. What is "immutability" in FP?
Ans: Immutability means that once data is created, it cannot be changed. Instead
of modifying existing data, FP operations create new data structures with the
desired changes. This helps prevent side effects and makes programs more
predictable.
15. What is "first-class functions"?
Ans: First-class functions means that functions are treated like any other variable:
they can be passed as arguments to other functions, returned from functions,
and assigned to variables.
16. What is a "higher-order function"?
Ans: A higher-order function is a function that either takes one or more functions
as arguments, or returns a function as its result (or both). Examples include
map, filter, and reduce.
17. Briefly explain "referential transparency."
Ans: Referential transparency means that an expression can be replaced with its
corresponding value without changing the program's behavior. Pure functions
inherently provide referential transparency.
18. What is "recursion" in FP, and why is it often used?
Ans: Recursion is a technique where a function calls itself to solve smaller
instances of the same problem. It's often used in FP instead of loops because
it aligns with immutability and the absence of mutable state.
19. Name some benefits of using Functional Programming.
Ans: Benefits include easier testing (due to pure functions), better
concurrency/parallelism, improved code readability and maintainability, and
reduced bugs (due to immutability and lack of side effects).
20. Give an example of a language that strongly supports Functional
Programming.
Ans: Haskell is a classic example of a purely functional programming language.
Other languages like JavaScript, Python, and Scala also have strong support
for functional programming concepts.

4|Page
Computer Science Federal Board Class-12

21. What is Object-Oriented Programming (OOP)?


Ans: OOP is a programming paradigm based on the concept of "objects," which are
instances of "classes" and can contain both data (attributes/properties) and
code (methods/behaviors) that operate on that data.
22. What is a "class" in OOP?
Ans: A class is a blueprint or a template for creating objects. It defines the
structure (attributes) and behavior (methods) that all objects of that class will
possess.
23. What is an "object" in OOP?
Ans: An object is an instance of a class. It's a concrete entity created from the class
blueprint, with its own unique set of attribute values.
24. What are the four main pillars (or principles) of OOP?
Ans: The four main pillars are:
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction
25. Briefly explain Encapsulation.
Ans: Encapsulation is the bundling of data (attributes) and methods (behaviors)
that operate on the data into a single unit (the object), and restricting direct
access to some of an object's components (data hiding). It's about protecting
data and providing controlled access.
26. Briefly explain Inheritance.
Ans: Inheritance is a mechanism where a new class (subclass/derived class) can
inherit properties and behaviors from an existing class (superclass/base class).
It promotes code reusability and establishes an "is-a" relationship.
27. Briefly explain Polymorphism.
Ans: Polymorphism (meaning "many forms") allows objects of different classes to
be treated as objects of a common type. It enables a single interface to
represent different underlying forms or types, typically achieved through
method overriding or overloading.

5|Page
Computer Science Federal Board Class-12

28. Briefly explain Abstraction.


Ans: Abstraction is the process of hiding complex implementation details and
showing only the essential features of an object. It focuses on "what" an
object does rather than "how" it does it, providing a simplified view.
29. What is "method overriding"?
Ans: Method overriding occurs when a subclass provides its own specific
implementation for a method that is already defined in its superclass. The
method name, return type, and parameters must be the same.
30. What is "method overloading"?
Ans: Method overloading occurs when a class has multiple methods with the same
name but different parameters (different number or types of arguments). This
allows methods to perform similar operations on different types of data.
31. Name some popular programming languages that are object-oriented.
Ans: Popular OOP languages include Java, C++, Python, C#, Ruby, and Smalltalk.
32. What is a "variable" in Python?
Ans: A variable is a named storage location that holds a value. In Python, you don't
declare a variable's type explicitly; its type is inferred from the value assigned
to it.
33. How do you define a "comment" in Python?
Ans: Comments in Python start with a hash symbol (#) and continue to the end of
the line. Multi-line comments can be created using triple quotes
("""Docstrings""" or '''comments''').
34. What is an "expression" in Python?
Ans: An expression is a combination of values, variables, operators, and function
calls that Python can evaluate to produce a result. Examples: a + b,
len(my_list), 5 2.
35. What is a "statement" in Python?
Ans: A statement is a logical instruction that Python can execute. Examples include
assignment statements (x = 10), if statements, for loops, and function
definitions.

6|Page
Computer Science Federal Board Class-12

36. How do you write an "if-else" statement in Python?


Ans: python
if condition:
# code to execute if condition is True
else:
# code to execute if condition is False
37. What is an "elif" clause used for?
Ans: elif (short for "else if") is used in an if statement to check multiple
conditions sequentially. If the preceding if or elif conditions are `False`, it
checks the elif condition.
38. How do you create a "for loop" in Python?
Ans: A for`loop iterates over the items of any sequence (like a list, tuple, string,
or range) or other iterable objects.

python
for item in iterable:
# code to execute for each item
39. What is a "while loop" in Python?
Ans: A while loop repeatedly executes a block of code as long as a given
condition is True.

python
while condition:
# code to execute while condition is True
40. What is the purpose of the `break` statement?
Ans: The `break` statement is used to immediately terminate the current loop
(either `for` or `while`) and transfer control to the statement immediately
following the loop.
41. What is the purpose of the `continue` statement?
Ans: The continue statement is used to skip the rest of the current iteration of a
loop and move to the next iteration.

7|Page
Computer Science Federal Board Class-12

42. How do you define a "function" in Python?


Ans: Functions are defined using the `def` keyword, followed by the function
name, parentheses for parameters, and a colon.

def function_name(parameter1, parameter2):


# function body
return result
43. What is a "return" statement used for in a function?
Ans: The return statement is used to exit a function and optionally send a value
back to the caller. If no `return` statement is present, the function implicitly
returns None.
44. What is a "list" in Python?
Ans: A list is a mutable, ordered sequence of elements. Elements are enclosed in
square brackets `[]` and can be of different data types. Example: my_list =
[1, 'hello', 3.14].
45. What is a "tuple" in Python?
Ans: A tuple is an immutable, ordered sequence of elements. Elements are
enclosed in parentheses () and can be of different data types. Example:
my_tuple = (1, 'world', 2.71).
46. What is a "dictionary" in Python?
Ans: A dictionary is an unordered collection of key-value pairs. Keys must be
unique and immutable, while values can be of any type. Enclosed in curly
braces {}. Example: my_dict = {'name': 'Alice', 'age': 30}.
47. What is a Python List?
Ans: A Python List is an ordered, mutable (changeable) collection of items, where
items can be of different data types.
48. How do you create a List?
Ans: Lists are created using square brackets [], with items separated by commas.
Example: my_list = [1, 'apple', 3.14]

8|Page
Computer Science Federal Board Class-12

49. Are Lists mutable or immutable?


Ans: Lists are mutable, meaning you can add, remove, or change elements after
the list has been created.
50. How do you access elements in a List?
Ans: Elements are accessed by their index (position), starting from 0 for the first
element.
Example: my_list[0] would give 1.
51. Can a List contain duplicate elements?
Ans: Yes, Lists can contain duplicate elements.
52. What is a Python Tuple?
Ans: A Python Tuple is an ordered, immutable (unchangeable) collection of items,
where items can be of different data types.
53. How do you create a Tuple?
Ans: Tuples are created using parentheses (), with items separated by commas.
Example: my_tuple = (1, 'banana', 2.71)
54. Are Tuples mutable or immutable?
Ans: Tuples are immutable, meaning once created, you cannot add, remove, or
change its elements.
55. How do you access elements in a Tuple?
Ans: Elements are accessed by their index (position), similar to Lists.
Example: my_tuple[1] would give 'banana'.
56. When might you choose a Tuple over a List?
Ans: Tuples are often chosen for collections of items that should not change, for
functions that need to return multiple values, or as dictionary keys (since they
are immutable).
57. What is a Python Set?
Ans: A Python Set is an unordered collection of unique items. It does not allow
duplicate elements.

9|Page
Computer Science Federal Board Class-12

58. How do you create a Set?


Ans: Sets are created using curly braces {} or the set() constructor.
Example: my_set = {1, 2, 3} or my_set = set([1, 2, 3])
Note: An empty set must be created with `set()`, not `{}` which creates an
empty dictionary.
59. Are Sets ordered?
Ans: No, Sets are unordered, meaning elements do not have a defined index or
position.
60. Can a Set contain duplicate elements?
Ans: No, Sets automatically remove duplicate elements.
61. What are common operations performed on Sets?
Ans: Common operations include union (|), intersection (&), difference (-), and
checking for membership (in).
62. What is a Python Dictionary?
Ans: A Python Dictionary is an unordered collection of key-value pairs, where each
key must be unique and immutable, and values can be of any data type.
63. How do you create a Dictionary?
Ans: Dictionaries are created using curly braces {} with key-value pairs separated
by colons `:`.
Example: my_dict = {'name': 'Alice', 'age': 30}
64. How do you access values in a Dictionary?
Ans: Values are accessed by their corresponding keys.
Example: my_dict['name'] would give 'Alice'.
65. Are Dictionaries mutable or immutable?
Ans: Dictionaries are mutable, meaning you can add, remove, or change key-value
pairs after creation.
66. What are the requirements for Dictionary keys?
Ans: Dictionary keys must be unique and immutable (e.g., strings, numbers,
tuples). Values, however, can be mutable and contain duplicates.

10 | P a g e
Computer Science Federal Board Class-12

67. Can a Python dictionary have a list as one of its values?


Ans: Yes, absolutely. A list can be a value associated with a key in a Python
dictionary.
68. How would you define a dictionary where a key maps to a list?
Ans: You simply assign a list literal or a list variable as the value for a given key.
Example: students = {'class_a': ['Alice', 'Bob',
'Charlie'], 'class_b': ['David', 'Eve']}
69. How do you access an element within a list that is a dictionary value?
Ans: First, access the list using its key, then use list indexing to access the element
within that list.
Example: students['class_a'][0] would return `'Alice'.
70. Can you modify a list that is a value in a dictionary?
Ans: Yes, since lists are mutable, you can modify a list even when it's stored as a
value in a dictionary.
Example: `students['class_a'].append('Frank')`
71. What is a common use case for having lists as dictionary values?
Ans: A common use case is when you need to group multiple related items under a
single identifier, such as storing a list of products for a customer, a list of
grades for a student, or a list of tasks for a project.
72. How do you open a file in Python?
Ans: You use the open() function, specifying the file path and the mode.
Example: `file = open('my_file.txt', 'r')`
73. What are the common modes for opening a file?
Ans: 'r': Read (default)
'w': Write (creates a new file or overwrites an existing one)
'a': Append (adds to the end of the file; creates if it doesn't exist)
'x': Exclusive creation (fails if file already exists)
'b': Binary mode (e.g., `'rb'`, `'wb'`)
't': Text mode (default)

11 | P a g e
Computer Science Federal Board Class-12

74. What is the best practice for ensuring a file is closed after use?
Ans: Use the `with` statement (context manager), which automatically handles
closing the file even if errors occur.
Example:
python
with open('my_file.txt', 'r') as file:
content = file.read()
75. How do you read the entire content of a text file?
Ans: Use the read() method after opening the file in read mode.
Example: content = file.read()
76. How do you read a text file line by line?
Ans: You can iterate directly over the file object in a `for` loop, or use the
`readline()` or `readlines()` methods.
Example (iteration):

```python
for line in file:
print(line.strip()) # .strip() removes newline
characters
77. How do you write content to a text file?
Ans: Open the file in `'w'` (write) or `'a'` (append) mode, then use the `write()`
method.
Example: file.write('Hello, world!\n')
78. What is the difference between `'w'` and `'a'` file modes?
Ans: 'w' (write) creates a new file if it doesn't exist, and truncates (clears)
the file if it already exists.
'a' (append) creates a new file if it doesn't exist, but if the file exists, it
adds new content to the end without clearing previous content.
79. What happens if you try to read from a file opened in `'w'` mode?
Ans: You will encounter an io.UnsupportedOperation error because 'w'
mode is for writing only and does not support reading.

12 | P a g e
Computer Science Federal Board Class-12

80. How do you handle file not found errors?


Ans: You can use a `try-except` block to catch the FileNotFoundError.
Example:

python
try:
with open('non_existent.txt', 'r') as file:
pass
except FileNotFoundError:
print("Error: File not found!")
81. What is a GUI in Python?
Ans: A GUI (Graphical User Interface) in Python refers to a visual way for users to
interact with a Python program, using elements like buttons, text fields,
labels, windows, and menus, instead of a command-line interface.
82. What are the most common Python libraries/toolkits for GUI development?
Ans: The most common Python GUI toolkits are:
Tkinter: Python's de-facto standard GUI library, included with most
Python installations.
PyQt: A set of Python bindings for the Qt application framework (very
powerful, widely used).
PyGTK/Gtk: Python bindings for the GTK+ toolkit.
Kivy: A library for developing multi-touch applications, often used for cross-
platform desktop and mobile apps.
wxPython: A wrapper for the wxWidgets C++ GUI library.
83. What is Tkinter?
Ans: Tkinter is Python's standard library for creating GUIs. It's a thin object-
oriented layer on top of Tcl/Tk, which is a popular open-source GUI toolkit.
84. What are "widgets" in GUI programming?
Ans: Widgets are the basic building blocks of a GUI. They are the visual
components that users interact with, such as buttons, labels, text entry fields,
scrollbars, checkboxes, radio buttons, and frames.

13 | P a g e
Computer Science Federal Board Class-12

85. How do you create the main window in a Tkinter application?


Ans: You create an instance of the `Tk` class.
Example: root = tk.Tk()
86. What is the purpose of the mainloop() (or run()) method in GUI
applications?
Ans: The mainloop() (in Tkinter) or app.exec_() (in PyQt) method starts the
event loop. This loop listens for user interactions (like mouse clicks, keyboard
presses) and updates the GUI accordingly, keeping the application running
until it's closed.
87. How do you add a button to a Tkinter window?
Ans: You create an instance of the tk.Button widget and then use a layout
manager (like pack(), grid(), or place()) to position it.
Example:

python
import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text="Click Me")
button.pack()
root.mainloop()
88. How do you make a button perform an action when clicked?
Ans: You associate a Python function with the button's `command` attribute.
Example:

python
def on_button_click():
print("Button clicked!")

button = tk.Button(root, text="Click Me",


command=on_button_click)

14 | P a g e
Computer Science Federal Board Class-12

89. What are "layout managers" in GUI development?


Ans: Layout managers are tools or methods used to arrange and position widgets
within a window or frame. Common Tkinter layout managers include `pack()`
(stacks widgets), `grid()` (arranges in rows and columns), and `place()`
(absolute positioning).
90. What is an "event" in GUI programming?
Ans: An event is an action or occurrence that the GUI application can respond to.
Examples include button clicks, key presses, mouse movements, window
resizing, or data changes
91. What is "event handling"?
Ans: Event handling is the process of detecting user actions (events) and executing
specific code (event handlers or callbacks) in response to those actions.
92. What is a Database?
Ans: A database is an organized collection of structured information, or data,
typically stored electronically in a computer system. It's designed for efficient
storage, retrieval, and management of data.
93. What is a Database Management System (DBMS)?
Ans: A DBMS is software that interacts with end-users, applications, and the
database itself to capture and analyze data. It manages the database,
allowing users to define, create, maintain, and control access to the database.
(e.g., MySQL, PostgreSQL, SQLite).
94. What is SQL?
Ans: SQL (Structured Query Language) is a standard language used to
communicate with and manipulate relational databases. It's used to query,
insert, update, and delete data, as well as to define database schemas.
95. What is a "table" in a relational database?
Ans: A table is a collection of related data organized in rows and columns. Each
column represents an attribute (e.g., "name", "age"), and each row
represents a single record or entry (e.g., one person's data).

15 | P a g e
Computer Science Federal Board Class-12

96. What is a "primary key"?


Ans: A primary key is a column or a set of columns in a table that uniquely
identifies each row (record) in that table. It ensures that each row can be
distinctly identified.
97. What is a "foreign key"?
Ans: A foreign key is a column or a set of columns in one table that refers to the
primary key in another table. It establishes a link or relationship between two
tables, enforcing referential integrity.
98. What is SQLite?
Ans: SQLite is a C-language library that implements a small, fast, self-contained,
high-reliability, full-featured, SQL database engine. It's unique in that it's
embedded directly into the application that uses it, meaning it doesn't
require a separate server process.
99. Why is SQLite often chosen for small applications or embedded systems?
Ans: It's chosen because it's lightweight, requires no separate server setup, stores
the entire database in a single file, and is very easy to integrate and use.
100. What Python module is used to interact with SQLite databases?
Ans: The sqlite3 module is the standard built-in Python module for working
with SQLite databases.
101. How do you connect to (or create) an SQLite database file in Python?
Ans: You use the sqlite3.connect() function, passing the filename as an
argument. If the file doesn't exist, SQLite will create it.
Example: conn = sqlite3.connect('my_database.db')
102. What is a "cursor" object in sqlite3?
Ans: A cursor object is used to execute SQL queries and fetch results from the
database. It acts as a control structure that enables traversal over the records
in a database.
Example: cursor = conn.cursor()

16 | P a g e
Computer Science Federal Board Class-12

103. How do you create a table in an SQLite database using Python?


Ans: You use the `execute()` method of the cursor object to run a `CREATE TABLE`
SQL statement.
Example:
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')
104. What is the purpose of conn.commit()?
Ans: conn.commit() is used to save (commit) the changes made to the
database. Without commit(), changes like creating tables or inserting data
will not be permanently stored.
105. What is the purpose of conn.close()?
Ans: conn.close() is used to close the connection to the database, releasing
any resources held by the connection. It's crucial to close connections when
done.
106. What does the IF NOT EXISTS clause do in a CREATE TABLE
statement?
Ans: IF NOT EXISTS prevents an error from occurring if you try to create a
table that already exists. If the table already exists, the statement is simply
skipped.
107. Can you use with statement for SQLite connections in Python?
Ans: Yes, it's best practice! The sqlite3.connect() function returns a
context manager, so you can use `with` to ensure the connection is properly
closed.
Example:
with sqlite3.connect('my_database.db') as conn:
cursor = conn.cursor()
# ... execute queries ...

17 | P a g e
Computer Science Federal Board Class-12

18 | P a g e

You might also like