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.
88 questions
Unit 4 · Programming in Python
Exercise: the basics of Python
2. Write short answers to these questions
What is the main job of the input() function in Python?
Answer
input() lets the user give data to a program while it runs. It shows a prompt, waits for the user to type something and press Enter, and returns what was typed as a string. Example: name = input("Enter your name: "). To use the input as a number, convert it with int() or float().
Give an example of a string literal in Python.
Answer
A string literal is text written directly in the program inside quotes, for example "Hello, Nepal" or 'Bhaktapur1'. In city = "Pokhara", "Pokhara" is the string literal.
What is an identifier in Python programming?
Answer
An identifier is a name given to something in a program, such as a variable, a function or a class: in total_marks = 450, total_marks is an identifier. It may contain letters, digits and underscores, can’t start with a digit, can’t be a keyword (such as if or for), and is case-sensitive (Age and age are different).
Explain the difference between the division operator (/) and the floor division operator (//).
Answer
/ (division) |
// (floor division) |
|---|---|
| Gives the exact answer, including the decimal part. | Divides and drops the decimal part, rounding down to a whole number. |
| The result is always a float. | For two integers, the result is an integer. |
9 / 2 gives 4.5; 8 / 2 gives 4.0 |
9 // 2 gives 4; 8 // 2 gives 4 |
Define the concept of data types in Python.
Answer
A data type is the kind of value a piece of data is, which decides what can be done with it. Python’s basic data types are integer (int, whole numbers such as 25), float (float, numbers with a decimal point such as 3.14), string (str, text such as "Nepal") and Boolean (bool, True or False). For example, numbers can be multiplied, but text can’t be.
What is the purpose of relational operators in Python? Give one example.
Answer
Relational operators compare two values, and give True or False. They are used to make conditions for if statements and loops. Example: marks >= 35 is True when the marks are 35 or more. The relational operators are ==, !=, >, <, >= and <=.
Describe what the else block does in an if-else statement.
Answer
The else block holds the lines that run when the if condition is false. So exactly one of the two blocks always runs: the if block when the condition is true, the else block otherwise. Example: if marks >= 35: print("Pass") and else: print("Fail"). else has no condition of its own and ends with a colon.
What is a nested if statement?
Answer
A nested if is an if statement written inside another if (or else) block. The inner condition is checked only when the outer condition is true. Example: first check if age >= 16: (citizenship), and inside it check if age >= 18: (voting).
When would you use a for loop instead of a while loop?
Answer
Use a for loop when you know in advance how many times to repeat, or when you go through every item of a sequence (a range of numbers, a list, a string): for example, printing a multiplication table from 1 to 10. Use a while loop when you repeat until a condition changes and you don’t know how many rounds it will take, such as asking for a password until it is right.
What does the range() function do in for loops?
Answer
range() makes a sequence of whole numbers for a for loop to go through, which sets how many times the loop runs. range(5) gives 0 to 4; range(1, 11) gives 1 to 10 (the stop value is never included); range(2, 21, 2) gives 2, 4, … 20 (the third number is the step).
Define a Python list and give a simple example.
Answer
A list is a data type that stores several values, in order, in one variable. It is written in square brackets with commas between the items, and the items can be of different types. Each item has an index starting from 0. Example: fruits = ["apple", "mango", "banana"]; fruits[0] is "apple".
Discuss the concept of iteration in programming.
Answer
Iteration means repeating a set of instructions again and again, either a fixed number of times or until a condition is met. It saves writing the same lines many times: one loop of 2 lines can print a thousand numbers. Python’s for loop repeats for each item in a sequence, and its while loop repeats as long as a condition is true. Each repetition is one round (iteration) of the loop.
3. Write long answers to these questions
Explain the categories of operators in Python (arithmetic, relational and logical), with examples of each.
Answer
An operator is a symbol that performs an operation on values (its operands).
Arithmetic operators do calculations: + addition (7 + 2 is 9), - subtraction (7 - 2 is 5), * multiplication (7 * 2 is 14), / division (7 / 2 is 3.5), // floor division (7 // 2 is 3), % modulus, the remainder (7 % 2 is 1), ** exponent (7 ** 2 is 49).
Relational operators compare two values and give True or False: == equal to (5 == 5 is True), != not equal to (3 != 5 is True), > greater than, < less than, >= greater than or equal to, <= less than or equal to (4 <= 6 is True).
Logical operators combine conditions: and is True only if both are true (age > 15 and age < 20), or is True if at least one is true (day == "Saturday" or holiday), and not reverses a condition (not (marks < 35)).
Arithmetic operators make values, relational operators turn values into True/False, and logical operators combine those True/False results into one decision.
Describe the three main types of conditional statements in Python (if, if-else and if-elif-else).
Answer
if statement: runs a block only when its condition is true; otherwise it does nothing.
if marks >= 35: print("Pass")if-else statement: chooses between two blocks; the if block runs when the condition is true, the else block when it is false. One of them always runs.
if marks >= 35: print("Pass")else: print("Fail")if-elif-else statement: chooses among many blocks. The conditions are checked from the top; the block of the first true one runs and the rest are skipped. else runs if none is true.
if marks >= 80: print("Distinction")elif marks >= 35: print("Pass")else: print("Fail")In all three, the condition line ends with a colon and the block under it is indented.
Explain Python’s two loops, for and while, with their syntax and a practical example of each.
Answer
The for loop repeats once for each value in a sequence, so it is used when the number of repetitions is known.
for variable in sequence: # block to repeatExample: the multiplication table of 7.
for i in range(1, 11): print(7, "x", i, "=", 7 * i)The while loop repeats as long as its condition is true, so it is used when we repeat until something happens.
while condition: # block to repeatExample: keep asking until the right PIN is typed.
pin = input("Enter PIN: ")while pin != "4321": pin = input("Wrong. Enter PIN again: ")print("Welcome!")A for loop ends when its sequence runs out; a while loop ends when its condition becomes false, so something inside it must change the condition.
Describe the four basic data types (integer, float, string and Boolean), with an example of each. Why is it important to understand data types when writing Python programs?
Answer
- Integer (
int): whole numbers without a decimal point, positive, negative or zero:students = 45. - Float (
float): numbers with a decimal point:height = 1.52. - String (
str): text inside single or double quotes:city = "Biratnagar". - Boolean (
bool):TrueorFalse:is_present = True.
Understanding data types matters because the type decides what an operation does and which operations are allowed. + adds numbers (5 + 3 is 8) but joins strings ("5" + "3" is "53"), and "Age: " + 15 is an error (TypeError). Since input() always gives a string, a program must convert it with int() or float() before calculating. Knowing the types helps you choose the right conversion and avoid wrong answers and errors.
Write a Python program that takes an integer from the user and: prints “Positive” if the number is greater than 0, “Negative” if it is less than 0, and “Zero” if it is 0; and if the number is positive, also checks whether it is even or odd and prints the result. Your program should show input and output, conditional statements (including a nested if) and arithmetic operators.
Hint
Use if, elif and else for the three cases, and inside the if block, a second if with n % 2 == 0.
Answer
n = int(input("Enter an integer: "))if n > 0: print("Positive") if n % 2 == 0: # nested if: only for positive numbers print("Even") else: print("Odd")elif n < 0: print("Negative")else: print("Zero")Output
Enter an integer: 14PositiveEvenLine 1 reads an integer (input and type casting). Lines 2, 8 and 10 choose between positive, negative and zero. The if on line 4 is nested inside the first block, so the even/odd check runs only for positive numbers; it uses the arithmetic operator %: a number is even when the remainder after dividing by 2 is 0.
Exercise: user-defined functions
2. Write short answers to these questions
What is the main benefit of using user-defined functions in programming?
Answer
A function’s code is written once and can be reused as many times as needed, just by calling it, which makes programs shorter. It also splits a program into small parts (modularity), each doing one job, so the program is easier to read, test and correct: a mistake is fixed in one place, and every call gets the fix.
Name the two types of Python functions.
Answer
- Built-in functions, which come with Python, such as
print(),len()andint(). - User-defined functions, which programmers write themselves with
def.
Explain the difference between a parameter and an argument in a Python function.
Answer
A parameter is a name in brackets in the function header that receives a value: in def area(length, width):, length and width are parameters. An argument is the actual value given when the function is called: in area(5, 8), 5 and 8 are arguments. When the function is called, each argument is put into its parameter.
What is local scope in Python functions? Give a brief example.
Answer
A variable made inside a function has local scope: it can be used only inside that function, and it exists only while the function runs.
def show(): msg = "Hello" # msg is local print(msg) show() # prints Helloprint(msg) # NameError: msg is not defined hereWhat is global scope in Python? How does it differ from local scope?
Answer
A variable made outside every function, in the main program, has global scope: it can be read anywhere in the program, including inside functions. A local variable, made inside a function, can be used only in that function and is gone when the function ends. For example, with rate = 0.1 at the top of a program, every function can use rate; but a result made inside a function can’t be used in the main program.
What is the purpose of the return keyword in a Python function?
Answer
return ends the function and sends a value back to the line that called it, where the call is replaced by that value. Example: with def add(x, y): return x + y, the line s = add(5, 3) stores 8 in s. A return with no value just ends the function, which then gives back None.
Explain what positional arguments are and how they are passed to a function.
Answer
Positional (required) arguments are matched to the parameters by their position: the first argument goes to the first parameter, the second to the second, and so on. The call must give exactly as many as the function needs. Example: for def check(a, b, c):, the call check(2, 5, 7) sets a = 2, b = 5 and c = 7. Swapping the arguments swaps the values.
Describe the use of default arguments in Python functions.
Answer
A default argument is a value given to a parameter in the function header, such as rate=0.10 in def interest(prin, time, rate=0.10):. It is used when the call doesn’t give that argument, so a value that is nearly always the same needn’t be typed every time: interest(2000, 2) uses 0.10, while interest(2000, 2, 0.12) uses 0.12. Parameters with defaults must come after those without.
What are keyword arguments, and what advantage do they offer when calling a function?
Answer
Keyword arguments are arguments given with the parameter’s name in the call, as name=value: interest(time=2, rate=0.12, prin=2000). Because each value is matched by name, they can be written in any order, so you don’t have to remember the order of the parameters, and the call is easier to read: it shows what each value is for.
What happens if a void function has a return statement without any value?
Answer
The return simply ends the function there and goes back to the caller; any lines after it in the function are skipped. Since no value is given, the function returns Python’s empty value, None: x = quote() stores None in x.
3. Write long answers to these questions
Explain the concept of function scope in Python, differentiating between local and global scope.
Answer
The scope of a variable is the part of a program where it can be used. Python has two main scopes.
Local scope: a variable made inside a function, including its parameters, is local to it. It is created when the function is called, can be used only inside that function, and disappears when the function returns. Using it outside gives a NameError. Two functions can each have a local variable called x without affecting each other.
Global scope: a variable made in the main program, outside every function, is global. It exists for the whole run of the program and can be read anywhere, inside functions too.
pi = 3.14 # global def circle_area(r): # r is local a = pi * r * r # a is local; pi is read from the global scope return a print(circle_area(10)) # 314.0print(pi) # 3.14: fine, pi is globalprint(a) # NameError: a is local to circle_area| Local variable | Global variable |
|---|---|
| made inside a function | made outside all functions |
| used only inside that function | used anywhere in the program |
| exists only while the function runs | exists for the whole program |
Describe the concept of return values in Python functions. Differentiate between functions that return a value (non-void) and those that do not (void). Give examples of both, and explain how the return value can be used in the calling part of the program.
Answer
A return value is the result a function sends back to the line that called it, with the return statement. The call is then replaced by that value.
A non-void function works out a value and returns it:
def square(n): return n * nA void function does a job, such as printing, but returns no computed value; it has no return, or a return with nothing after it, and Python makes it return None:
def show_square(n): print("The square is", n * n)The returned value can be used wherever a value can go: stored in a variable (s = square(4), so s is 16), printed (print(square(4))), used in an expression (total = square(3) + square(4), 25) or passed to another function (print(square(square(2))), 16). A void function’s result can’t be used like this: x = show_square(4) prints the message but stores None in x.
Python allows functions to return multiple values. Explain how this is done, with an example of a function that returns several values and how the caller can use them.
Answer
Write all the values after return, separated by commas: return a, b. Python packs them into a single tuple. The caller can keep the tuple whole, or unpack it into one variable per value.
def min_max(numbers): return min(numbers), max(numbers) marks = [72, 85, 64, 90]result = min_max(marks)print(result)low, high = min_max(marks)print("Lowest:", low, "Highest:", high)Output
(64, 90)Lowest: 64 Highest: 90On line 5 the tuple is kept whole; on line 7 it is unpacked into low and high. The number of variables on the left must match the number of values returned.
Design a Python program with at least two user-defined functions: one that takes two numbers as arguments and returns their product, and another that takes a list of numbers as an argument and prints each number.
Answer
def product(a, b): return a * b def print_numbers(numbers): for n in numbers: print(n) x = float(input("Enter the first number: "))y = float(input("Enter the second number: "))print("Product:", product(x, y))print_numbers([4, 8, 15, 16])Output
Enter the first number: 4Enter the second number: 2.5Product: 10.0481516product() is a non-void function: it returns a * b, and the main program prints what comes back. print_numbers() is a void function: it prints each number in the list with a for loop and returns nothing.
Exercise: libraries, packages and errors
2. Write short answers to these questions
Define the term “module” in Python programming.
Answer
A module is a single file of Python code (a .py file) containing functions, variables and classes that other programs can use by importing it. For example, the math module has sqrt() and pi: import math then math.sqrt(16). Any .py file you write can be used as a module too.
What is the relationship between modules and libraries in Python?
Answer
A library is made up of modules: it is a collection of modules (often grouped in packages) that together provide one kind of facility. A module is one file; a library is many. For example, Python’s standard library contains the modules math, random, csv and turtle, and the Matplotlib library contains the module pyplot.
Give an example of a built-in Python library and its purpose.
Answer
The math module, part of Python’s built-in standard library, gives mathematical functions and constants: math.sqrt(25) gives 5.0 and math.pi gives 3.14159…. Other examples: random makes random numbers, turtle draws graphics, and csv reads and writes CSV files.
Explain why packages are useful for code organization and reusability.
Answer
A package groups related modules into one folder under one name, so a large amount of code is organized by topic and easy to find: matplotlib.pyplot for plotting, for example. Since the package can be imported into any program, the same tested code is reused again and again instead of being rewritten, and modules in different packages may even share a name without clashing.
What is the purpose of using an alias when importing a module in Python? Give an example.
Answer
An alias is a short name given to a module as it is imported, with as, so that a long name needn’t be typed every time and the code is shorter and easier to read. Example: import pandas as pd, after which pd.read_csv("data.csv") means pandas.read_csv("data.csv"). Similarly import matplotlib.pyplot as plt.
Name two functions provided by Python’s math module.
Answer
math.sqrt(), which gives the square root (math.sqrt(49) is 7.0), and math.pow(), which gives a power (math.pow(2, 3) is 8.0). Others: math.sin(), math.cos(), math.log10(), math.ceil(), math.floor(), math.factorial().
What is a runtime error? Give an example of a situation that might cause one.
Answer
A runtime error is an error that happens while a program is running, although its syntax is correct: a line turns out to be impossible to carry out with the data it has. Example: a program that calculates total / count stops with ZeroDivisionError: division by zero if the user gives 0 for count. Another: int(input()) raises a ValueError if the user types letters.
Explain the difference between an error and an exception in Python.
Answer
“Error” is the general word for any problem in a program. Some errors, like syntax errors, are found before the program runs and must be corrected in the code; logical errors give wrong results with no message at all. An exception is an error detected while the program runs, such as ZeroDivisionError or ValueError. An exception doesn’t have to be fatal: the program can catch it with try and except and carry on, whereas a syntax error can only be fixed by changing the code.
What is the role of the except block in a try-except statement?
Answer
The except block says what to do if an error happens in the try block. When the try block raises an exception, Python jumps to the except block that names that exception and runs it, instead of stopping the program with an error message. Example: except ZeroDivisionError: print("Can't divide by zero").
When is the else block in a try-except-else statement executed?
Answer
The else block runs only when the try block finishes without raising any exception; if an exception happens, the except block runs instead, and else is skipped. It holds the code that should run only when everything in try worked, such as printing a result.
3. Write long answers to these questions
Explain the concepts of Python libraries and packages, and why they are important in software development.
Answer
A module is one file of Python code. A package is a folder of related modules, accessed with a dot, such as matplotlib.pyplot. A library is a collection of modules and packages that together meet one kind of need: NumPy for scientific computing, Pandas for data, Matplotlib for charts. Python’s standard library (math, random, csv, turtle, datetime…) comes with Python; others are installed with pip install. Any of them is used with import.
They matter because:
- Reuse: programmers don’t rewrite common code (square roots, reading files, charts); one line imports it.
- Saving time: a program that would take weeks can be written in hours.
- Reliability: popular libraries are used and tested by millions, so they have fewer bugs than new code.
- Organization: code is split by topic, so large programs stay manageable.
- Sharing: libraries let programmers around the world build on one another’s work.
Introduce three popular Python libraries: Pandas, Turtle and Matplotlib. For each, describe its main purpose and give a simple example of how it is used.
Answer
Pandas stores and analyzes data in tables called DataFrames: it reads and writes files such as CSV and Excel, and filters, sorts and summarizes data.
import pandas as pddf = pd.DataFrame({'Name': ['Sita', 'Ram'], 'Marks': [85, 72]})print(df)Turtle draws pictures by moving a pointer, the turtle, that draws as it moves. It is used to learn programming through graphics.
import turtlet = turtle.Turtle()for i in range(3): # an equilateral triangle t.forward(100) t.left(120)turtle.done()Matplotlib draws charts and graphs: line plots, bar charts, pie charts, scatter plots and more.
import matplotlib.pyplot as pltplt.bar(['A', 'B', 'C'], [30, 45, 25])plt.show()Discuss the types of error that can occur in Python programs: syntax errors, runtime errors and logical errors. Give an example of each, and explain how each affects the running and the correctness of a program.
Answer
Syntax error: a mistake in the rules of writing Python, such as a missing colon, bracket or quote, or wrong indentation. Example: if marks >= 35 without the colon gives SyntaxError: expected ':'. Python finds it before running anything, so no part of the program runs until it is corrected.
Runtime error: the code is written correctly, but something impossible happens while it runs. Example: result = a / b when the user enters 0 for b gives ZeroDivisionError: division by zero. The program runs until that line, then stops, unless the error is handled with try and except. It may appear only with some inputs.
Logical error: the program runs to the end with no message, but the result is wrong, because the logic is wrong. Example: average = a + b / 2 instead of (a + b) / 2 gives 11 for 8 and 6, not 7. This is the most dangerous kind, because nothing warns you; it is found only by testing with values whose answers you know.
Explain the importance of error handling in Python.
Answer
Error handling means expecting the errors that can happen while a program runs and dealing with them using try, except, else and finally. It is important because:
- The program doesn’t crash: a wrong input or a missing file gives a helpful message instead of stopping everything.
- It is easier to use: “Please type a number” is clearer to a user than a traceback.
- It protects data:
finallymakes sure files are closed and work is saved even when something goes wrong. - The program can recover: it can ask again, use a default value or skip a bad record and go on.
- It is easier to maintain: problems are handled in known places.
try: age = int(input("Enter your age: "))except ValueError: print("Please enter your age as a number.")Exercise: files and Pandas
2. Write short answers to these questions
What are the main advantages of using the Pandas library for file handling in Python?
Answer
- One line reads or writes a whole file:
pd.read_csv()anddf.to_csv(). - It reads many formats besides CSV: Excel, JSON, SQL databases.
- The data arrive as a DataFrame, a table with named columns, and number columns are recognized as numbers automatically.
- The data can then be sorted, filtered, summarized and cleaned at once, and passed straight to charts.
Explain what a CSV file is and why it is a common format for exchanging data.
Answer
A CSV (comma-separated values) file is a plain-text file holding a table: each line is one record, its values separated by commas, and the first line usually names the columns, such as Name,Age then Sita,15. It is common for exchanging data because it is plain text that any text editor or spreadsheet can open, its structure is simple for programs to write and read, and almost every program and programming language supports it.
What is the first step you need to take to use the Pandas library in your Python program for file handling?
Answer
Import it, usually with the alias pd: import pandas as pd. (If Pandas isn’t installed on the computer yet, it must first be installed from the command prompt with pip install pandas.)
Describe the basic syntax for reading a CSV file into a Pandas DataFrame.
Answer
df = pd.read_csv("filename.csv"), after import pandas as pd. read_csv() takes the file’s name (with its folder, if it is not in the program’s folder) and returns a DataFrame, stored here in df. An optional sep gives the separator if it is not a comma: pd.read_csv("data.csv", sep=";").
How can you access one column of data after reading a CSV file into a Pandas DataFrame? Give an example.
Answer
Write the column’s name in square brackets after the DataFrame’s name: df['Salary']. If the name has no spaces, df.Salary works too. Example: after df = pd.read_csv("result.csv"), print(df['Computer']) shows that column’s values, and df['Computer'].mean() gives their average.
Explain the basic syntax for writing a Pandas DataFrame to a CSV file.
Answer
df.to_csv("filename.csv", index=False). to_csv() is a method of the DataFrame, here df; it takes the name of the file to write (creating it, or replacing it if it exists). index=False leaves out the row numbers, and an optional sep sets the separator, a comma by default.
What happens if you try to open a file that doesn’t exist in read ("r") mode with the built-in open() function?
Answer
Python raises an exception, FileNotFoundError: [Errno 2] No such file or directory: 'name.txt', and the program stops, unless the error is handled with try and except FileNotFoundError:. Read mode never creates a file.
Explain the difference between write ("w") mode and append ("a") mode when opening a file.
Answer
Both create the file if it doesn’t exist. If the file exists, "w" wipes all of its contents as soon as it is opened and writes from the start, while "a" keeps its contents and adds the new writing at the end. Use "w" to replace a file, and "a" to add to a log or a list of records.
Why is it important to close a file after reading or writing (even when using Pandas)?
Answer
Closing a file makes sure that everything written is really saved to the disk, frees the memory and the file for other programs, and avoids having too many files open at once. A file left open can lose its last data if the program crashes, and on Windows other programs may not be able to change or delete it. Pandas’ read_csv() and to_csv() open and close the file for you when given a file name; a file you open yourself with open() you must close with close(), or open with with so Python closes it.
3. Write long answers to these questions
Write the steps to read data from a CSV file using Pandas in Python, with a simple program that imports the Pandas library and reads the CSV file.
Answer
- Install Pandas if it isn’t installed:
pip install pandasat the command prompt. - Import it:
import pandas as pd. - Read the file with
pd.read_csv(), which returns a DataFrame:df = pd.read_csv("result.csv"). - Look at the field names with
df.columns. - Use the data: a column with
df['Computer'], the first rows withdf.head(), or the whole table withprint(df).
import pandas as pd # import the librarydf = pd.read_csv("result.csv") # read the CSV file into a DataFrameprint(df.columns) # the field namesprint(df) # the dataYou have a CSV file named student_data.csv with the columns Name, Age and Grade. Write a Python program using Pandas to (a) read the data from the file into a DataFrame, (b) print the first 5 rows of the DataFrame, (c) calculate the average age of the students, and (d) create a new DataFrame containing only the students with a Grade of “A”.
Answer
import pandas as pd df = pd.read_csv("student_data.csv") # a. read the fileprint(df.head()) # b. the first 5 rowsaverage_age = df['Age'].mean() # c. the average ageprint("Average age:", average_age)grade_a = df[df['Grade'] == 'A'] # d. only the students with grade Aprint(grade_a)If the file holds six students, the output might be:
Output
Name Age Grade0 Asha 15 A1 Bikash 16 B2 Chandra 15 A3 Dipa 16 C4 Eshan 15 AAverage age: 15.5 Name Age Grade0 Asha 15 A2 Chandra 15 A4 Eshan 15 Adf['Grade'] == 'A' gives True or False for each student, and df[…] keeps only the True rows, which keep their own index numbers (0, 2, 4).
Exercise
2. Write short answers to these questions
Define data visualization in your own words.
Answer
Data visualization is showing data as pictures, such as charts, graphs and maps, so that people can understand it quickly and see its patterns, trends and comparisons, which are hard to see in a table of numbers.
Why is data visualization important for businesses and analysts?
Answer
Businesses collect huge amounts of data every day. Charts let them understand it quickly, spot trends (which product sells most, which month is slow), find problems and unusual values, and make decisions based on facts. They also make it easy to explain findings to others, such as managers and customers, who have no time to read tables of numbers.
Name three popular Python libraries for data visualization.
Answer
Matplotlib, Seaborn and Plotly.
What feature of Matplotlib gives both freedom and the need for more code?
Answer
Matplotlib is a low-level library: the programmer controls every part of a chart (axes, labels, colors, sizes, ticks), which gives great freedom, but each of those details has to be set in code, so making a polished chart takes more lines than in a higher-level library such as Seaborn or Plotly Express.
What type of data is usually shown with a bar chart?
Answer
Data in separate categories, each with a number, to compare them: the marks of each student, the sales of each product, the population of each province. Each category gets a bar whose length is its value.
What is Seaborn built on, and what kind of charts does it mainly make?
Answer
Seaborn is built on Matplotlib (and works closely with Pandas DataFrames). It mainly makes attractive statistical charts that show patterns and relations in data, such as line plots, bar plots, heatmaps and distributions, with less code than Matplotlib alone.
What key feature of Plotly sets it apart from Matplotlib?
Answer
Plotly’s charts are interactive: in a browser or notebook you can hover over a point to see its exact value, zoom in, move around and hide or show parts of the data. Matplotlib’s charts are mostly still pictures.
In Matplotlib, what do plt.xlabel() and plt.ylabel() do?
Answer
They label the axes: plt.xlabel('Day') writes a title under the horizontal (x) axis, and plt.ylabel('Plates') writes one beside the vertical (y) axis, so a reader knows what each axis shows.
What type of data is best shown with a pie chart?
Answer
The parts of one whole, to show each part’s share or percentage: how a budget is spent, the share of each party’s votes, the subjects of a timetable. It works best with a few parts; with many small slices, or for comparing changes over time, a bar or line chart is clearer.
What is the purpose of the color argument in Plotly Express functions?
Answer
color names a column whose values decide the color of each point, line or bar, so the data are split into groups with a legend: color='Gender' draws boys and girls in two colors. It lets one chart compare groups.
3. Write long answers to these questions
Explain the importance of data visualization in data analysis.
Answer
Data analysis means studying data to find useful information. Visualization helps at every step:
- Understanding: a chart shows in seconds what would take hours to find in a table: the highest and lowest values, the trend, the shape of the data.
- Patterns and trends: rising or falling sales, seasons, connections between two quantities (a scatter plot of study hours against marks).
- Errors and unusual values: a mistyped mark of 950 stands out at once on a chart.
- Comparison: bar charts compare categories; pie charts show shares of a whole.
- Decisions: managers, doctors and governments act on what charts show.
- Communication: a clear chart explains findings to people who aren’t experts.
With huge amounts of data made every day, visualization is how people make sense of it.
Compare Matplotlib and Plotly for data visualization in Python: their key features, strengths and weaknesses, especially their ease of use, interactivity and the control they give over line charts, pie charts and bar charts.
Answer
Matplotlib is Python’s oldest and most used plotting library. Its charts are still images, shown in a window or saved as pictures (PNG, PDF). Strengths: it can draw nearly every kind of chart, gives complete control over every detail, and is ideal for printed reports. Weaknesses: it needs more lines of code, its default look is plain, and its charts are not interactive.
- Line:
plt.plot(x, y); bar:plt.bar(x, y); pie:plt.pie(sizes, labels=…, autopct='%1.1f%%'); then labels withplt.title(),plt.xlabel(),plt.ylabel(), andplt.show().
Plotly makes interactive charts in a web browser or notebook. Strengths: hovering shows values, you can zoom and pan, the charts look modern by default, can be put on websites (saved as HTML), and plotly.express makes a complete chart, with legend and colors, in one line from a DataFrame. Weaknesses: the charts are heavier files, they need a browser, and fine control over every detail takes more knowledge of its other parts.
- Line:
px.line(df, x=…, y=…); bar:px.bar(df, x=…, y=…, color=…); pie:px.pie(df, names=…, values=…); thenfig.show().
In short: Matplotlib for detailed control and printable still charts; Plotly for quick, interactive charts to explore data or share online.
Explain how to create a basic line chart, bar graph and pie chart using Matplotlib. Include the import statement, example data, and the key functions used to create and show each chart.
Answer
Import the pyplot module: import matplotlib.pyplot as plt. Then give the data as lists, call the chart function, add a title and labels, and show it with plt.show().
import matplotlib.pyplot as pltmonths = ['Baisakh', 'Jestha', 'Asar', 'Shrawan']sales = [120, 150, 90, 180] # line chart: plt.plot()plt.plot(months, sales)plt.title("Sales by month")plt.xlabel("Month")plt.ylabel("Sales")plt.show() # bar graph: plt.bar()plt.bar(months, sales)plt.title("Sales by month")plt.xlabel("Month")plt.ylabel("Sales")plt.show() # pie chart: plt.pie()plt.pie(sales, labels=months, autopct='%1.1f%%')plt.title("Share of sales")plt.show()plt.plot() joins the points with lines (for a trend); plt.bar() draws a bar for each category (for comparison); plt.pie() divides a circle in proportion to the values (for shares of a whole), with autopct writing the percentages. Each plt.show() opens one chart; close its window to see the next.
A Pandas DataFrame holds a year’s sales data for different product categories, with the columns Month, Category and Sales. Outline the steps and write Python code (with Matplotlib or Plotly) to make: (a) a line chart of the total sales trend over the months, for all categories together; (b) a bar graph comparing the total sales of each category for the whole year; (c) a pie chart of each category’s percentage of the year’s total sales.
Hint
Each month and each category appears on many rows. df.groupby('Month')['Sales'].sum() adds up the sales for each month.
Answer
Steps: import Pandas and Matplotlib; read the data into a DataFrame; for each chart, add up the sales of the group it needs with groupby() and sum(); then plot the totals.
import pandas as pdimport matplotlib.pyplot as plt df = pd.read_csv("sales.csv") # columns: Month, Category, Sales # a. total sales in each month, all categories togethermonthly = df.groupby('Month', sort=False)['Sales'].sum()plt.plot(monthly.index, monthly.values)plt.title("Total sales by month")plt.xlabel("Month")plt.ylabel("Sales")plt.show() # b. total sales of each category for the yearby_category = df.groupby('Category')['Sales'].sum()plt.bar(by_category.index, by_category.values)plt.title("Total sales by category")plt.xlabel("Category")plt.ylabel("Sales")plt.show() # c. each category's share of the year's salesplt.pie(by_category.values, labels=by_category.index, autopct='%1.1f%%')plt.title("Share of sales by category")plt.show()groupby('Month') gathers the rows of each month, and ['Sales'].sum() adds their sales; sort=False keeps the months in the order they appear in the file instead of alphabetical order. The result’s .index holds the months (or categories) and .values the totals.
4. Practical questions
Write a Python program to take two numbers as input and print their sum, difference, product and quotient.
Answer
a = float(input("Enter the first number: "))b = float(input("Enter the second number: "))print("Sum:", a + b)print("Difference:", a - b)print("Product:", a * b)print("Quotient:", a / b)Output
Enter the first number: 10Enter the second number: 4Sum: 14.0Difference: 6.0Product: 40.0Quotient: 2.5Write a program that takes a user’s name as input and prints a greeting message using the print() function.
Answer
name = input("Enter your name: ")print("Namaste,", name + "! Welcome to Python.")Output
Enter your name: AayushNamaste, Aayush! Welcome to Python.Create a Python program that takes an integer from the user and checks whether it is positive, negative or zero, using an if-elif-else statement.
Answer
n = int(input("Enter an integer: "))if n > 0: print("Positive")elif n < 0: print("Negative")else: print("Zero")Write a program that accepts two numbers from the user and swaps their values without using a third variable.
Answer
a = int(input("Enter a: "))b = int(input("Enter b: "))a, b = b, aprint("After swapping: a =", a, "b =", b)Output
Enter a: 3Enter b: 8After swapping: a = 8 b = 3Line 3 works out the right side first, the pair (8, 3), then puts them into a and b. Without that Python shortcut, arithmetic also works: a = a + b, b = a - b, a = a - b.
Create a program that takes a sentence as input and counts the number of vowels in it.
Answer
sentence = input("Enter a sentence: ")count = 0for letter in sentence.lower(): if letter in "aeiou": count += 1print("Number of vowels:", count)Output
Enter a sentence: Namaste from NepalNumber of vowels: 6lower() turns capitals into small letters, so “A” is counted as well as “a”. in checks whether the letter is one of the five.
Write a Python program to create a new file called data.txt and write the sentence “Hello, this is a test file.” into it.
Answer
file = open("data.txt", "w")file.write("Hello, this is a test file.")file.close()Change the program above to append the sentence “This is an appended line.” to the same file.
Answer
file = open("data.txt", "a")file.write("\nThis is an appended line.")file.close()The mode changes from "w" to "a", so the first sentence is kept; \n starts the new sentence on a new line.
Write a program that reads a file and prints its content on the screen.
Answer
file = open("data.txt", "r")print(file.read())file.close()Output
Hello, this is a test file.This is an appended line.Write a Python program using the csv module to create a CSV file students.csv with the columns Name and Marks, and add three student records.
Answer
import csvwith open("students.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerow(["Name", "Marks"]) writer.writerow(["Sita", 85]) writer.writerow(["Ram", 72]) writer.writerow(["Gita", 91])print("students.csv created.")csv.writer() makes a writer object, and writerow() writes one list as one line, with the commas put in. newline="" stops Windows from leaving a blank line between the rows.
Write a program that reads the data from students.csv and displays it.
Answer
import csvwith open("students.csv", "r") as f: for row in csv.reader(f): print(row)Output
['Name', 'Marks']['Sita', '85']['Ram', '72']['Gita', '91']With Pandas, print(pd.read_csv("students.csv")) shows it as a table.
Using Pandas, read a CSV file and print its first five rows.
Answer
import pandas as pddf = pd.read_csv("students.csv")print(df.head())head() gives the first 5 rows; head(n) the first n.
Write a Pandas program to create a DataFrame from a dictionary and save it as a CSV file.
Answer
import pandas as pddata = {'Name': ['Sita', 'Ram', 'Gita'], 'Marks': [85, 72, 91]}df = pd.DataFrame(data)df.to_csv("marks.csv", index=False)print("Saved to marks.csv")Using Pandas and Matplotlib, read data from a CSV file and draw a pie chart of product sales.
Answer
Suppose sales.csv has the columns Product and Sales:
import pandas as pdimport matplotlib.pyplot as pltdf = pd.read_csv("sales.csv")plt.pie(df['Sales'], labels=df['Product'], autopct='%1.1f%%')plt.title("Product sales")plt.show()Write a Python function that takes two numbers as input and returns their sum.
Answer
def add(a, b): return a + b print(add(7, 5)) # 12Create a function that calculates the area of a circle, given the radius as a parameter.
Answer
def area_circle(r): return 3.14 * r * r radius = float(input("Enter the radius: "))print("Area:", area_circle(radius))Output
Enter the radius: 10Area: 314.0With import math, math.pi * r * r is more accurate; use whichever value of π the question gives.
Write a function that checks whether a number is prime.
Hint
A prime number has exactly two factors, 1 and itself. Try dividing by every number from 2 upwards; if any divides exactly (n % i == 0), it isn’t prime.
Answer
def is_prime(n): if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True num = int(input("Enter a number: "))if is_prime(num): print(num, "is a prime number.")else: print(num, "is not a prime number.")Output
Enter a number: 2929 is a prime number.1 and numbers below it are not prime (line 2). It is enough to try divisors up to the square root of n, n ** 0.5: if n had a factor larger than that, it would also have one smaller. range(2, n) works too, just more slowly.
Write a function that takes a list of numbers and returns the largest number in the list.
Answer
def largest(numbers): biggest = numbers[0] for n in numbers: if n > biggest: biggest = n return biggest print(largest([12, 45, 7, 30]))Output
45Start with the first number as the biggest so far, and replace it whenever a bigger one comes. (Python’s built-in max() does the same job: max([12, 45, 7, 30]).)
Write a program that reads a file and handles the exception if the file does not exist.
Answer
filename = input("Enter the file name: ")try: file = open(filename, "r") print(file.read()) file.close()except FileNotFoundError: print("Sorry, the file", filename, "does not exist.")Output
Enter the file name: missing.txtSorry, the file missing.txt does not exist.If the file exists, the try block prints it; if not, open() raises FileNotFoundError and the except block shows a message instead of a crash.
