Programming in Python

    Programming in Python

    Reading Mode:

    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.1Revision of the Basics of Python
    4.2User Defined Functions: scope, parameter, argument, return type, passing
    4.3Library and Packages in Python (importing standard libraries; Math, random, Pandas, Turtle, matplotlib)
    4.4Graphics Using Turtle
    4.5Error Handling: errors and exceptions, try-except blocks
    4.6File Handling (modes: read, write, append) and Reading/Writing CSV files using Pandas
    4.7Data 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 (Name and name are different).

    Input and Output

    StatementUse
    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 typeMeaningExample
    intWhole numberx = 10
    floatDecimal numbery = 3.5
    strText (string)name = "Ram"
    boolTrue or Falseok = True
    listOrdered, changeable collection[10, 20, 30]
    dictKey-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

    TypeOperatorsExample
    Arithmetic+ - * / // % **7 // 2 gives 3, 7 % 2 gives 1, 2 ** 3 gives 8
    Relational== != > < >= <=5 > 3 gives True
    Logicaland, 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

    GroupFunctionExampleResult
    Stringlen()len("Nepal")5
    upper()"nepal".upper()NEPAL
    lower()"NEPAL".lower()nepal
    center()"Nepal".center(11, "*")***Nepal***
    Numeric / Mathsum()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 def keyword.

    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

    TermMeaning
    ParameterThe variable written in the function definition (inside the brackets). It receives a value.
    ArgumentThe 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
    

    print vs return: print only displays a value on the screen. return gives 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

    FormExample
    No parameter, no returndef hello(): print("Hi")
    With parameter, no returndef square(n): print(n * n)
    No parameter, with returndef pi(): return 3.14
    With parameter and returndef square(n): return n * n

    Scope of Variables

    Scope means the part of the program where a variable can be used.

    Local variableGlobal variable
    Created inside a functionCreated outside all functions
    Can be used only inside that functionCan be used anywhere in the program
    Destroyed when the function endsExists 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))
    
    LibraryPurpose
    mathMathematical functions
    randomGenerating random numbers and choices
    PandasWorking with data and tables, reading and writing CSV files
    TurtleDrawing graphics and shapes
    matplotlibDrawing charts and graphs (data visualization)

    The math Library

    Function / ValueMeaningExampleResult
    math.sqrt(x)Square rootmath.sqrt(49)7.0
    math.pow(x, y)x to the power ymath.pow(2, 3)8.0
    math.floor(x)Round downmath.floor(3.7)3
    math.ceil(x)Round upmath.ceil(3.2)4
    math.factorial(n)Factorialmath.factorial(5)120
    math.piValue of pimath.pi3.141592...
    import math
    r = 7
    print("Area of circle =", math.pi * r * r)
    

    The random Library

    FunctionMeaningExample
    random.random()Random decimal between 0 and 10.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 listrandom.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

    FunctionMeaning
    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.

    ShapeSidesTurning angle
    Triangle3120┬░
    Square490┬░
    Pentagon572┬░
    Hexagon660┬░
    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 errorMeaningExample
    Syntax errorRules (grammar) of Python are broken; the program does not run at allprint("Hello" (missing bracket)
    Runtime error (Exception)Occurs while the program is runningDividing by zero
    Logical errorProgram runs but gives a wrong output because of wrong logicUsing + 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:

    ExceptionOccurs whenExample
    ZeroDivisionErrorDividing a number by zero10 / 0
    ValueErrorThe value has the wrong formint("abc")
    TypeErrorWrong data type is used"5" + 3
    NameErrorA variable is not definedprint(x) without creating x
    IndexErrorList index is out of range[1, 2, 3][5]
    FileNotFoundErrorThe file does not existopen("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 ErrorException
    Found before the program runsOccurs while the program runs
    Caused by wrong grammar of the languageCaused by wrong values or situations
    Program cannot startProgram stops in the middle
    Cannot be handled with try-exceptCan 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

    ModeNameMeaning
    "r"ReadOpens the file to read. Gives an error if the file does not exist.
    "w"WriteOpens the file to write. Creates the file if it does not exist; erases old content if it exists.
    "a"AppendOpens 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=False stops the column names from being written again.

    Summary of Pandas Functions

    FunctionUse
    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

    FunctionUse
    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?

    ChartBest forExample
    Line chartShowing change or trend over timeMonthly sales
    Bar graphComparing different categoriesMarks of students
    Pie chartShowing parts of a wholeShare of study time

    Practical Work

    TaskProgram / Action
    a) Structure of user defined functionsWrite functions with parameters and return values (area, factorial, even/odd)
    b) Install and use packagespip install pandas matplotlib, then import pandas, import turtle, import matplotlib.pyplot
    c) Draw shapes and fill colours using TurtleDraw a circle, rectangle and polygons; use fillcolor, begin_fill, end_fill
    d) Read and write CSV using PandasUse DataFrame, to_csv() and read_csv()
    e) Plot bar, line and pie charts using matplotlibUse 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:

    1. Title of the project
    2. Objective (what the project does)
    3. Libraries and functions used
    4. Steps followed (planning, coding, testing)
    5. Output (screenshots)
    6. 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; return sends back a result.
    • Local variable: inside the function only. Global variable: can be used anywhere.
    • Library = collection of ready-made code; use import to 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 with show().

    Important Exam Questions (SEE Style)

    A. Very Short Answer Questions (Define / Full form)

    1. What is a function?
    2. What is the use of the def keyword?
    3. Differentiate parameter and argument (one line each).
    4. What is a library in Python?
    5. What is the use of the import statement?
    6. What is Turtle?
    7. What is an exception?
    8. What is a CSV file? Write its full form.
    9. Write the use of pd.read_csv().
    10. What is the use of matplotlib?
    11. Name the three modes of file handling.
    12. What is the use of penup()?

    B. Short Answer Questions

    1. Differentiate between local and global variables.
    2. Differentiate between syntax error and exception.
    3. Differentiate between parameter and argument with an example.
    4. Write any three advantages of using functions.
    5. What is the difference between print and return?
    6. Explain the three modes of file handling (r, w, a).
    7. Write the use of try and except.
    8. Write any four Turtle functions and their uses.
    9. Explain the line chart, bar graph and pie chart with their uses.
    10. Write the difference between import math and from math import sqrt.
    11. Name any two functions of the random library and write their use.

    C. Long Answer / Program Writing Questions

    1. What is a user defined function? Explain with its syntax, parameters, arguments and return statement with an example.
    2. What is exception handling? Explain try-except with an example.
    3. What is file handling? Explain the modes of file handling with examples.
    4. How are Pandas and matplotlib used in Python? Explain with examples.

    D. Application-Type (Programs)

    1. 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))
      
    2. 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))
      
    3. 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()
      
    4. 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")
      
    5. Write a program to create a CSV file named book.csv with the columns Title and Price using Pandas.

      import pandas as pd
      data = {"Title": ["Maths", "Science"], "Price": [250, 300]}
      df = pd.DataFrame(data)
      df.to_csv("book.csv", index=False)
      
    6. Write a program to read book.csv and display its content.

      import pandas as pd
      df = pd.read_csv("book.csv")
      print(df)
      
    7. 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()
      
    8. 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

    TopicKey Point
    Functionsdef, parameters, arguments, return, local and global scope
    Librariesimport math, random, turtle, pandas, matplotlib
    Turtleforward, backward, left, right, penup, pendown, color, fillcolor
    Error handlingSyntax, runtime and logical errors; try-except
    File handlingModes r, w, a
    CSV with Pandasread_csv() and to_csv()
    Data visualizationplot() 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