Class 10 Computer Science Programming in Python Notes and Important Questions
Loading notes…
Notes for Class 10 Programming in Python (Computer Science) are shown above.
Class 10 Programming in Python Notes (Computer Science)
Chapter 4 : Programming in Python Chapter 4 : Programming in Python (16 Teaching Hours) Theory Marks : 12 Unit Weightage : 24% (highest) Subject : Computer Science, Class 10 4.1 Revision of the Basics of Python 4.1 Revision of the Basics of Python Introduction to Python Introduction to Python Python is a high-level, easy-to-read programming language widely used for general-purpose programming, data analysis, web development and artificial intelligence. It uses simple English-like syntax and indentation (spacing) instead of curly braces to define blocks of code, which makes it beginner-friendly. Variables Variables A variable is a named location in memory used to store a value that can change during program execution. In Python, a variable does not need its type to be declared in advance - it is created the moment a value is assigned to it. Example : Example : name = "Sujata" age = 15 height = 5.4 Constants Constants A constant is a value that is not meant to change during the execution of a program. Python does not have a strict built-in constant type, but by convention, programmers write constant names in capital letters to show they should not be changed. Example : Example : PI = 3.14159 MAX_MARKS = 100 Variable names must start with a letter or underscore, not a digit - Variable names are case-sensitive ( Age and age are different) - Python keywords (like if, for, while) cannot be used as variable names -
Data Types Data Types Data Type Data Type Meaning Meaning Example Example int Whole numbers (integers) 10, -5, 2082 float Decimal (floating-point) numbers 3.14, -0.5 str Text / string of characters "Kathmandu" bool Logical value - only True or False True, False Operators Operators Input and Output Input and Output The input() function is used to take data from the user (keyboard), and the print() function is used to display output on the screen. Data received through input() is always treated as text (string) by default and must be converted if a number is needed. Example : Example : name = input("Enter your name: ") age = int(input("Enter your age: ")) print("Hello", name, "you are", age, "years old") Conditional Statements Conditional Statements Conditional statements allow a program to make decisions and execute different blocks of code depending on whether a condition is True or False. Example : Example : marks = 75 if marks >= 90: print("Grade A+") elif marks >= 75: print("Grade A") Arithmetic operators Arithmetic operators - + (add), - (subtract), * (multiply), / (divide), // (floor division), % (modulus/remainder), ** (exponent/power) - Relational (comparison) operators Relational (comparison) operators - == (equal to), != (not equal to), >, <, >=, <= - Logical operators Logical operators - and, or, not - Assignment operators Assignment operators - =, +=, -=, *=, /= -
else: print("Below A") Loops Loops Loops are used to repeat a block of code multiple times, without writing the same statement again and again. for loop example : for loop example : for i in range(1, 6): print("Number:", i) while loop example : while loop example : count = 1 while count <= 5: print("Count:", count) count += 1 The range(start, stop, step) function is commonly used with for loops to generate a sequence of numbers. If step is omitted, it defaults to 1. range() with a step - example : range() with a step - example : for i in range(2, 11, 2): # 2, 4, 6, 8, 10 print(i) Common Built-in Functions Common Built-in Functions Function Function Purpose Purpose print() Displays output on the screen input() Takes input from the user (as text) len() Returns the number of items/characters in a sequence type() Returns the data type of a value int(), float(), str() Converts a value to int, float or text respectively range() Generates a sequence of numbers, commonly used in loops for loop for loop - repeats a block a fixed/known number of times or over a sequence (like a range or a list) - while loop while loop - repeats a block as long as a given condition remains True -
Remember : Remember : In Python, indentation (usually 4 spaces) is not just a style choice - it is how Python identifies which statements belong inside a loop, if-block or function. Wrong indentation causes an error. 4.2 User-defined Functions and Passing Parameters 4.2 User-defined Functions and Passing Parameters Function Concept Function Concept A function is a named, reusable block of code that performs a specific task. Instead of writing the same set of instructions repeatedly, we write it once inside a function and simply "call" that function whenever the task needs to be performed. Defining Functions Defining Functions A user-defined function is created using the def keyword, followed by the function name and parentheses. Syntax : Syntax : def function_name(): # block of code statement(s) Calling Functions Calling Functions Once a function is defined, it can be executed (run) simply by writing its name followed by parentheses, wherever it is needed in the program. Example : Example : def greet(): print("Welcome to Computer Science!") greet() # calling/invoking the function Parameters and Arguments Parameters and Arguments A parameter parameter is a variable listed inside the parentheses in a function's definition, acting as a placeholder for the value that will be received. An argument argument is the actual value passed into the function when it is called. Passing Parameters Passing Parameters Example : Example :
def greet(name): # 'name' is a parameter print("Hello,", name) greet("Priya") # "Priya" is the argument Return Values Return Values The return keyword is used inside a function to send a result/value back to the place where the function was called, so that value can be stored or used further. Example : Example : def add(a, b): return a + b result = add(5, 3) print(result) # Output: 8 Functions With / Without Parameters Functions With / Without Parameters Type Type Description Description Example call Example call Without parameters Performs a fixed task, no external input needed greet() With parameters Accepts input values to work with greet("Priya") Exam tip : Exam tip : A function without return gives back the special value None. Use return whenever the result needs to be used later in the program. Main program calls with argument add(a, b) return a + b returns result Fig 4.0 - How control passes to a function and a value returns back 4.3 Libraries and Packages 4.3 Libraries and Packages Concept of Library Concept of Library A library is a collection of pre-written, ready-to-use functions and code that programmers can use directly in their own programs, instead of writing everything from scratch. This saves time and reduces errors.
Concept of Package Concept of Package A package is a way of organising related modules/libraries together into a single folder structure, making large collections of code easier to manage, install and reuse. Importing Libraries Importing Libraries The import keyword is used to bring a library's functions into a Python program so they can be used. Syntax / Example : Syntax / Example : import math print(math.sqrt(25)) # Output: 5.0 import pandas as pd # imported with a short alias 'pd' Using Python Libraries Using Python Libraries Library Library Common Use Common Use math Mathematical functions (square root, power, etc.) turtle Drawing graphics and shapes pandas Handling and analysing tabular data random Generating random numbers 4.4 Graphics Using Turtle 4.4 Graphics Using Turtle Introduction to Turtle Graphics Introduction to Turtle Graphics Turtle graphics is a way of creating drawings and patterns on screen by giving movement commands to a small onscreen "turtle" (an arrow/pointer) that leaves a trail as it moves - similar to steering a pen across paper. Turtle Module Turtle Module The turtle module is Python's built-in library for turtle graphics. It must be imported before it can be used. Example : Example : import turtle t = turtle.Turtle() Commands for Movement Commands for Movement
Command Command Action Action forward(x) Moves the turtle forward by x units backward(x) Moves the turtle backward by x units right(angle) Turns the turtle clockwise by the given angle left(angle) Turns the turtle anticlockwise by the given angle penup() Lifts the pen so moving does not draw a line pendown() Lowers the pen so moving draws a line Drawing Basic Shapes Drawing Basic Shapes Example - drawing a square : Example - drawing a square : import turtle t = turtle.Turtle() for i in range(4): t.forward(100) t.right(90) turtle.done() Fig 4.1 - Output of the square-drawing turtle program above Creating Simple Graphics / Patterns Creating Simple Graphics / Patterns By repeating movement and turning commands inside a loop with different angles, turtle graphics can be used to create polygons, stars and other repeating geometric patterns - a popular way to practise loops visually. 4.5 Error Handling 4.5 Error Handling Errors in Python Errors in Python An error is a problem in a program that prevents it from running correctly. Python errors are broadly of two kinds: syntax errors syntax errors (mistakes in the code's structure, caught before the program runs) and runtime errors runtime errors (problems that occur while the program is actually executing).
Exceptions Exceptions An exception is a runtime error that Python detects during execution and which, if not handled, stops the program immediately and displays an error message. Types of Common Errors Types of Common Errors Error Type Error Type Occurs When Occurs When ZeroDivisionError Dividing a number by zero ValueError A value of the wrong type is used (e.g. converting "abc" to int) NameError Using a variable that has not been defined TypeError Performing an operation on incompatible data types IndexError Trying to access a list/string position that does not exist try and except try and except The try block lets us test a block of code for errors, and the except block lets us handle/respond to the error gracefully instead of the whole program crashing. Handling Exceptions Handling Exceptions Example : Example : try: num = int(input("Enter a number: ")) result = 100 / num print("Result:", result) except ZeroDivisionError: print("Error: Cannot divide by zero!") except ValueError: print("Error: Please enter a valid number!") Exam tip : Exam tip : Without error handling, a single bad input (like dividing by zero) crashes the whole program. try...except lets the program show a friendly message and keep running instead. The finally Block The finally Block An optional finally block can be added after try/except. Code inside finally always runs, whether or not an error occurred - commonly used for clean-up actions such as closing a file.
Example : Example : try: num = int(input("Enter a number: ")) print(100 / num) except ZeroDivisionError: print("Cannot divide by zero!") finally: print("Program finished running.") Worked Example - Combining Functions, Loops and Error Handling Worked Example - Combining Functions, Loops and Error Handling Program - average of marks entered by the user : Program - average of marks entered by the user : def calculate_average(marks_list): return sum(marks_list) / len(marks_list) marks = [] for i in range(3): try: m = int(input("Enter marks: ")) marks.append(m) except ValueError: print("Please enter a number!") print("Average:", calculate_average(marks)) This program shows several Class 10 topics working together: a for loop to repeat input three times, a user-defined function to calculate the average, and try/except to handle an invalid (non-numeric) entry. 4.6 File Handling Using Pandas Library 4.6 File Handling Using Pandas Library Introduction to Pandas Introduction to Pandas Pandas is a popular Python library used for working with structured/tabular data - similar to working with a spreadsheet or a database table, but through Python code. It makes reading, analysing and manipulating data much easier.
Pandas Library Pandas Library Pandas must be imported before use, and is conventionally given the short alias pd. Example : Example : import pandas as pd DataFrame DataFrame A DataFrame is the main data structure used in Pandas - a two-dimensional, table-like structure with labelled rows and columns, very similar to a table in a database or a sheet in Excel. Creating DataFrames Creating DataFrames Example : Example : import pandas as pd data = {'Name': ['Anisha', 'Bikash'], 'Marks': [88, 76]} df = pd.DataFrame(data) print(df) Reading and Manipulating Data Reading and Manipulating Data Example - reading a CSV file : Example - reading a CSV file : import pandas as pd df = pd.read_csv("students.csv") print(df.head()) # shows the first 5 rows print(df['Marks'].mean()) # average of the Marks column Basic File/Data Handling Using Pandas Basic File/Data Handling Using Pandas Example - basic statistics : Example - basic statistics : pd.read_csv("file.csv") - reads data from a CSV file into a DataFrame - pd.read_excel("file.xlsx") - reads data from an Excel file into a DataFrame - df.head() - displays the first few rows of a DataFrame - df.to_csv("file.csv") - saves a DataFrame back to a CSV file - df.shape - shows the number of rows and columns in a DataFrame - df['column'].sum(), .mean(), .max(), .min() - quick statistics on one column of data -
import pandas as pd df = pd.read_csv("students.csv") print("Highest:", df['Marks'].max()) print("Lowest:", df['Marks'].min()) print("Average:", df['Marks'].mean()) 4.7 Introduction to Data Visualization 4.7 Introduction to Data Visualization Concept of Data Visualization Concept of Data Visualization Data visualization is the practice of presenting data graphically - using charts, graphs and plots - so that patterns, trends and relationships in the data can be understood quickly and easily, rather than reading through raw numbers. Importance of Data Visualization Importance of Data Visualization Presenting Data Using Charts/Graphs Presenting Data Using Charts/Graphs Chart Type Chart Type Best Used For Best Used For Bar chart Comparing values across different categories Line chart Showing a trend or change over time Pie chart Showing proportions/percentages of a whole Basic Visualization Using Python/Pandas Basic Visualization Using Python/Pandas Pandas works closely with the matplotlib library to turn a DataFrame's data directly into a chart with just one or two lines of code. Example : Example : import pandas as pd import matplotlib.pyplot as plt data = {'Subject': ['Math', 'Science', 'English'], 'Marks': [85, 78, 90]} df = pd.DataFrame(data) Makes large amounts of data easier and faster to understand - Helps identify trends, patterns and outliers at a glance - Makes it easier to compare different sets of data - Supports clearer, more convincing presentations and reports -
df.plot(x='Subject', y='Marks', kind='bar') plt.show() Remember : Remember : Pandas is for organising and analysing data (in rows/columns); Matplotlib (used together with Pandas) is for turning that data into visual charts. Chapter Summary Chapter Summary Glossary - Key Terms at a Glance Glossary - Key Terms at a Glance Term Term One-line meaning One-line meaning Variable Named memory location that stores a value that can change Function Reusable, named block of code that performs a task Parameter Placeholder variable in a function's definition Argument Actual value passed into a function when called Library Collection of pre-written, reusable code Turtle Python module for drawing graphics with movement commands Exception Runtime error detected while a program is executing DataFrame Pandas' table-like structure with rows and columns Data visualization Presenting data graphically as charts/graphs Python programs are built from variables, constants, data types, operators, input/output, conditional statements and loops. - Functions (with def) let code be written once and reused; parameters pass values in, and return sends a result back out. - Libraries and packages provide ready-made code; import brings them into a program. - The turtle module draws graphics on screen by moving and turning a pointer. - try...except catches runtime errors (exceptions) so a program can fail gracefully instead of crashing. - The pandas library organises data into DataFrames and can read/write files such as CSV. - Data visualization turns raw data into bar, line or pie charts to make it easier to understand, often using pandas with matplotlib. -
Important Questions (Exam Practice) Important Questions (Exam Practice) Based on the SEE Computer Science question pattern (MCQ 1 mark, Short 2 marks, Long 4 marks) - this unit carries the highest weight (12 marks), so expect at least one programming/output-based question. True or False True or False 1. A variable's data type must be declared before assigning it a value in Python. (False) 2. A function can be called multiple times after it is defined once. (True) 3. The except block runs only when an error occurs inside the try block. (True) 4. The turtle.forward() command turns the turtle without moving it. (False) 5. A DataFrame can only have one column. (False) Fill in the Blanks Fill in the Blanks 1. The ____________ keyword is used to define a function in Python. 2. The ____________ function is used to take input from the user. 3. A ____________ error occurs when a number is divided by zero. 4. The ____________ module is used for drawing turtle graphics. 5. The main data structure in Pandas is called a ____________. Very Short / 1-Mark Type Very Short / 1-Mark Type 1. What is a variable? 2. Define function. 3. What is the use of the import keyword? 4. Write the full form/meaning of DataFrame. 5. Name any two turtle movement commands. Short Answer / 2-Mark Type Short Answer / 2-Mark Type 1. Differentiate between parameter and argument. 2. What is the difference between a for loop and a while loop? 3. Differentiate between syntax error and runtime error (exception). 4. What is the use of try and except in Python? 5. Differentiate between a library and a package.
Long Answer / 4-Mark Type Long Answer / 4-Mark Type 1. Write a Python function that takes two numbers as parameters and returns their sum. Explain how it works. 2. Explain the turtle module with a program to draw a square. 3. What is exception handling? Write a program using try and except to handle division by zero. 4. What is a DataFrame in Pandas? Explain with a short example how to create one. 5. What is data visualization? Explain its importance with an example chart type. Study tip : Study tip : For programming questions, always write code line by line and add a one-line comment/explanation for the tricky parts - examiners give partial marks even if the program is not 100% perfect, as long as the logic is clearly shown.
Related chapters in Computer Science: Class 10 Multimedia notes, Class 10 AI and Contemporary Technologies notes, Class 10 Computer Network and Communication notes.
Important Questions
Study the following Python program and answer the questions:
def find_square(n):
return n * n
num = int(input("Enter a number: "))
result = find_square(num)
print("Square =", result)What is the name of the user-defined function?
What is the parameter of the function?
What will be the output if the user enters 6?
Modify the function to return the cube of the given number.
Study the following Python program and answer the questions:
def check_number(n):
if n > 0:
return "Positive"
elif n < 0:
return "Negative"
else:
return "Zero"
num = int(input("Enter a number: "))
print(check_number(num))a. What is the name of the user-defined function?
b. What is the parameter of the function?
c. What will be the output if the user enters -8?
d. Rewrite the function to return "Even" if the number is even and "Odd" if it is odd.
Study the following Python program and answer:
import pandas as pd
data = {'Name':['Asha','Bikash','Chandra'],
'Marks':[45,72,60]}
df = pd.DataFrame(data)
print(df[df['Marks']>=60])
a. Write the output of the above Python code.
b. Modify the code to display students who scored less than 60.
Study the following Python program and answer the questions:
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")a. What is the purpose of the % operator?
b. What will be the output if the user enters 15?
c. Modify the program to display whether the number is positive or negative.
d. What type of statement is if...else?
Study the following Python program and answer the questions:
def calculate(a, b):
return a + b
try:
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
result = calculate(x, y)
print("Result:", result)
except ValueError:
print("Invalid input")
a. What is the purpose of the calculate() function?
b. Identify the parameters used in the function.
c. What happens if the user enters 5 and 7?
d. What happens if the user enters a non-numeric value?
Study the following Python program and answer the questions:
numbers = [10, 20, 30, 40, 50]
total = 0
for n in numbers:
total = total + n
print("Total =", total)a. What is the name of the list used in the program?
b. How many elements are present in the list?
c. What will be the output of the program?
d. Modify the program to calculate and display the average of the numbers.
24 more questions locked
Upgrade to a paid plan to view all important questions
This page covers Programming in Python, chapter 4 of 5 in the Class 10 Computer Science syllabus set by the National Examination Board (NEB). 28 important questions for this chapter are available, each with a full solution.
For numerical and derivation-based chapters like this one, working through past NEB questions is usually more useful than re-reading notes alone — try solving each important question above before checking the solution, then compare your working step by step.