Python Study Guide
A comprehensive guide for the Jury Exam
Unit I: Introduction to Python
Print()
1. Write a Python program to print "Hello World!!".
Code:
print("Hello World!!")Logic:
Uses the built-in `print()` function to display the string "Hello World!!" on the console.
Print()
2. Write a program to print multiple variables together in a single line.
Code:
name = "Alex"
age = 25
city = "New York"
print("Name:", name, "Age:", age, "City:", city)Logic:
The `print()` function can take multiple arguments. It automatically adds a space between each argument when printing.
Print()
3. Write a program to print multiple items separated by a custom separator.
Code:
print("apple", "banana", "cherry", sep=" | ")Logic:
The `sep` parameter of the `print()` function specifies the separator to use between items, overriding the default space.
Print()
4. Write a program to print multiple statements on the same line using the `end` parameter.
Code:
print("Hello", end=" ")
print("World!")Logic:
The `end` parameter specifies what to print at the end. By default, it's a newline character (`\n`). Setting it to a space prevents a line break.
Print()
5. Write a Python program to print "Welcome to Python Lab!!".
Code:
print("Welcome to Python Lab!!")Logic:
A simple use of the `print()` function to display a specific string.
Print()
6. Write a program to print "Hello World", "Welcome to Python Lab", and "Welcome to Python Programming" on separate lines.
Code:
print("Hello World")
print("Welcome to Python Lab")
print("\nWelcome to Python Programming")Logic:
Each `print()` call ends with a newline by default. The `\n` in the third string adds an extra blank line before the text.
Print()
7. Write a program to print a multi-line string.
Code:
print("""This is line 1
This is line 2
This is line 3""")Logic:
Triple quotes (`"""` or `'''`) create a multi-line string literal, preserving all line breaks within it.
Print()
8. Write a program that prints "My name is Mohit." in a new line and then prints your name in a new line.
Code:
my_name = "Your Name"
print("My name is Mohit.")
print(my_name)Logic:
Two separate `print()` calls ensure each string is printed on its own line.
Print()
9. Write a program that prints "The capital of France is Paris." in a new line and then prints the capital of your country in a new line.
Code:
country_capital = "New Delhi"
print("The capital of France is Paris.")
print(country_capital)Logic:
Similar to the previous problem, this uses two `print()` statements for separate lines of output.
Input()
10. Write a program that prompts the user to enter their age and prints out their age in years, months, and days.
Code:
age_in_years = int(input("Enter your age in years: "))
age_in_months = age_in_years * 12
age_in_days = age_in_years * 365
print(f"Your age in months is approximately: {age_in_months}")
print(f"Your age in days is approximately: {age_in_days}")Logic:
It takes an integer input for age, then performs simple multiplication to calculate the approximate age in months and days.
Input()
11. Write a program that prompts the user to enter a number and prints out its square root.
Code:
import math
num = float(input("Enter a number: "))
if num >= 0:
print(f"The square root is {math.sqrt(num)}")
else:
print("Cannot calculate square root of a negative number.")Logic:
Uses the `math.sqrt()` function after importing the `math` module. It includes a check to prevent errors with negative numbers.
Input()
12. Write a program that prompts the user to enter two numbers and prints out their sum, difference, product, and quotient.
Code:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(f"Sum: {num1 + num2}")
print(f"Difference: {num1 - num2}")
print(f"Product: {num1 * num2}")
if num2 != 0:
print(f"Quotient: {num1 / num2}")
else:
print("Cannot divide by zero.")Logic:
Performs basic arithmetic operations. Includes a check to avoid a division-by-zero error.
Input()
13. Write a program to perform average of five numbers using input() function and type conversion concept.
Code:
n1=float(input("1: ")); n2=float(input("2: ")); n3=float(input("3: ")); n4=float(input("4: ")); n5=float(input("5: "))
average = (n1 + n2 + n3 + n4 + n5) / 5
print(f"Average is: {average}")Logic:
Takes five numbers as input, converts them to floats, sums them up, and divides by 5 to find the average.
Input()
14. Write a Python program to take the user's name as input and display a greeting message.
Code:
name = input("Enter your name: ")
print(f"Hello, {name}! Welcome.")Logic:
Uses an f-string to embed the user's input directly into a greeting message.
Input()
15. Write a Python program to take two numbers as input and print their sum.
Code:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(f"The sum is: {num1 + num2}")Logic:
Reads two inputs, converts them to floats, and prints their sum.
Input()
16. Write a Python program to take three numbers as input and calculate their average.
Code:
n1=float(input("1: ")); n2=float(input("2: ")); n3=float(input("3: "))
average = (n1 + n2 + n3) / 3
print(f"The average is: {average}")Logic:
Takes three numbers, sums them, and divides by 3.
Input()
17. Write a program that prompts the user to enter a number and find the area of rectangle.
Code:
length = float(input("Enter length: "))
width = float(input("Enter width: "))
area = length * width
print(f"The area of the rectangle is: {area}")Logic:
Calculates area using the formula `length * width`.
Input()
18. Write a program that prompts the user to enter their weight and height and calculates their BMI.
Code:
weight_kg = float(input("Enter weight in kg: "))
height_m = float(input("Enter height in meters: "))
if height_m > 0:
bmi = weight_kg / (height_m ** 2)
print(f"Your BMI is: {bmi:.2f}")
else:
print("Height must be positive.")Logic:
Calculates Body Mass Index using the formula `weight / height^2`. Formats the output to two decimal places.
Input()
19. Write a program that prompts the user to enter a number and find the area of Circle.
Code:
import math
radius = float(input("Enter the radius of the circle: "))
if radius >= 0:
area = math.pi * (radius ** 2)
print(f"The area is: {area:.2f}")
else:
print("Radius cannot be negative.")Logic:
Calculates circle area using `π * r^2`. Uses `math.pi` for the value of Pi.
Type()
20. Write a Python program to check and display the type of an integer variable.
Code:
my_int = 100
print(f"Value: {my_int}, Type: {type(my_int)}")Logic:
The built-in `type()` function returns the data type of the variable passed to it.
Type()
21. Write a Python program to check and display the type of a float variable.
Code:
my_float = 3.14
print(f"Value: {my_float}, Type: {type(my_float)}")Logic:
Demonstrates that `type()` correctly identifies floating-point numbers as `<class 'float'>`.
Type()
22. Write a Python program to check and display the type of a string variable.
Code:
my_string = "Hello"
print(f"Value: {my_string}, Type: {type(my_string)}")Logic:
Shows that `type()` identifies text as `<class 'str'>`.
Type()
23. Write a Python program to check and display the type of an integer variable.
Code:
my_integer = 42
print(f"Value: {my_integer}, Type: {type(my_integer)}")Logic:
A repetition of problem 20, confirming the behavior of `type()` on integers.
Type()
24. Write a Python program to take input from the user and display the value and its type.
Code:
user_input = input("Enter any value: ")
print(f"You entered: '{user_input}', Type: {type(user_input)}")Logic:
Highlights that the `input()` function always returns data as a string (`str`), regardless of what the user types.
Type()
25. Write a Python program to take a number as input, convert it to an integer, and display its type before and after conversion.
Code:
num_str = input("Enter a number: ")
print(f"Before conversion: '{num_str}', Type: {type(num_str)}")
num_int = int(num_str)
print(f"After conversion: {num_int}, Type: {type(num_int)}")Logic:
Demonstrates explicit type conversion. The `int()` function is used to convert the input string into an integer.
Type()
26. Write a Python program to perform an arithmetic operation and display the type of the result.
Code:
result = 10 / 5
print(f"Result of 10 / 5 is: {result}, Type: {type(result)}")
result2 = 10 + 5.5
print(f"Result of 10 + 5.5 is: {result2}, Type: {type(result2)}")Logic:
Shows how Python determines the result's type. Division (`/`) always produces a float. Operations involving a float also result in a float.
Unit II: Data Structures & Functions
List Operations
1. Write a Python program to perform following operations on List: Creating, Accessing Elements, Index, Slicing, Adding and Removing Elements.
Code:
my_list = [10, "hello", 3.14]
print(f"List: {my_list}")
print(f"Element at index 1: {my_list[1]}")
print(f"Index of 'hello': {my_list.index('hello')}")
print(f"Slice [1:3]: {my_list[1:3]}")
my_list.append(True)
print(f"After append: {my_list}")
my_list.remove(3.14)
print(f"After remove: {my_list}")Logic:
Demonstrates creating a list, accessing elements by index, finding an element's index, slicing, adding with `append()`, and removing with `remove()`.
List Operations
2. Write a Python program to perform following operations on List: Creating, Accessing, Index, Slicing, Modifying and Searching elements.
Code:
fruits = ["apple", "banana", "cherry"]
print(f"Original: {fruits}")
fruits[1] = "blackberry"
print(f"Modified: {fruits}")
if "apple" in fruits:
print("Apple is in the list.")Logic:
Shows how to modify an element by its index (`fruits[1] = ...`) and how to check for an element's existence using the `in` keyword.
List Operations
3. Write a Python program to perform following operations on List: Creating, Accessing, Index, Slicing, Sorting and Reversing elements.
Code:
numbers = [4, 1, 7, 3, 9]
print(f"Original: {numbers}")
numbers.sort()
print(f"Sorted: {numbers}")
numbers.reverse()
print(f"Reversed: {numbers}")Logic:
The `.sort()` method sorts the list in-place (modifies the original). The `.reverse()` method reverses the order of elements in-place.
Tuple Operations
4. Write a Python program to perform following operations on Tuple: Creating, Accessing, Index, Slicing, Concatenation.
Code:
my_tuple = (10, 20, "Python")
tuple2 = (40, 50)
print(f"Tuple: {my_tuple}")
print(f"Element at index 2: {my_tuple[2]}")
concatenated = my_tuple + tuple2
print(f"Concatenated: {concatenated}")Logic:
Tuples are immutable. Accessing and slicing are similar to lists. The `+` operator creates a new tuple by concatenating existing ones.
Tuple Operations
5. Write a Python program to perform following operations on Tuple: Creating, Accessing, Index, Slicing, Deleting.
Code:
my_tuple = (1, 2, 3)
print(f"Tuple before deletion: {my_tuple}")
del my_tuple
# print(my_tuple) # This would cause a NameError because the tuple is gone.Logic:
You cannot delete individual elements from a tuple because they are immutable. The `del` keyword deletes the entire tuple object from memory.
Tuple Operations
6. Write a Python program to perform following operations on Tuple: Creating, Accessing, Index, Slicing, Nested Tuples.
Code:
nested_tuple = (1, ('a', 'b'), 3)
print(f"Nested tuple: {nested_tuple}")
print(f"Accessing nested element 'a': {nested_tuple[1][0]}")Logic:
A tuple can contain other tuples. To access elements in a nested tuple, you use multiple indices, one after the other.
Set Operations
7. Write a Python program to perform following operations on Set: Creating, Accessing, Index, Slicing, Order.
Code:
my_set = {10, 20, 30, 10}
print(f"Set: {my_set}")
print("Cannot access by index. Sets are unordered. Iterating instead:")
for item in my_set:
print(item)Logic:
Sets are unordered collections of unique elements (the duplicate `10` is ignored). You cannot use an index or slicing to access elements; you must iterate through them.
Set Operations
8. Write a Python program to perform following operations on Set: Creating, Accessing, Adding, Removing.
Code:
my_set = {"apple", "banana"}
my_set.add("cherry")
print(f"After add: {my_set}")
my_set.remove("banana")
print(f"After remove: {my_set}")Logic:
`.add()` adds a single element. `.remove()` deletes an element but will raise an error if the element doesn't exist. `.discard()` is a safer alternative that doesn't raise an error.
String Operations
9. Write a Python program to perform following operations on String: Creating, Accessing Characters, Slicing, Index, Length.
Code:
my_string = "Hello World"
print(f"String: {my_string}")
print(f"Char at index 1: {my_string[1]}")
print(f"Slice [6:]: {my_string[6:]}")
print(f"Index of 'W': {my_string.index('W')}")
print(f"Length: {len(my_string)}")Logic:
Strings are immutable sequences. They support indexing, slicing, the `.index()` method to find a character's position, and the `len()` function to get their length.
Dictionary Operations
10. Write a program to remove a word from a dictionary.
Code:
my_dict = {"brand": "Ford", "model": "Mustang"}
print(f"Original: {my_dict}")
del my_dict["model"]
print(f"After del: {my_dict}")Logic:
The `del` keyword removes a key-value pair from a dictionary using its key.
Dictionary Operations
11. Write a program to check if a word is in a dictionary.
Code:
my_dict = {"name": "John", "age": 30}
if "age" in my_dict:
print("'age' is a key in the dictionary.")
if "city" not in my_dict:
print("'city' is not a key in the dictionary.")Logic:
The `in` keyword checks for the presence of a key in a dictionary. It returns `True` if the key exists and `False` otherwise.
Dictionary Operations
12. Write a program to add a word and its meaning to a dictionary.
Code:
glossary = {"apple": "A fruit"}
print(f"Before: {glossary}")
glossary["python"] = "A programming language."
print(f"After: {glossary}")Logic:
A new key-value pair is added by assigning a value to a new key. If the key already exists, its value will be updated.
More List Operations
13. Write a program to print the elements at a specific range of indices in a list.
Code:
my_list = ['a', 'b', 'c', 'd', 'e', 'f']
print(my_list[2:5]) # Prints elements at index 2, 3, 4Logic:
Slicing `[start:end]` extracts a sub-list from the `start` index up to, but not including, the `end` index.
More List Operations
14. Write a program to print all the elements in a list except the first three elements.
Code:
my_list = [10, 20, 30, 40, 50, 60]
print(my_list[3:])Logic:
Omitting the `end` index in a slice (`[3:]`) means "go from index 3 to the end of the list".
More List Operations
15. Write a program to print all the elements in a list except the last three elements.
Code:
my_list = [10, 20, 30, 40, 50, 60]
print(my_list[:-3])Logic:
A negative index in a slice counts from the end. `[:-3]` means "from the beginning up to the last 3 elements".
More List Operations
16. Write a program to check if two lists are equal.
Code:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = [1, 3, 2]
print(f"list1 == list2: {list1 == list2}") # True
print(f"list1 == list3: {list1 == list3}") # FalseLogic:
The `==` operator checks if two lists have the exact same elements in the exact same order.
More String and Set Methods
17. Write a Python program to perform following String methods: lower(), upper(), capitalize(), reverse().
Code:
my_string = "pYtHoN iS fUn"
print(f"Lower: {my_string.lower()}")
print(f"Upper: {my_string.upper()}")
print(f"Capitalize: {my_string.capitalize()}")
print(f"Reversed: {my_string[::-1]}")Logic:
`.lower()`, `.upper()`, and `.capitalize()` return new, modified strings. There is no `.reverse()` method for strings; slicing `[::-1]` is the common way to reverse one.
More String and Set Methods
18. Write a program to find the union, intersection, and difference of two sets.
Code:
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
print(f"Union (all elements from both): {set_a.union(set_b)}")
print(f"Intersection (common elements): {set_a.intersection(set_b)}")
print(f"Difference (elements in A but not B): {set_a.difference(set_b)}")Logic:
Sets have built-in methods for standard mathematical set operations. Union combines all unique elements. Intersection finds common elements. Difference finds elements present in the first set but not the second.
Built-in Functions and Libraries
19. Write a program to find the maximum and minimum of a list of numbers.
Code:
numbers = [15, 2, 49, 8, -5]
print(f"Max: {max(numbers)}")
print(f"Min: {min(numbers)}")Logic:
The built-in functions `max()` and `min()` find the largest and smallest items in an iterable like a list.
Built-in Functions and Libraries
20. Write a program to sort a list.
Code:
my_list = ["banana", "apple", "cherry"]
my_list.sort() # Sorts in-place
print(my_list)Logic:
The `list.sort()` method sorts the list in-place (alphabetically for strings, numerically for numbers). The `sorted()` function is an alternative that returns a new sorted list without changing the original.
Built-in Functions and Libraries
21. Write a program to calculate the square root of a number using the `math.sqrt()` function.
Code:
import math
num = 25
print(math.sqrt(num))Logic:
The `math` module must be imported to use its functions. `math.sqrt()` calculates the square root of a non-negative number.
Built-in Functions and Libraries
22. Write a program to calculate the sine of an angle using the `math.sin()` function.
Code:
import math
angle_degrees = 90
angle_radians = math.radians(angle_degrees)
print(f"Sine of 90 degrees is: {math.sin(angle_radians)}")Logic:
Trigonometric functions in the `math` module, like `math.sin()`, require the angle to be in radians. `math.radians()` is used to convert from degrees.
Built-in Functions and Libraries
23. Write a program to get the current time.
Code:
import datetime
now = datetime.datetime.now()
print(f"Current date and time: {now}")
print(f"Formatted time: {now.strftime('%H:%M:%S')}")Logic:
Uses the `datetime` module. `datetime.datetime.now()` gets the current local date and time. The `.strftime()` method formats this object into a readable string.
Built-in Functions and Libraries
24. Write a program to delete a directory.
Code:
import os
dir_name = "temp_dir_to_delete"
# First, create the directory to ensure it exists
# if not os.path.exists(dir_name):
# os.makedirs(dir_name)
# Now, delete it
# os.rmdir(dir_name)
print(f"The command 'os.rmdir("{dir_name}")' would delete the empty directory.")Logic:
The `os` module interacts with the operating system. `os.rmdir()` removes an **empty** directory. The code is commented out to prevent accidental deletion during execution.
More Dictionary and String Methods
25. Write a Python program to perform following operations on Dictionary: Creating, Accessing, Ordered, Adding, Removing.
Code:
# Creating
student = {"name": "Alice", "age": 21}
print(f"Created: {student}")
# Accessing
print(f"Name: {student['name']}")
# Adding
student["major"] = "Computer Science"
print(f"After adding major: {student}")
# Removing
del student["age"]
print(f"After removing age: {student}")
# Dictionaries are ordered since Python 3.7Logic:
Shows the fundamental dictionary operations: creation with `{}`, accessing with `[]`, adding/updating by key assignment, and removing with `del`.
More Dictionary and String Methods
26. Write a Python program to perform following operations on Dictionary: Creating, Accessing, Duplicate, Accessing Keys, Accessing Values.
Code:
my_dict = {"brand": "Ford", "model": "Mustang", "year": 1964, "year": 2022}
# Note the duplicate "year" key
print(f"Dictionary: {my_dict}")
print(f"Keys: {my_dict.keys()}")
print(f"Values: {my_dict.values()}")Logic:
Duplicate keys are not allowed in a dictionary; the last value assigned to a key is the one that is kept. The `.keys()` and `.values()` methods provide views of all the keys and values in the dictionary.
More Dictionary and String Methods
27. Write a Python program to perform following String methods: lower(), upper(), capitalize(), isalpha(), isdigit().
Code:
s1 = "HelloWorld"
s2 = "12345"
s3 = "Hello 123"
print(f"'s1' isalpha?: {s1.isalpha()}") # True
print(f"'s2' isdigit?: {s2.isdigit()}") # True
print(f"'s3' isalpha?: {s3.isalpha()}") # False (contains space and digits)
print(f"'s3' isdigit?: {s3.isdigit()}") # False (contains space and letters)Logic:
`.isalpha()` checks if all characters in the string are alphabetic. `.isdigit()` checks if all characters are digits. Both return `False` if the string contains any other types of characters (like spaces or symbols).
Unit III: Conditional Statements
Comparisons
1. Write a program to find the greatest among two numbers.
Code:
num1 = 10
num2 = 20
if num1 > num2:
print(f"{num1} is greater.")
elif num2 > num1:
print(f"{num2} is greater.")
else:
print("They are equal.")Logic:
An `if-elif-else` structure compares the two numbers and prints the appropriate result based on which condition is met first.
Comparisons
2. Write a program to find the greatest among 3 numbers.
Code:
num1, num2, num3 = 10, 20, 5
if num1 >= num2 and num1 >= num3:
greatest = num1
elif num2 >= num1 and num2 >= num3:
greatest = num2
else:
greatest = num3
print(f"The greatest is {greatest}")Logic:
Uses `if-elif-else` with the `and` logical operator to check if a number is greater than or equal to both of the other two numbers.
Number Properties
3. Write a program to check if a number is even or odd.
Code:
num = 7
if num % 2 == 0:
print("Even")
else:
print("Odd")Logic:
Uses the modulo operator (`%`). If a number divided by 2 has a remainder of 0, it's even; otherwise, it's odd.
Number Properties
4. Write a program to check if a number is prime or not.
Code:
num = 13
is_prime = True
if num > 1:
# Check for factors from 2 up to the square root of num
for i in range(2, int(num**0.5) + 1):
if (num % i) == 0:
is_prime = False
break
else:
is_prime = False
if is_prime:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")Logic:
A number is prime if it's greater than 1 and only divisible by 1 and itself. The code checks for factors from 2 up to the square root of the number for efficiency. If a factor is found, a flag `is_prime` is set to `False`.
Number Properties
5. Write a program to find if a year is a leap year or not.
Code:
year = 2024
if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0):
print(f"{year} is a Leap Year")
else:
print(f"{year} is not a Leap Year")Logic:
Implements the leap year rule: a year is a leap year if it is divisible by 4, unless it is divisible by 100 but not by 400.
Practical Scenarios
6. Write a program to identify student grades based on marks.
Code:
marks = 85
if marks >= 90: grade = "A"
elif marks >= 80: grade = "B"
elif marks >= 70: grade = "C"
elif marks >= 50: grade = "D"
elif marks >= 40: grade = "Pass"
else: grade = "Fail"
print(f"With {marks} marks, the grade is: {grade}")Logic:
A cascading `if-elif-else` structure checks mark ranges from highest to lowest to assign a grade. The first condition that evaluates to true determines the grade.
Practical Scenarios
7. Write a program to check students' grades and provide feedback.
Code:
grade = 'A'
if grade == 'A': feedback = "Outstanding"
elif grade == 'B': feedback = "Excellent"
elif grade == 'C': feedback = "Very Good"
elif grade == 'D': feedback = "Good"
elif grade == 'E': feedback = "Satisfactory"
else: feedback = "Needs Improvement"
print(f"Feedback for Grade {grade}: {feedback}")Logic:
Uses `if-elif-else` to match a specific grade character to a predefined feedback string.
Practical Scenarios
8. Write a Python program to check if a number is positive or negative.
Code:
num = -5
if num > 0: print("Positive")
elif num < 0: print("Negative")
else: print("Zero")Logic:
Compares the number to 0 to determine if it's positive, negative, or exactly zero.
Practical Scenarios
9. Write a Python program to find the largest of two numbers.
Code:
num1, num2 = 100, 50
if num1 > num2: print(f"{num1} is largest")
elif num2 > num1: print(f"{num2} is largest")
else: print("Both numbers are equal")Logic:
A simple `if-elif-else` block to compare two numbers and handle the case where they are equal.
Practical Scenarios
10. Write a Python program to check if a person is eligible to vote (age ≥ 18).
Code:
age = 20
if age >= 18: print("Eligible to vote")
else: print("Not eligible to vote")Logic:
A simple conditional check to see if the age is greater than or equal to 18.
Practical Scenarios
11. Write a Python program to check whether a given string is a palindrome or not.
Code:
s = "madam"
if s == s[::-1]:
print(f"'{s}' is a Palindrome")
else:
print(f"'{s}' is not a Palindrome")Logic:
A string is a palindrome if it reads the same forwards and backwards. This is checked efficiently by comparing the original string to its reversed version, created using the slice `[::-1]`.
Practical Scenarios
12. Write a Python program to check whether a given number is a palindrome or not.
Code:
num = 121
if str(num) == str(num)[::-1]:
print(f"{num} is a Palindrome")
else:
print(f"{num} is not a Palindrome")Logic:
The easiest way to check if a number is a palindrome is to convert it to a string and use the same string reversal logic as the previous problem.
Practical Scenarios
13. Write a python program that will check for traffic light conditions.
Code:
light = "green"
if light == "green": print("Car is allowed to go")
elif light == "yellow": print("Car has to wait")
elif light == "red": print("Car has to stop")
else: print("Unrecognized signal")Logic:
An `if-elif-else` chain to match the traffic light color string to the correct driving action.
Practical Scenarios
14. Write a program to check whether the number divisible by 5 and 11.
Code:
num = 55
if num % 5 == 0 and num % 11 == 0:
print(f"{num} is divisible by both 5 and 11")
else:
print(f"{num} is not divisible by both 5 and 11")Logic:
Uses the `and` logical operator to ensure the number is divisible by both numbers (i.e., the remainder is 0 for both divisions).
Practical Scenarios
15. Modify the student grades program to calculate percentage and grade from five subject marks.
Code:
s1, s2, s3, s4, s5 = 90, 95, 88, 76, 82
total = s1+s2+s3+s4+s5
percentage = (total / 500) * 100
if not (0 <= percentage <= 100):
grade = "Error: Invalid percentage"
elif percentage >= 85: grade = "Excellent"
elif percentage >= 75: grade = "Very Good"
elif percentage >= 60: grade = "Good"
elif percentage >= 45: grade = "Pass"
else: grade = "Fail"
print(f"Percentage: {percentage:.2f}%, Grade: {grade}")Logic:
First, it calculates the total and percentage. Then, it uses an `if-elif-else` chain, starting with a check for invalid percentages, to assign a grade.
Practical Scenarios
16. Write a program to check whether a number is positive, negative, or zero.
Code:
num = 0
if num > 0: print("Positive")
elif num < 0: print("Negative")
else: print("Zero")Logic:
Repetition of problem 8. Compares the number to 0 to determine its category.
Practical Scenarios
17. Write a program to check whether a character is a vowel, consonant, digit, or special symbol.
Code:
char = '%'
# Convert to lowercase for easier comparison
char_lower = char.lower()
if 'a' <= char_lower <= 'z':
if char_lower in 'aeiou':
print(f"'{char}' is a Vowel")
else:
print(f"'{char}' is a Consonant")
elif '0' <= char <= '9':
print(f"'{char}' is a Digit")
else:
print(f"'{char}' is a Special Symbol")Logic:
It first checks if the character is an alphabet. If so, it checks if it's a vowel. If not an alphabet, it checks if it's a digit. If it's neither, it's classified as a special symbol.
Practical Scenarios
18. Write a program to check if a person is eligible to apply for a driving license.
Code:
age = 18
test_passed = True
if age >= 18:
if test_passed:
print("Eligible for a driving license.")
else:
print("Not eligible: Must pass the written test.")
else:
print("Not eligible: Must be at least 18 years old.")Logic:
Uses a nested `if` statement. The primary condition (age) is checked first. Only if that is true is the secondary condition (test passed) checked.
Practical Scenarios
19. Write a program to find the largest of three numbers using nested if.
Code:
num1, num2, num3 = 10, 30, 20
if num1 >= num2:
if num1 >= num3:
largest = num1
else:
largest = num3
else:
if num2 >= num3:
largest = num2
else:
largest = num3
print(f"The largest number is {largest}")Logic:
This demonstrates a nested `if` approach. The outer `if` compares the first two numbers to find a temporary larger one. The inner `if` then compares that temporary larger number with the third number to find the final largest value.
Practical Scenarios
20. Write a program to check if a given year is a century year.
Code:
year = 2000
if year % 100 == 0:
print(f"{year} is a century year.")
else:
print(f"{year} is not a century year.")Logic:
A century year is a year that is evenly divisible by 100. The modulo operator (`%`) is used to check if the remainder of the division is 0.