Ch-7 Python Programming
1. Answer these questions.
a) Explain programming languages with its types.Ans: A programming language is a formal set of instructions used to communicate with a computer and create software.
(1) Low-Level Languages: These are close to machine hardware.
(i) Machine Language: Binary code (0s and 1s) that the CPU understands directly.
(ii) Assembly Language: Uses "mnemonics" (like MOV or ADD) instead of binary. Requires an Assembler.
(2) High-Level Languages: Designed to be human-readable and use English-like words (e.g., Python, Java, C++). They must be translated into machine code to run.
b) Differentiate between compiler and interpreter.
Ans:| Compiler | Interpreter |
|---|---|
| 1. Scans the entire program and translates it as a whole. | 1. Translates and executes the program line-by-line. |
| 2. Faster execution but slower initial translation. | 2. Slower execution but starts immediately. |
| 3. Debugging,Shows all errors at once after scanning. | 3. "Stops at the first error, making it easier to debug." |
| 4. Generates an intermediate object code (like an .exe). | 4. Does not generate intermediate object code. |
Algorithm: A step-by-step logical procedure or set of rules to be followed in calculations or problem-solving.
Flowchart: A visual or graphical representation of an algorithm using standard symbols.
d) Write five symbols with their functions of flowchart.1. Oval (Terminal): Indicates the Start or End of the process.
2. Parallelogram (Input/Output): Represents data being entered into or displayed from the system.
3. Rectangle (Process): Represents a calculation or a specific action.
4. Diamond (Decision): Used for "Yes/No" or "True/False" questions that branch the flow.
5. Arrows (Flow Lines): Show the direction of the process flow.
e) Create an algorithm to find whether the given number is odd or even. Also make flowchart from the algorithm.Step 1: Start
Step 2: Input or read an integer number (let's call it N)
Step 3: Calculate the remainder of N divided by 2 (N % 2)
Step 4: Check if the remainder is equal to 0:
4.1 If True, display "N is Even"
4.2 If False, display "N is Odd"
Step 5: Stop

f) Explain Python programming with its features.(i) Easy to read and write: Python uses simple and understandable syntax, making it easy for programmers to write and understand the code.
(ii) Versatile: Python can be used for a wide range of tasks like simple automating systems to complex web development, data analysis, and Artificial Intelligence.
(iii) Beginner-friendly : Python uses simple syntax, making it a great choice for those who are new to programming.
(iv) Extensive standard library : Python has an extensive standard library of pre-written code that offers programmers ready-made solutions, without requiring them to write code from ground level.
(v) Rich ecosystem : Python has a vast collection of libraries and ready-made structures known as frameworks that provide ready-to-use tools for programmers.
g) Describe the use of input/output statements in Python.| input() | print() |
|---|---|
| 1. Receives data from the user | 1. Displays data to the user |
| 2. Always returns a str | 2. Returns None |
| 3. Pauses the program until input is entered | 3. Executes immediately |
Formatted string literals (commonly called f-strings) are a Python syntax introduced in Python 3.6 that allow you to embed expressions, variables, and formatting instructions directly inside string literals.
By prefixing a string with f or F and placing expressions inside curly braces {} Enables direct evaluation and interpolation of variables without needing string concatenation (+) or the .format() method.
Example Program
user_name = input("Enter your name: ")
# Display the welcome message using an f-string
print(f"Hello {user_name}! Welcome to our program")
i) Explain the data types with examples.The classification of data based on its nature is called datatype. Python also offers various data type which are listed as:
j) Describe typecasting with its types.1. Integer (int):
It is a whole number ranging from negative infinity to positive infinity. Examples: ...,-3,-2,-1,0,1,2,3,...2. Float (float):
It is numbers with decimals. Examples: 3.14, -0.21, 1.567.3. String (str):
It consists of alphabets, special characters, alphanumeric values which are enclosed in double quotes. Examples: "hello world" , "Python Programming " etc.4. Boolean (bool):
It only provides True or False values. Example: is_student = True, has_mobile=FalseThe process of converting a variable from one data type to another is called type casting.
k) List the types of operators. Explain any one of them in detail with examples.1. Implicit Type casting
Implicit type casting, also known as automatic type conversion, occurs when the Python interpreter automatically converts one data type to another in certain situations.Example program to show concept of implicit type casting x = 12 # integer y = 9.5 # float z = x + y print(z) # Output: 21.5
2. Explicit Type casting
In explicit type casting, you forcefully change a variable from one data type to another using built-in functions. Here are the main ways to do this in Python: * int(): Forcefully converts a value to a whole number. * float(): Forcefully converts a value to a decimal number. * str(): Forcefully converts a value to text.Example program to show concept of explicit type casting
x = 21
y = float(x)
print("int to float:", y) # Output: 21.0Types of operators in Python
(i) Arithmetic Operator
(ii) Relational Operator
(iii) Logical Operator
(iv) Assignment Operator
l) Explain a conditional statement with an example. 1. Arithmetic operator
Arithmetic operator is used in Python to do mathematical operations. We use arithmetic operators as special symbols to do basic math. It is like having a set of tools for simple calculation.| Operators | Description | Example |
|---|---|---|
| + | Addition | print ( 5 + 2) = 7 |
| - | Subtraction | print ( 5 - 2) = 3 |
| * | Multiplication | print ( 5 * 2) = 10 |
| ** | Exponential (Power) | print ( 5 ** 2) = 25 |
| / | Division | print ( 5 / 2) = 2.5 |
| // | Floor Division | print ( 5 // 2) = 2 |
| % | Modulus(Remainder) | print ( 5 % 2) = 1 |
The if-else statement in Python evaluates a condition: if the condition is True, the code under if executes; if it is False, the code under else runs.
Syntax of if-else statement
if condition:
# Code block executes if condition is True
else:
# Code block executes if condition is False
m) Define iteration. Differentiate for and while loop. Example program to demonstrate concept of if-else statement
age = float (input ( " Enter age : " ) ) if age >= 18: print("Eligible to vote.") else: print("Not eligible to vote.")The process of repeating a particular task until a specified condition is satisfied is called iteration.
| For loop | While loop |
|---|---|
| 1. For loop is used when we know the number of iterations. | 1. While loop is used when we don’t know the number of iterations. |
| 2. This loop iterates an infinite number of times if the condition is not specified. | 2. If the condition is not specified, it shows compilation error. |
| 3. The increment is done after the execution of the statement. | 3. The increment can be done before or after the execution of a statement. |
| 4. The nature of increment is simple. | 4. The nature of increment is complex. |
| 5. Initialisation can be in or out of the loop. | 5. Initialisation is always out of the loop. |
| List | Dictionary |
|---|---|
| 1. A list stores elements in a sequence. | 1. A dictionary stores data in key:value pairs. |
| 2. List elements are accessed by index. | 2. Dictionary values are accessed by keys. |
| 3. List elements have an order. | 3. Dictionary values don’t have any specific order. |
| 4. List elements can be added and removed. | 4. Dictionary values are added as key:value pair and removed by key. |
# Initial list of places
cities = ["Kathmandu", "Biratnagar", "Nepalgunj", "Pokhara", "Butwal", "Birendranagar", "Mahendranagar", "Balefi"]
# a. Add list item "Malangawa"
cities.append("Malangawa")
# b. Remove list item "Balefi"
cities.remove("Balefi")
# c. Print the list items one by one using a loop
print("Updated list of cities:")
for city in cities:
print(city)
2. Write the names of technical terms:
a. A set of instructions to perform a specific task.
Ans: Program
b. The set of rules to write a program.
Ans: Syntax
c. Language translator that reads and translates program code to machine code line by line
Ans: Interpreter
d. The graphical or pictorial representation of a program
Ans: Flowchart
e. Text added in source code for the purpose of providing information or explanation that is ignored by the Python interpreter during execution
Ans: Comment
f. A data type that only provides true or false value
Ans: Boolean or bool
g. A special symbol that is used to check the relationship between two variables
Ans: Relational or Comparision Operator
h. The values or entities that operators act upon in programming
Ans: Operands
i. A decision-making control structure that helps our program to choose what to do
Ans: Selection or Conditional Statement
j. The process of repeating a task until a specified condition is met
Ans: Iteration or Looping
3. Write true or false for the following statements.
a. Programming language is used to give commands to the computer. True
b. Computers understand high level programming easily. False
c. Compiler and interpreter translate programming code to machine code. True
d. Algorithms are a graphical representation of instructions. False
e. Python is a machine understandable programming language. False
f. Print statement is used to display output in Python. True
g. In Python, "int" data type denotes alphabetical characters such as hello. False
h. Type casting is the conversion of one data type to another. True
i. In AND operator all the conditions must be true for the result to be true. True
j. In Python, if statement is used to provide a condition that, when false, allows a block of code to be executed. False
k. A for loop in Python is used to repeat a process until a specified time given by the user. False
l. Dictionaries have key: value pairs True
m. List items cannot be changed. False
n. In the dictionary the data can be deleted by value. False
4. Write full forms of the following.
i. LLL = Low-Level Language ii. HLL = High-Level Language iii. I/O = Input/Output iv. IDE = Integrated Development Environment5. Choose the correct answer.
a. In the context of programming language, what does the term "syntax" refer to? (i) The meaning of the code (ii) A set of instructions (iii) Efficiency of code execution (iv) Structure and rules of codeb) A computer understands ... (i) high level programming language (ii) low level programming language (iii) natural human language (iv) symbols and pictures
c) How does a flowchart represent a process in a program? (i) It provides a set of instructions for the computer. (ii) It visually shows the steps and decision points in a process. (iii) It directly executes the algorithm on the computer. (iv) It is a high-level programming language.
d) How does an algorithm differ from flowchart? (i) Algorithm is visual, while a flowchart is textual representation. (ii) An algorithm and flowchart are interchangeable terms. (iii) Algorithm is programming language, while flowchart is abstract concept (iv) Algorithm is a step-by-step procedure, while flowchart is a visual representation
e) Python is a programming language. (i) natural (ii) low-level (iii) high-level (iv) easy
f) What are keywords in Python? (i) Words used as comment in code (ii) Identifiers for variables (iii) Special words reserved for specific purpose (iv) User-defined functions
g) Input function is used in Python to (i) retrieve user input (ii) display the information (iii) define variable (iv) perform mathematical calculation
h) What data type in Python is suitable for representing text and characters? (i) Float (ii) Boolean (iii) Int (iv) String
(i) What will be the result of the following expression: float("3.14")? (i) 3.14 (ii) 3 (iii) 3.14" (iv) Error
j) What is the function of the NOT operator in Python? (i) Check for equality (ii) Give True value (iii) Convert expression to string (iv) Negate Boolean expression
k) What does the given image represent? (i) It is a flowchart telling us to bring umbrella. (ii) It is a flowchart giving us information about rain. (iii) It is a flowchart showing decision to make based on the condition of rain. (iv) It is a flowchart telling us not to bring umbrella.
l) How are elements accessed in a Python list? (i) By keys (ii) By values (iii) By indices (iv) By attributes
m) Which of the following statements accurately describes the mutability of Python lists and dictionaries? (i) Lists are immutable, while dictionaries are mutable. (ii) Both lists and dictionaries are immutable. (iii) Both lists and dictionaries are mutable. (iv) Lists are mutable, while dictionaries are immutable.
n) What is the primary purpose of Python lists? (i) Storing data in key:value pairs (ii) Storing data in a sequence. (iii) Storing data in a unordered manner (iv) Associating keys with values
6. Practise these practical questions.
Input/Output
a) Write a program to ask input as "name" from the user and greet the user as he/she provides their name.name = input("Enter your name: ")
print( "Hello", name , " Hope you have a great day.")
b) Write a program to input 3 sides of triangle and print areaimport math
a = float(input("Enter first side: "))
b = float(input("Enter second side: "))
c = float(input("Enter third side: "))
# Check the Triangle Inequality Theorem
if (a + b > c) and (a + c > b) and (b + c > a):
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
print("The area of the triangle is: ",area)
else:
print("Error: These side lengths cannot form a valid triangle.")
c) Write a program to input a radius and find the area and circumference of circleimport math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius**2
circumference = 2 * math.pi * radius
print("Area: ",area)
print("Circumference: ", circumference)
d) Write a program to input 3 digits as integers and calculate their sum and average.num1 = int(input("Enter first integer: "))
num2 = int(input("Enter second integer: "))
num3 = int(input("Enter third integer: "))
total_sum = num1 + num2 + num3
average = total_sum / 3
print( "Sum: " , total_sum)
print( "Average of three numbers ", average)
e) Write a program to input a diameter and print area of circle and circumference of circleimport math
diameter = float(input("Enter the diameter of the circle: "))
radius = diameter / 2
area = math.pi * radius**2
circumference = math.pi * diameter
print( " Area" , area)
print( " Circumference:" , circumference)
Constant value and Operators
a) Write a program to input a radius and find the area and circumference of the circle.# Defining PI as a constant
pi = 3.14159
radius = float(input("Enter radius: "))
area = pi * (radius**2)
circumference = 2 * pi * radius
print( " Area: " , area )
print( " Circumference" , circumference )
b) Write a program to show the use of arithmetic operators. (Perform add, subtract, multiply, divide, square and modulus between two numbers)num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print( " Addition (+): " , num1 + num2)
print( " Subtraction (-): " , num1 - num2)
print( " Multiplication (*):" , num1 * num2)
print( " Division (/): " , num1 / num2)
print( " Square of first number (**2): ", num1 ** 2)
print( " Modulus (%): " , num1 % num2)
c) Write a program to show the use of a comparison operator between two variables. (Use the following operators. ==, <=, >=, !=)a = float(input("Enter value for a: "))
b = float(input("Enter value for b: "))
print(" a == b (Is equal to): " , a == b )
print(" a <= b (Is less than or equal to): " , a <= b)
print(" a >= b (Is greater than or equal to): " , a >= b)
print(" a != b (Is not equal to): ", a != b)
If.....else Statement
a) Write a program using the if statement to check whether the given number is positive.num = float(input("Enter a number: "))
if num > 0:
print("The number is positive.")
b) Write a program that takes people's age as input and checks whether they are eligible to vote. (Voting age is 18 and above)age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
c) Write a program to check whether the given number is even or odd using an if-else statement.num = int(input("Enter a number: "))
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
d) Write a program to input two numbers and find the smallest number.num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if num1 < num2:
print("The smallest number is:", num1)
else:
print("The smallest number is:", num2)
e) Write a program that takes students' marks as an input and checks whether the student passed or failed. (40 or greater is pass marks)marks = float(input("Enter student's marks: "))
if marks >= 40:
print("Result: Pass")
else:
print("Result: Fail")
f) Write a program that takes 3 numbers as inputs and displays the smallest number.num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if num1 <= num2 and num1 <= num3:
print("The smallest number is:", num1)
elif num2 <= num1 and num2 <= num3:
print("The smallest number is:", num2)
else:
print("The smallest number is:", num3)
g) Make a program like a traffic light using an if-elif-else statement. Ask input from the user on providing color. (green-go, red-stop and orange-be ready, any other color-invalid color)color = input("Enter traffic light color: ").lower()
if color == "green":
print("go")
elif color == "red":
print("stop")
elif color == "orange":
print("be ready")
else:
print("invalid color")
h) Write a program to input practical and theory marks of Computer and check pass or fail. You can also validate whether a user has entered valid marks or not. (valid marks should be checked for both theory and practical)theory = float(input("Enter Theory marks (0-50): "))
practical = float(input("Enter Practical marks (0-50): "))
if theory < 0 or theory > 50 or practical < 0 or practical > 50:
print("Invalid marks entered. Theory and Practical marks must be between 0-50.")
else:
if theory >= 20 and practical >= 20:
print("Result: Passed in Computer Science.")
else:
print("Result: Failed in Computer Science.")
For loop
a) Write a program to print numbers from 1-15.for i in range(1, 16):
print(i)
b) Write a program to print an input name 20 times.name = input("Enter your name: ")
for i in range(20):
print(name)
c) Write a program to print the squares of numbers from 1 to 5 using a for loop.for i in range(1, 6):
print(i, "squared is", i * i)
d) Write a program to print first 20 odd numbersa=1
for i in range(20):
print(a)
a+=2
e) Write a program that takes an integer as input and prints the multiplication table for that number.num = int(input("Enter a number: "))
for i in range(1, 11):
print(num, "x", i, "=", num * i)
While loop
a) Write a program to print numbers from 1-20.i = 1
while i <= 20:
print(i)
i += 1
b) Write a program to print first 30 even numbers.count = 0
num = 2
while count < 30:
print(num)
num += 2
count += 1
c) Write a program to calculate the factorial of a given number.num = int(input("Enter a number: "))
factorial = 1
i = num
while i > 0:
factorial *= i
i -= 1
print("Factorial of", num, "is", factorial)
d) Write a program to print the sum of the first 20 odd numbers.count = 0
num = 1
total_sum = 0
while count < 20:
total_sum += num
num += 2
count += 1
print("Sum of the first 20 odd numbers is", total_sum)
e) Write a program to input multi digits numbers and display the sum of the digits. num = int(input("Enter a multi-digit number: "))
temp = num
digit_sum = 0
while temp > 0:
digit = temp % 10
digit_sum += digit
temp //= 10
print("Sum of digits of", num, "is", digit_sum)
Lists
1. Write a Python program to create a list of 5 integers and print the list.numbers = [10, 20, 30, 40, 50]
print(numbers)
2. Write a Python program to print the second and fourth elements of a list.numbers = [10, 20, 30, 40, 50]
print("Second element:", numbers[1])
print("Fourth element:", numbers[3])
3. Write a Python program to append a new element to the end of a list and print the updated list.numbers = [10, 20, 30]
numbers.append(40)
print(numbers)
4. Write a Python program to print the first three elements of a list using slicing.numbers = [10, 20, 30, 40, 50]
print(numbers[0:3])
5. Write a Python program to print the length of a list.numbers = [10, 20, 30, 40, 50]
print("Length of list:", len(numbers))
6. Write a Python program to iterate through a list and print each element.numbers = [10, 20, 30, 40, 50]
for item in numbers:
print(item)
7. Write a Python program to create a list of squares of numbers from 1 to 10 using list comprehension.squares = [x * x for x in range(1, 11)]
print(squares)
8. Write a Python program to remove the third element from a list and print the updated list.numbers = [10, 20, 30, 40, 50]
del numbers[2]
print(numbers)
Dictionaries
1. Write a Python program to create a dictionary with 3 key-value pairs and print the dictionary.student = {"name": "Alex", "age": 9, "grade": "A"}
print(student)
2. Write a Python program to print the value associated with a specific key in a dictionary.student = {"name": "Alex", "age": 9, "grade": "A"}
print("Age:", student["age"])
3. Write a Python program to add a new key-value pair to a dictionary and print the updated dictionary.student = {"name": "Alex", "age": 9}
student["city"] = "Kathmandu"
print(student)
4. Write a Python program to remove a key-value pair from a dictionary using the del statement and print the updated dictionary.student = {"name": "Alex", "age": 9, "grade": "A"}
del student["grade"]
print(student)
5. Write a Python program to iterate through a dictionary and print all the keys.student = {"name": "Alex", "age": 9, "grade": "A"}
for key in student:
print(key)
6. Write a Python program to create a dictionary where the keys are numbers from 1 to 5 and the values are their squares using dictionary comprehension.squares = {x: x * x for x in range(1, 6)}
print(squares)
7. Write a Python program to check if a specific key exists in a dictionary.student = {"name": "Alex", "age": 9}
key_to_check = "age"
if key_to_check in student:
print("Key", key_to_check, "exists in the dictionary.")
else:
print("Key", key_to_check, "does not exist.")
8. Write a Python program to merge two dictionaries and print the resulting dictionary. dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = dict1.copy()
merged_dict.update(dict2)
print(merged_dict)