[Go to site: main page, start]

0% found this document useful (0 votes)
156 views4 pages

Python Programs for ICSE Class 9

The document contains 15 Python practice programs designed for ICSE Class 9, covering essential programming concepts such as input/output, control structures, functions, and data structures. Each program addresses a specific task, including user input, calculations, and data manipulation. The examples provided serve as practical exercises for students to enhance their programming skills.

Uploaded by

cbec.uk23
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
156 views4 pages

Python Programs for ICSE Class 9

The document contains 15 Python practice programs designed for ICSE Class 9, covering essential programming concepts such as input/output, control structures, functions, and data structures. Each program addresses a specific task, including user input, calculations, and data manipulation. The examples provided serve as practical exercises for students to enhance their programming skills.

Uploaded by

cbec.uk23
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ICSE Class 9 - Python Practice Programs

These 15 programs cover key topics: input/output, if-else, loops, functions, lists, tuples, dictionaries,
and strings.

1. Input and Display User Details


name = input("Enter your name: ")
age = int(input("Enter your age: "))
subject = input("Enter your favorite subject: ")

print("Hello", name, "! You are", age, "years old and you like", subject)

2. Largest of Two Numbers


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

if a > b:
print(a, "is greater.")
elif b > a:
print(b, "is greater.")
else:
print("Both numbers are equal.")

3. Grade Calculator
marks = int(input("Enter marks: "))

if marks >= 90:


grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 40:
grade = "D"
else:
grade = "Fail"

print("Grade:", grade)

4. Electricity Bill Calculator


last_reading = int(input("Enter last meter reading: "))
current_reading = int(input("Enter current meter reading: "))
rate = float(input("Enter rate per unit: "))

units = current_reading - last_reading


bill = units * rate

print("Units consumed:", units)


print("Total bill: Rs.", bill)

5. Simple Calculator
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
op = input("Enter operator (+, -, *, /): ")

if op == '+':
print("Result:", num1 + num2)
elif op == '-':
print("Result:", num1 - num2)
elif op == '*':
print("Result:", num1 * num2)
elif op == '/':
print("Result:", num1 / num2)
else:
print("Invalid operator")

6. Check Prime Number


n = int(input("Enter a number: "))

if n > 1:
for i in range(2, n):
if n % i == 0:
print(n, "is not a prime number")
break
else:
print(n, "is a prime number")
else:
print("Number is not prime")

7. Fibonacci Series
n = int(input("Enter number of terms: "))
a = 0
b = 1
print("Fibonacci Series:")
for i in range(n):
print(a)
c = a + b
a = b
b = c

8. Function - Area of Circle


def calculate_area(radius):
area = 3.1416 * radius * radius
return area

r = float(input("Enter radius: "))


print("Area of circle is:", calculate_area(r))
9. Function with Default Argument
def greet(name, msg="Welcome to Robotics and AI"):
print("Hello", name, "-", msg)

greet("Riya")
greet("Arjun", "Keep learning Python!")

10. List Operations


students = ["Ravi", "Anita", "Karan"]
print("Original list:", students)

[Link]("Meena")
[Link](1, "Sohan")
[Link]("Karan")
[Link]()

print("Updated list:", students)

11. Tuple and Conversion


fruits = ("apple", "banana", "mango")
print("Original tuple:", fruits)

fruit_list = list(fruits)
fruit_list.append("orange")
fruits = tuple(fruit_list)

print("Updated tuple:", fruits)

12. Dictionary of Student Marks


students = {"Ravi": 78, "Anita": 85, "Karan": 92}

for name in students:


print(name, "scored", students[name])

topper = max(students, key=[Link])


print("Topper is", topper, "with", students[topper], "marks")

13. Count Vowels in a String


text = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0

for ch in text:
if ch in vowels:
count = count + 1

print("Number of vowels:", count)


14. Even and Odd Numbers from a List
numbers = input("Enter numbers separated by space: ").split()
numbers = [int(n) for n in numbers]

even = []
odd = []

for n in numbers:
if n % 2 == 0:
[Link](n)
else:
[Link](n)

print("Even numbers are:", even)


print("Odd numbers are:", odd)

15. Bonus Calculator


def calculate_bonus(salary, years):
if years > 5:
bonus = salary * 0.05
else:
bonus = 0
return bonus

salary = float(input("Enter salary: "))


years = int(input("Enter years of service: "))

