Programming in Python
Unit 4: Programming in Python
Class: 10 | Subject: Computer Science | Exam: SEE Syllabus: CDC Computer Science Grade 9тАУ10 (Unit 4) Working hours: 16 theory + 18 practical
Topics Covered in this Unit
| S.N. | Topic |
|---|---|
| 4.1 | Revision of the Basics of Python |
| 4.2 | User Defined Functions: scope, parameter, argument, return type, passing |
| 4.3 | Library and Packages in Python (importing standard libraries; Math, random, Pandas, Turtle, matplotlib) |
| 4.4 | Graphics Using Turtle |
| 4.5 | Error Handling: errors and exceptions, try-except blocks |
| 4.6 | File Handling (modes: read, write, append) and Reading/Writing CSV files using Pandas |
| 4.7 | Data Visualization: line chart, pie chart and bar graph (matplotlib) |
| тАУ | Practical Tasks and Project Work |
4.1 Revision of the Basics of Python
Python is a simple, high-level, interpreted programming language. Its code is easy to read and write, so it is widely used for learning programming, data science, AI and web development.
Basic Structure of a Python Program
# This is a comment (it is ignored by Python)
name = input("Enter your name: ") # input
print("Hello,", name) # output
- Python uses indentation (spaces at the beginning of a line) to define blocks of code.
#starts a comment.- Python is case sensitive (
Nameandnameare different).
Input and Output
| Statement | Use |
|---|---|
print() | Displays output on the screen |
input() | Takes input from the user (always as a string) |
a = int(input("Enter a number: "))
print("Square =", a * a)
Variables and Data Types
A variable is a name given to a memory location that stores a value.
| Data type | Meaning | Example |
|---|---|---|
int | Whole number | x = 10 |
float | Decimal number | y = 3.5 |
str | Text (string) | name = "Ram" |
bool | True or False | ok = True |
list | Ordered, changeable collection | [10, 20, 30] |
dict | Key-value pairs | {"name": "Ram", "age": 15} |
Type Casting
Converting one data type into another.
int("25") # 25
float(7) # 7.0
str(100) # "100"
Operators
| Type | Operators | Example |
|---|---|---|
| Arithmetic | + - * / // % ** | 7 // 2 gives 3, 7 % 2 gives 1, 2 ** 3 gives 8 |
| Relational | == != > < >= <= | 5 > 3 gives True |
| Logical | and, or, not | (5 > 3) and (2 > 4) gives False |
| Assignment | = += -= *= /= | x += 5 means x = x + 5 |
Conditional Statements
marks = int(input("Enter marks: "))
if marks >= 80:
print("Distinction")
elif marks >= 40:
print("Pass")
else:
print("Fail")
Loops (Iteration)
# for loop
for i in range(1, 6):
print(i)
# while loop
n = 1
while n <= 5:
print(n)
n += 1
List and Dictionary
fruits = ["apple", "banana", "mango"]
fruits.append("orange") # add at the end
print(fruits[0]) # apple (index starts from 0)
print(len(fruits)) # 4
student = {"name": "Ram", "age": 15}
print(student["name"]) # Ram
student["age"] = 16 # change a value
Library (Built-in) Functions
| Group | Function | Example | Result |
|---|---|---|---|
| String | len() | len("Nepal") | 5 |
upper() | "nepal".upper() | NEPAL | |
lower() | "NEPAL".lower() | nepal | |
center() | "Nepal".center(11, "*") | ***Nepal*** | |
| Numeric / Math | sum() | sum([1, 2, 3]) | 6 |
pow() | pow(2, 3) | 8 | |
round() | round(3.14159, 2) | 3.14 | |
abs() | abs(-5) | 5 | |
int() | int(7.9) | 7 | |
sqrt() (from math) | math.sqrt(16) | 4.0 |
4.2 User Defined Functions
Function
A function is a named block of code that performs a specific task. It runs only when it is called.
Types of Functions
- Built-in functions: already available in Python, e.g.
print(),len(),input(). - User-defined functions: created by the programmer using the
defkeyword.
Advantages of Using Functions
- Reusability: write once, use many times.
- Reduces repetition of code.
- Makes a program shorter, simpler and easier to debug.
- A big problem can be divided into small parts.
Syntax
def function_name(parameters):
# body of the function
statements
return value # optional
Defining and Calling a Function
def greet(): # function definition
print("Welcome to Nepal")
greet() # function call
greet() # can be called again
Output:
Welcome to Nepal
Welcome to Nepal
Parameter and Argument
| Term | Meaning |
|---|---|
| Parameter | The variable written in the function definition (inside the brackets). It receives a value. |
| Argument | The actual value passed when calling the function. |
def add(a, b): # a and b are PARAMETERS
print(a + b)
add(10, 20) # 10 and 20 are ARGUMENTS -> Output: 30
Return Type (the return statement)
return sends a result back to the place where the function was called, and ends the function.
def add(a, b):
return a + b
result = add(10, 20)
print(result) # 30
return:returngives the value back so that it can be stored or used in more calculations.
Passing Arguments to a Function
1. Positional arguments: values are matched by position (order).
def info(name, age):
print(name, age)
info("Ram", 15) # name = "Ram", age = 15
2. Keyword arguments: values are matched by the parameter name, so the order does not matter.
info(age=15, name="Ram")
3. Default parameters: a parameter gets a default value if no argument is given.
def greet(name="Friend"):
print("Hello", name)
greet("Sita") # Hello Sita
greet() # Hello Friend
Four Forms of a Function
| Form | Example |
|---|---|
| No parameter, no return | def hello(): print("Hi") |
| With parameter, no return | def square(n): print(n * n) |
| No parameter, with return | def pi(): return 3.14 |
| With parameter and return | def square(n): return n * n |
Scope of Variables
Scope means the part of the program where a variable can be used.
| Local variable | Global variable |
|---|---|
| Created inside a function | Created outside all functions |
| Can be used only inside that function | Can be used anywhere in the program |
| Destroyed when the function ends | Exists until the program ends |
x = 10 # global variable
def show():
y = 5 # local variable
print(x, y) # both can be used here
show() # Output: 10 5
print(x) # 10
print(y) # ERROR: y is not defined (it is local to show)
To change a global variable inside a function, use the global keyword:
count = 0
def increase():
global count
count = count + 1
increase()
print(count) # 1
Example Programs
1. Function to find the area of a rectangle
def area(length, breadth):
return length * breadth
print("Area =", area(10, 5)) # Area = 50
2. Function to check even or odd
def check(n):
if n % 2 == 0:
return "Even"
else:
return "Odd"
print(check(7)) # Odd
3. Function to find the factorial of a number
def factorial(n):
f = 1
for i in range(1, n + 1):
f = f * i
return f
print(factorial(5)) # 120
4.3 Library and Packages in Python
Library
A library is a collection of ready-made code (modules and functions) that we can use in our program so that we do not need to write everything from the beginning.
Module and Package
- Module: a single Python file (
.py) that contains functions and variables. Example:math. - Package: a collection of modules kept together in a folder. Example:
pandas.
Types of Libraries
Installing an external library (in Command Prompt / Terminal):
pip install pandas
pip install matplotlib
Importing a Library
We must import a library before using it.
import math # import the whole library
print(math.sqrt(25)) # use as library_name.function()
from math import sqrt # import only one function
print(sqrt(25)) # no need to write 'math.'
import math as m # give a short name (alias)
print(m.sqrt(25))
Popular Libraries
| Library | Purpose |
|---|---|
| math | Mathematical functions |
| random | Generating random numbers and choices |
| Pandas | Working with data and tables, reading and writing CSV files |
| Turtle | Drawing graphics and shapes |
| matplotlib | Drawing charts and graphs (data visualization) |
The math Library
| Function / Value | Meaning | Example | Result |
|---|---|---|---|
math.sqrt(x) | Square root | math.sqrt(49) | 7.0 |
math.pow(x, y) | x to the power y | math.pow(2, 3) | 8.0 |
math.floor(x) | Round down | math.floor(3.7) | 3 |
math.ceil(x) | Round up | math.ceil(3.2) | 4 |
math.factorial(n) | Factorial | math.factorial(5) | 120 |
math.pi | Value of pi | math.pi | 3.141592... |
import math
r = 7
print("Area of circle =", math.pi * r * r)
The random Library
| Function | Meaning | Example |
|---|---|---|
random.random() | Random decimal between 0 and 1 | 0.4837... |
random.randint(a, b) | Random integer from a to b (both included) | random.randint(1, 6) |
random.choice(list) | Picks one random item from a list | random.choice(["red", "green", "blue"]) |
import random
dice = random.randint(1, 6)
print("You got", dice)
4.4 Graphics Using Turtle
Turtle is a Python library used to draw pictures and shapes on the screen. Imagine a small turtle (pen) moving on a drawing board (canvas): wherever it moves, it can draw a line.
Getting Started
import turtle
t = turtle.Turtle() # create (define) a turtle named t
t.forward(100) # move forward and draw
turtle.done() # keep the window open
Note: Do not save your file with the name
turtle.py, because Python will get confused with the library name.
Common Turtle Functions
| Function | Meaning |
|---|---|
forward(n) or fd(n) | Move forward by n steps |
backward(n) or bk(n) | Move backward by n steps |
left(angle) or lt(angle) | Turn left by the given angle (degrees) |
right(angle) or rt(angle) | Turn right by the given angle (degrees) |
penup() | Lift the pen: moves without drawing |
pendown() | Put the pen down: moves and draws |
color("name") | Set the pen (line) colour |
fillcolor("name") | Set the colour used to fill shapes |
begin_fill() / end_fill() | Start and finish the area to be filled |
pensize(n) | Set the thickness of the line |
shape("turtle") | Change the shape of the pointer (arrow, turtle, circle, square, triangle) |
circle(r) | Draw a circle of radius r |
speed(n) | Set drawing speed (1 = slow, 10 = fast) |
goto(x, y) | Move to the position (x, y) |
Example 1: Draw a Square
import turtle
t = turtle.Turtle()
for i in range(4):
t.forward(100)
t.left(90)
turtle.done()
Example 2: Draw a Rectangle
import turtle
t = turtle.Turtle()
for i in range(2):
t.forward(150)
t.left(90)
t.forward(80)
t.left(90)
turtle.done()
Example 3: Draw a Triangle
import turtle
t = turtle.Turtle()
for i in range(3):
t.forward(100)
t.left(120)
turtle.done()
Example 4: Draw a Circle
import turtle
t = turtle.Turtle()
t.circle(60)
turtle.done()
Example 5: Draw a Coloured and Filled Shape
import turtle
t = turtle.Turtle()
t.color("blue") # pen colour
t.fillcolor("yellow") # fill colour
t.pensize(3)
t.begin_fill()
for i in range(4):
t.forward(100)
t.left(90)
t.end_fill()
turtle.done()
Example 6: Move Without Drawing (penup and pendown)
import turtle
t = turtle.Turtle()
t.forward(50) # draws a line
t.penup() # lift the pen
t.forward(50) # moves, no line
t.pendown() # put the pen down
t.forward(50) # draws a line again
turtle.done()
Drawing Any Regular Polygon
The turning angle is 360 ├╖ number of sides.
| Shape | Sides | Turning angle |
|---|---|---|
| Triangle | 3 | 120┬░ |
| Square | 4 | 90┬░ |
| Pentagon | 5 | 72┬░ |
| Hexagon | 6 | 60┬░ |
import turtle
t = turtle.Turtle()
sides = 6
for i in range(sides):
t.forward(80)
t.left(360 / sides)
turtle.done()
4.5 Error Handling
Errors
An error is a mistake in a program that stops it from working correctly.
| Type of error | Meaning | Example |
|---|---|---|
| Syntax error | Rules (grammar) of Python are broken; the program does not run at all | print("Hello" (missing bracket) |
| Runtime error (Exception) | Occurs while the program is running | Dividing by zero |
| Logical error | Program runs but gives a wrong output because of wrong logic | Using + instead of * to find the area |
Exception
An exception is an error that occurs during the execution of a program and stops it suddenly. If we do not handle it, the program crashes.
Common exceptions:
| Exception | Occurs when | Example |
|---|---|---|
ZeroDivisionError | Dividing a number by zero | 10 / 0 |
ValueError | The value has the wrong form | int("abc") |
TypeError | Wrong data type is used | "5" + 3 |
NameError | A variable is not defined | print(x) without creating x |
IndexError | List index is out of range | [1, 2, 3][5] |
FileNotFoundError | The file does not exist | open("abc.txt") for a missing file |
Exception Handling with try-except
We use try and except to catch the error and keep the program running instead of crashing.
try:
# code that may cause an error
except:
# code that runs if an error occurs
Example 1: Division
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Result =", a / b)
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
Example 2: Handling more than one error
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Result =", a / b)
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
except ValueError:
print("Error: Please enter numbers only.")
Example 3: Catching any error
try:
num = int(input("Enter a number: "))
print("Square =", num * num)
except Exception:
print("Something went wrong!")
Difference between Syntax Error and Exception
| Syntax Error | Exception |
|---|---|
| Found before the program runs | Occurs while the program runs |
| Caused by wrong grammar of the language | Caused by wrong values or situations |
| Program cannot start | Program stops in the middle |
Cannot be handled with try-except | Can be handled with try-except |
4.6 File Handling
Concept of File Handling
Variables store data temporarily in memory (RAM), and the data is lost when the program ends. File handling means storing data permanently in a file and reading it again later.
Opening a File
f = open("filename", "mode")
Modes of File Handling
| Mode | Name | Meaning |
|---|---|---|
"r" | Read | Opens the file to read. Gives an error if the file does not exist. |
"w" | Write | Opens the file to write. Creates the file if it does not exist; erases old content if it exists. |
"a" | Append | Opens the file to add data at the end. Creates the file if it does not exist; old content is kept. |
Writing, Appending and Reading a Text File
# 1. Write (creates the file / replaces old content)
f = open("note.txt", "w")
f.write("Hello Nepal\n")
f.close()
# 2. Append (adds at the end)
f = open("note.txt", "a")
f.write("I love Python\n")
f.close()
# 3. Read
f = open("note.txt", "r")
print(f.read())
f.close()
Output:
Hello Nepal
I love Python
Always close the file using
close()after use.
CSV File
CSV stands for Comma Separated Values. It is a simple text file in which data is arranged in rows and columns, with values separated by commas. It can be opened in Excel or Notepad.
Name,Marks
Ram,85
Sita,92
Hari,78
Pandas Library
Pandas is a Python library used to store, analyse and manage data in table form. Its main structure is the DataFrame, which is a table with rows and columns. It makes it very easy to read and write CSV files.
pip install pandas
Writing a CSV File using Pandas
import pandas as pd
data = {
"Name": ["Ram", "Sita", "Hari"],
"Marks": [85, 92, 78]
}
df = pd.DataFrame(data) # create a table (DataFrame)
df.to_csv("student.csv", index=False) # write to the CSV file
print("File saved")
index=False tells Pandas not to write the row numbers (0, 1, 2...) into the file.
Reading a CSV File using Pandas
import pandas as pd
df = pd.read_csv("student.csv") # read the CSV file
print(df)
Output:
Name Marks
0 Ram 85
1 Sita 92
2 Hari 78
Display only one column:
print(df["Name"])
Appending Data to a CSV File using Pandas
import pandas as pd
new = pd.DataFrame({"Name": ["Gita"], "Marks": [88]})
new.to_csv("student.csv", mode="a", header=False, index=False)
mode="a"means append (add at the end).header=Falsestops the column names from being written again.
Summary of Pandas Functions
| Function | Use |
|---|---|
pd.DataFrame(data) | Creates a table from data |
df.to_csv("file.csv", index=False) | Writes (saves) a DataFrame to a CSV file |
pd.read_csv("file.csv") | Reads a CSV file into a DataFrame |
df["column"] | Selects one column |
4.7 Data Visualization
Data visualization means showing data in the form of charts and graphs so that it is easy to understand, compare and analyse.
Matplotlib is a popular Python library for drawing charts. We use its pyplot module.
pip install matplotlib
import matplotlib.pyplot as plt
Common Functions
| Function | Use |
|---|---|
plt.plot() | Draws a line chart |
plt.bar() | Draws a bar graph |
plt.pie() | Draws a pie chart |
plt.title("text") | Adds the title |
plt.xlabel("text") / plt.ylabel("text") | Adds labels to the x-axis / y-axis |
plt.legend() | Shows the legend (label box) |
plt.show() | Displays the chart |
1. Line Chart
Shows change over time (trend).
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [120, 150, 130, 180, 200]
plt.plot(months, sales, marker="o", color="blue")
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
2. Bar Graph
Compares values of different categories.
import matplotlib.pyplot as plt
names = ["Ram", "Sita", "Hari", "Gita"]
marks = [85, 92, 78, 88]
plt.bar(names, marks, color="green")
plt.title("Marks of Students")
plt.xlabel("Student")
plt.ylabel("Marks")
plt.show()
3. Pie Chart
Shows the share (percentage) of each part in a whole.
import matplotlib.pyplot as plt
subjects = ["Maths", "Science", "English", "Computer"]
hours = [8, 6, 5, 4]
plt.pie(hours, labels=subjects, autopct="%1.1f%%")
plt.title("Study Time of a Student")
plt.show()
autopct="%1.1f%%" shows the percentage on each slice.
Which Chart to Use?
| Chart | Best for | Example |
|---|---|---|
| Line chart | Showing change or trend over time | Monthly sales |
| Bar graph | Comparing different categories | Marks of students |
| Pie chart | Showing parts of a whole | Share of study time |
Practical Work
| Task | Program / Action |
|---|---|
| a) Structure of user defined functions | Write functions with parameters and return values (area, factorial, even/odd) |
| b) Install and use packages | pip install pandas matplotlib, then import pandas, import turtle, import matplotlib.pyplot |
| c) Draw shapes and fill colours using Turtle | Draw a circle, rectangle and polygons; use fillcolor, begin_fill, end_fill |
| d) Read and write CSV using Pandas | Use DataFrame, to_csv() and read_csv() |
| e) Plot bar, line and pie charts using matplotlib | Use plt.bar(), plt.plot() and plt.pie() |
Combined Practice Program (Pandas + matplotlib)
import pandas as pd
import matplotlib.pyplot as plt
# 1. Create data and save it in a CSV file
data = {
"Name": ["Ram", "Sita", "Hari", "Gita"],
"Marks": [85, 92, 78, 88]
}
df = pd.DataFrame(data)
df.to_csv("result.csv", index=False)
# 2. Read the CSV file
df = pd.read_csv("result.csv")
print(df)
# 3. Draw a bar graph from the file data
plt.bar(df["Name"], df["Marks"], color="orange")
plt.title("Result of Students")
plt.xlabel("Student")
plt.ylabel("Marks")
plt.show()
Project Work (Syllabus Suggestion)
a) Develop a simple project of your own using libraries, user defined functions and a visualization tool (in IDLE, PyCharm, Jupyter Notebook or Google Colab).
b) Prepare a simple report explaining the process you followed.
Project ideas: Student result analyser, simple quiz game (using random), daily expense tracker with a chart, temperature or sales chart, a turtle-drawing of a house.
Format of the report:
- Title of the project
- Objective (what the project does)
- Libraries and functions used
- Steps followed (planning, coding, testing)
- Output (screenshots)
- Problems faced and conclusion
Quick Revision Points
- Function: a named block of code, created using
def, run when called. - Parameter = in the definition; Argument = value passed in the call;
returnsends back a result. - Local variable: inside the function only. Global variable: can be used anywhere.
- Library = collection of ready-made code; use
importto bring it into the program. - Turtle functions:
forward, backward, left, right, penup, pendown, color, fillcolor, begin_fill, end_fill. - Turning angle of a regular polygon = 360 ├╖ sides.
- Errors: syntax, runtime (exception), logical. Handle exceptions with
try-except. - File modes:
r= read,w= write (overwrites),a= append (adds at the end). - Pandas:
read_csv()reads a CSV file;to_csv()writes one. - matplotlib:
plot()= line,bar()= bar graph,pie()= pie chart; finish withshow().
Important Exam Questions (SEE Style)
A. Very Short Answer Questions (Define / Full form)
- What is a function?
- What is the use of the
defkeyword? - Differentiate parameter and argument (one line each).
- What is a library in Python?
- What is the use of the
importstatement? - What is Turtle?
- What is an exception?
- What is a CSV file? Write its full form.
- Write the use of
pd.read_csv(). - What is the use of
matplotlib? - Name the three modes of file handling.
- What is the use of
penup()?
B. Short Answer Questions
- Differentiate between local and global variables.
- Differentiate between syntax error and exception.
- Differentiate between parameter and argument with an example.
- Write any three advantages of using functions.
- What is the difference between
printandreturn? - Explain the three modes of file handling (
r,w,a). - Write the use of
tryandexcept. - Write any four Turtle functions and their uses.
- Explain the line chart, bar graph and pie chart with their uses.
- Write the difference between
import mathandfrom math import sqrt. - Name any two functions of the
randomlibrary and write their use.
C. Long Answer / Program Writing Questions
- What is a user defined function? Explain with its syntax, parameters, arguments and return statement with an example.
- What is exception handling? Explain
try-exceptwith an example. - What is file handling? Explain the modes of file handling with examples.
- How are Pandas and matplotlib used in Python? Explain with examples.
D. Application-Type (Programs)
-
Write a program using a function to find the area of a circle (use
math.pi).import math def area(r): return math.pi * r * r print("Area =", area(7)) -
Write a program using a function to check whether a number is even or odd.
def check(n): if n % 2 == 0: return "Even" return "Odd" print(check(9)) -
Write a program to draw a square filled with red colour using Turtle.
import turtle t = turtle.Turtle() t.fillcolor("red") t.begin_fill() for i in range(4): t.forward(100) t.left(90) t.end_fill() turtle.done() -
Write a program that takes two numbers and divides them, handling the error if the second number is zero.
try: a = int(input("Enter a: ")) b = int(input("Enter b: ")) print(a / b) except ZeroDivisionError: print("Cannot divide by zero") -
Write a program to create a CSV file named
book.csvwith the columnsTitleandPriceusing Pandas.import pandas as pd data = {"Title": ["Maths", "Science"], "Price": [250, 300]} df = pd.DataFrame(data) df.to_csv("book.csv", index=False) -
Write a program to read
book.csvand display its content.import pandas as pd df = pd.read_csv("book.csv") print(df) -
Write a program to draw a bar graph of the marks of 3 students using matplotlib.
import matplotlib.pyplot as plt names = ["Ram", "Sita", "Hari"] marks = [80, 90, 75] plt.bar(names, marks) plt.title("Marks") plt.show() -
Write a program to append a line "Good luck" to a file
msg.txt.f = open("msg.txt", "a") f.write("Good luck\n") f.close()
Multiple Choice Questions (MCQs)
1. Which keyword is used to create a function in Python? a) function b) define c) def d) fun Answer: c) def
2. The values written in the function call are called ______. a) Parameters b) Arguments c) Variables d) Modules Answer: b) Arguments
3. Which statement sends a value back from a function? a) print b) input c) return d) import Answer: c) return
4. A variable created inside a function is a ______ variable. a) Global b) Local c) Constant d) Static Answer: b) Local
5. Which statement is used to bring a library into a program? a) include b) using c) import d) get Answer: c) import
6. Which library is used to draw shapes using a pen? a) math b) turtle c) random d) pandas Answer: b) turtle
7. Which Turtle function lifts the pen so that no line is drawn? a) pendown() b) penup() c) stop() d) color() Answer: b) penup()
8. To draw a regular hexagon, the turtle turns by ______ degrees at each corner. a) 90 b) 72 c) 60 d) 120 Answer: c) 60
9. Dividing a number by zero causes ______. a) SyntaxError b) ZeroDivisionError c) NameError d) IndexError Answer: b) ZeroDivisionError
10. Which block is used to catch an error? a) if-else b) for-while c) try-except d) def-return Answer: c) try-except
11. Which file mode adds data at the end of a file without deleting the old data? a) r b) w c) a d) x Answer: c) a
12. Which Pandas function reads a CSV file? a) read_csv() b) open_csv() c) get_csv() d) load() Answer: a) read_csv()
13. CSV stands for ______. a) Computer Separated Values b) Comma Separated Values c) Code Style Values d) Column Sorted View Answer: b) Comma Separated Values
14. Which matplotlib function draws a pie chart? a) plt.plot() b) plt.bar() c) plt.pie() d) plt.chart() Answer: c) plt.pie()
15. Which chart is best for showing the change of sales over months? a) Pie chart b) Line chart c) Table d) Text Answer: b) Line chart
Summary
| Topic | Key Point |
|---|---|
| Functions | def, parameters, arguments, return, local and global scope |
| Libraries | import math, random, turtle, pandas, matplotlib |
| Turtle | forward, backward, left, right, penup, pendown, color, fillcolor |
| Error handling | Syntax, runtime and logical errors; try-except |
| File handling | Modes r, w, a |
| CSV with Pandas | read_csv() and to_csv() |
| Data visualization | plot() line, bar() bar graph, pie() pie chart |
Notes prepared as per the CDC Computer Science (Grade 9тАУ10) curriculum for SEE. Published on The Study Hub Nepal: https://thestudyhubnepal.web.app