Python Programming
Python Programming
Q.1) 1 mark
1. Indentation: Indentation in Python is used to define code blocks and control flow. It is
essential for the language's readability and structure.
2. Printing List Elements:
Python
Python
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
6. remove() Method: Removes the first occurrence of a specified element from a list.
7. Lambda Function to Add 10:
Python
add_10 = lambda x: x + 10
Python
Specific Topics
17. clock() and gmtime(): clock() returns the processor time, while gmtime() returns a
tuple representing the current time in UTC.
18. Exception Handling Syntax:
Python
try:
# code that might raise an exception
except ExceptionType as e:
# code to handle the exception
finally:
# code that always executes
Use code with caution.
1. Packages
A package is a collection of Python modules that are organized into a directory structure. This allows
for better organization and reusability of code.
Creating a Package:
Example:
Python
# package_name/module1.py
def function1():
print("This is function1 from module1")
# package_name/module2.py
def function2():
print("This is function2 from module2")
# main.py
import package_name.module1
import package_name.module2
package_name.module1.function1()
package_name.module2.function2()
2. Tuple Functions
Anonymous functions are functions defined without a name using the lambda keyword. They are
often used for simple, one-time functions.
Example:
Python
add = lambda x, y: x + y
result = add(10, 20)
print(result) # Output: 30
4. Loops
Python
count = 0
while count < 5:
print("Count:", count)
count += 1
Python
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
5. Input/Output Operations
Input:
Python
name = input("Enter your name: ")
print("Hello, " + name + "!")
Output:
Python
print("Hello, world!")
Python
# Reading the entire file
with open("file.txt", "r") as f:
content = f.read()
print(content)
7. Dictionary Methods
Python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
Python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2
print(intersection_set) # Output: {3}
9. Statements
• continue: Skips the rest of the current iteration and moves to the next iteration.
• if: Executes a block of code if a condition is true.
• if-else: Executes one block of code if a condition is true, and another block if it's false.
• break: Exits a loop.
Python
x = int(input("Enter the base: "))
y = int(input("Enter the exponent: "))
result = x ** y
print("Result:", result)
Python
num = int(input("Enter a number: "))
sum_of_divisors = 0
for i in range(1, num):
if num % i == 0:
sum_of_divisors += i
if sum_of_divisors == num:
print(num, "is a
perfect number")
else:
print(num, "is not a perfect number")
13. seek() and tell()
Python
my_list = [1, 2, 3, 4, 5]
sliced_list = my_list[1:4] # Elements from index 1 to 3 (exclusive)
print(sliced_list) # Output: [2, 3, 4]
Tuples are ordered collections, meaning the elements maintain their position and can be accessed by
index.
Python
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero")
Python
my_string = "hello"
print(my_string[-1]) # Output: o
20. Identifiers
Identifiers are names given to variables, functions, classes, and modules. They must start with a letter
or underscore and can contain letters, digits, and underscores.
(Q.3)&(Q.4) 4 marks
1. Program to accept a string from user and display the string in reverse order eliminating the
letter ‘s’:
python
Copy code
# Reverse string and remove 's'
def reverse_remove_s(string):
return ''.join([char for char in string[::-1] if char.lower() !=
's'])
python
Copy code
class AgeException(Exception):
def __init__(self, age):
self.age = age
super().__init__(f"Age {age} is less than 18.")
def check_age(age):
if age < 18:
raise AgeException(age)
else:
print("Age is acceptable.")
try:
age = int(input("Enter age: "))
check_age(age)
except AgeException as e:
print(e)
3. Program to check if a string contains only a certain set of characters (a-z, A-Z, 0-9):
python
Copy code
import re
def is_valid_string(s):
return bool(re.match('^[a-zA-Z0-9]+$', s))
python
Copy code
def add_ing_ly(string):
if len(string) >= 3:
if string.endswith('ing'):
return string + 'ly'
else:
return string + 'ing'
return string
python
Copy code
from collections import Counter
for d in data:
counter[d['item']] += d['amount']
print(counter)
python
Copy code
import datetime
now = datetime.datetime.now()
print("Year:", year(now))
print("Month:", month(now))
print("Day:", day(now))
print("Time:", time(now))
python
Copy code
def swap_first_two_chars(s1, s2):
return s2[:2] + s1[2:], s1[:2] + s2[2:]
python
Copy code
N = int(input("Enter a number: "))
powers_of_two = list(map(lambda x: 2 ** x, range(N+1)))
for i in range(len(powers_of_two)):
print(f"2 raised to {i} is {powers_of_two[i]}")
python
Copy code
def read_file(filename):
with open(filename, 'r') as file:
return file.read()
python
Copy code
def count_vowels_consonants(string):
vowels = 'aeiouAEIOU'
v_count = c_count = 0
for char in string:
if char.isalpha():
if char in vowels:
v_count += 1
else:
c_count += 1
return v_count, c_count
11. Program to print dictionary where keys are numbers between 1 and 15 and values are the
square of keys:
python
Copy code
squares = {i: i**2 for i in range(1, 16)}
print(squares)
python
Copy code
def count_upper_lower(string):
upper_count = lower_count = 0
for char in string:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
return upper_count, lower_count
python
Copy code
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
python
Copy code
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
python
Copy code
def check_key(dictionary, key):
return key in dictionary
Check2 = Check1
Check3 = Check1[:]
Check2[0] = 'Code'
Check3[1] = 'Mcq'
count = 0
if c[0] == 'Code':
count += 1
if c[1] == 'Mcq':
count += 10
print(count)
output: 11
b) counter = {}
def addToCounter(country):
if country in counter:
counter[country] += 1
else:
counter[country] = 1
addToCounter('China')
addToCounter('Japan')
addToCounter('china')
print(len(counter))
output: 3
c) a = True
b = False
c = False
if not a or b:
print(1)
print(3)
else:
print(4)
output: 3
for i in range(x):
l.append(i * i)
print(l)
f1(2)
f1(3)
output: [0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]
e) X=5
def f1():
global X
X=4
global X
return a + b + X
f1()
total = f2(1, 2)
print(total)
output: 7
f) def f(x):
print("hello")
if b == 0:
print("NO")
return
return f(a, b)
return f1
@f
return a % b
f(4, 0)
output: hello
NO
g) sum = 0
sum += i
print(sum)
output: 40
h) count = 1
def doThis():
global count
count += 1
doThis()
print(count)
output: 4