bonus = calculate_bonus(salary, years)


print("Bonus amount is: Rs.", bonus)

Common questions

Powered by AI

Functions with optional parameters possess flexibility by allowing certain arguments to be omitted during function calls, with defaults provided in such cases. Conversely, functions with mandatory parameters require that all parameters be supplied with values. The 'calculate_bonus()' function requires both 'salary' and 'years' as mandatory parameters to compute the bonus accurately, reflecting constraints where each parameter has a definable impact on the outcome. Thus, the thorough understanding of parameter necessity and utility greatly influences function design based on intended operations and flexibility .

Dictionaries allow associating student names directly with their respective marks, facilitating rapid data retrieval through key-value access. The demonstrated loop over keys provides an efficient means to output all student scores, while utilizing the 'max()' function highlights the topper by comparing values directly, showcasing dictionaries' capability for efficient data extraction and comparison. This structure enhances readability and reduces computational complexity compared to other structures like lists, proving invaluable for dynamic datasets requiring fast lookups and manipulations .

The grade calculator provides a straightforward grading scale with clear boundaries: A for marks 90 and above, B for 75 to 89, and so forth. However, its effectiveness may be limited due to the lack of granularity within each grade band and potential for jumps in scores creating disproportionate differences in grades. Additionally, it doesn't account for factors such as subjective assessment elements or a cumulative basis across different tests. While adequate for quick assessments, it may not fully capture student performance nuances, suggesting a need for refinement to improve accuracy and fairness in educational contexts .

The program correctly compares two integers to determine the larger. However, it assumes valid integer input without verification, risking unexpected behavior with invalid or non-numeric input. Implementing input validation and error handling through try-except blocks would enhance robustness by capturing and addressing invalid inputs, thus preventing runtime errors and ensuring accurate comparisons regardless of user input behavior .

The Fibonacci series function uses an iterative algorithm which initializes the first two numbers, 'a' and 'b', to 0 and 1, respectively. It then enters a loop that runs for 'n' iterations, computing the next number as the sum of 'a' and 'b', updating 'a' and 'b' accordingly. This approach is efficient because it maintains constant space complexity by using a few variables to hold the current and previous numbers, avoiding the overhead of recursive calls or additional storage structures, thereby directly computing the series values in a single pass through the loop .

To handle negative meter readings in the electricity bill calculator, the program should incorporate error handling using if-statements to check if 'last_reading' or 'current_reading' are negative. If a negative reading is found, the program can output an error message and terminate or prompt the user to enter valid readings. This modification is crucial as negative readings are not feasible in real scenarios and could lead to incorrect calculations, maintaining the integrity of the bill generation logic .

The program checks each number's parity using the modulus operator '%'. If a number 'n' returns a remainder of 0 when divided by 2, it is classified as even and added to the 'even' list; otherwise, it is added to the 'odd' list. While list comprehensions are not utilized in the example given, their use could simplify this task by embedding the conditional logic directly within a single line, enhancing readability and conciseness. For instance, 'even = [n for n in numbers if n % 2 == 0]' would create the even list without explicit loops, showcasing Python's powerful syntactical features .

Lists in Python are mutable, allowing changes such as adding, removing, or modifying elements, as shown when new students are appended or inserted into the list and the list is sorted. Conversely, tuples are immutable, meaning their size and elements cannot be changed directly once defined. The document illustrates converting a tuple to a list to perform modifications such as adding "orange", and then converting it back to a tuple to effectively "update" it, demonstrating tuple immutability .

Default arguments promote flexibility by allowing functions to be called with fewer arguments than the defined parameters while assigning predefined values to omitted arguments. In the document, the function 'greet' utilizes a default argument for 'msg', set to "Welcome to Robotics and AI". This enables the function to be called with just a 'name', automatically using the default message, such as 'greet("Riya")'. However, users can override the default by providing a specific message as demonstrated in 'greet("Arjun", "Keep learning Python!")', offering customization without redundancy in function calls .

The Python code checks if a number is prime by first ensuring it is greater than 1, as numbers less than or equal to 1 cannot be prime. The 'for' loop iterates from 2 to the number minus one, checking divisibility of the number by each iterator 'i'. If the number is divisible by 'i', it breaks the loop and prints that the number is not prime, indicating the presence of a factor other than 1 and itself. If the loop completes without finding a divisor, the number is declared prime, as it has no divisors other than 1 and itself .

You might also like