0% found this document useful (0 votes)
14 views27 pages

Python Programming Questions Guide

Uploaded by

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

Python Programming Questions Guide

Uploaded by

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

SANFORT WORLD

SCHOOL

MORADABAD

COMPUTER SCIENCE
PROGRAMMING QUESTIONS

SUBMITTED TO: SUBMITTED BY:


MUDIT SIR SAKSHAM NARANG
CLASS:12TH
CERTIFICATE

This is to clarify that the content of this


project by SAKSHAM NARANG is the bona fide
work of him submitted to SANFORT WORLD
SCHOOL MORADABAD for consideration in
partial fulfilment of the requirement of CBSE
.
The original research work was carried out
by him under the guidance of Mr. Mudit in the
academic year [Link] the basis of
the declaration made by him I recommend
this project report for evaluation.

SUBJECT TEACHER:
Mr. Mudit
ACKNOWLEDGEMENT
I would like to express my heartfelt gratitude
to all those who contributed to the
completion of this project. This endeavour
wouldn’t have seen possible without the
support , guidance and encouragement I
received from various individuals and
organisations.
First and foremost , I extend my sincere
thanks to Mr. Mudit for their invaluable
guidance , patience and expertise
throughout this project. Their mentorship
and constant support in shaping our ideas
and steering us in the right direction.
Thank you everyone who directly or
indirectly supported me during this project.
Your contributions are truly invaluable and
greatly appreciated.

Saksham Narang
Class: 12th

Q1. Write a Python program to calculate the factorial of a


given number using recursion.
Code:
# Factorial of a number using recursion

def recur_factorial(n):

if n == 1:

return n

else:

return n*recur_factorial(n-1)

num = 7

# check if the number is negative

if num < 0:

print("Sorry, factorial does not exist for negative numbers")

elif num == 0:

print("The factorial of 0 is 1")

else:

print("The factorial of", num, "is", recur_factorial(num))

Output:

Q2. Create a program to check if a given string is a


palindrome.

Code:
# Program to check if a string is palindrome or not

my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison

my_str = my_str.casefold()

# reverse the string

rev_str = reversed(my_str)

# check if the string is equal to its reverse

if list(my_str) == list(rev_str):

print("The string is a palindrome.")

else:

print("The string is not a palindrome.")

Output:

Q3. Write a Python function to find the greatest common


divisor (GCD) of two numbers.

Code:
# Python program to find H.C.F of two numbers

# define a function

def compute_hcf(x, y):

# choose the smaller number

if x > y:

smaller = y

else:

smaller = x

for i in range(1, smaller+1):

if((x % i == 0) and (y % i == 0)):

hcf = i

return hcf

num1 = 54

num2 = 24

print("The H.C.F. is", compute_hcf(num1, num2))

Output:
Q4. Implement a program to count the number of vowels in a
given string

Code:
string = "counting vowels!"
vowels = "aeiouAEIOU"

count = sum([Link](vowel) for vowel in vowels)


print(count)

Output:
5
Q5. Write a Python program to generate the Fibonacci series
up to n terms.

CODE:
# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms

n1, n2 = 0, 1

count = 0

# check if the number of terms is valid

if nterms <= 0:

print("Please enter a positive integer")

# if there is only one term, return n1

elif nterms == 1:

print("Fibonacci sequence upto",nterms,":")

print(n1)

# generate fibonacci sequence

else:

print("Fibonacci sequence:")

while count < nterms:

print(n1)

nth = n1 + n2

# update values

n1 = n2

n2 = nth

count += 1
Output:

Q6. Write a Python program to find the largest and smallest


numbers in a list.
CODE:
lst = []

num = int(input('How many numbers: '))

for n in range(num):

numbers = int(input('Enter number '))

[Link](numbers)

print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))

OUTPUT:
Q7. Create a program to count the frequency of each
element in a list

CODE:
# importing the module
import collections

# initializing the list


random_list = ['A', 'A', 'B', 'C', 'B', 'D', 'D', 'A', 'B']

# using Counter to find frequency of elements


frequency = [Link](random_list)

# printing the frequency


print(dict(frequency))
{'A': 3, 'B': 3, 'C': 1, 'D': 2}

OUTPUT:
{'A': 3, 'B': 3, 'C': 1, 'D': 2}

Q8. Write a Python program to merge two dictionaries and


print the resulting dictionary.
CODE:
dict_1 = {1: 'a', 2: 'b'}

dict_2 = {2: 'c', 4: 'd'}


print(dict_1 | dict_2)

OUTPUT:
{1: 'a', 2: 'c', 4: 'd'}
Q9. Implement a Python program to sort a list of tuples
based on the second element.

CODE:
a = [(1, 3), (4, 1), (2, 2)]

# Sort by second item

sorted_list = sorted(a, key=lambda x: x[1])

print("Sorted List:", sorted_list)

OUTPUT:
Sorted List: [(4, 1), (2, 2), (1, 3)]

Q10. Write a Python program to count the occurrence of


each character in a string
CODE:
my_string = "Programiz"
my_char = "r"

print(my_string.count(my_char))

OUTPUT:
2
Q11. Create a Python program to find all the substrings of a
given string.
CODE:
def get_all_substrings(input_string):
# base case 1: if the input string is empty, return an empty list
if len(input_string) == 0:
return []

# base case 2: if the input string contains only one character, return a list
with that character
elif len(input_string) == 1:
return [input_string]

# recursive case: if the input string contains multiple characters


else:
# create an empty list to store the resulting substrings
output = []

# use nested loops to generate all possible substrings of the input


string
for i in range(len(input_string)):
for j in range(i+1, len(input_string)+1):
[Link](input_string[i:j])

# recursively call the function with the input string sliced from the
second character to the end
# and concatenate the resulting list of substrings with the list
generated from the current call
return output + get_all_substrings(input_string[1:])

# test the function with an example string


my_string = "hello"
substrings = get_all_substrings(my_string)
print(substrings)

OUTPUT:
['h', 'he', 'hel', 'hell', 'hello', 'e', 'el', 'ell', 'ello', 'l', 'll', 'llo', 'l', 'lo', 'o', 'e', 'el', 'ell',
'ello', 'l', 'll', 'llo', 'l', 'lo', 'o', 'l', 'll', 'llo', 'l', 'lo', 'o', 'l', 'lo', 'o', 'o']

Q12. Write a Python program to read a file and count the


number of words, lines, and characters in it.

CODE:
# Function to count number of characters, words, spaces and lines in a file
def counter(fname):

# variable to store total word count


num_words = 0

# variable to store total line count


num_lines = 0

# variable to store total character count


num_charc = 0

# variable to store total space count


num_spaces = 0
# opening file using with() method
# so that file gets closed
# after completion of work
with open(fname, 'r') as f:

# loop to iterate file


# line by line
for line in f:

# incrementing value of num_lines with each


# iteration of loop to store total line count
num_lines += 1

# declaring a variable word and assigning its value as Y


# because every file is supposed to start with a word or a
character
word = 'Y'

# loop to iterate every


# line letter by letter
for letter in line:

# condition to check that the encountered character


# is not white space and a word
if (letter != ' ' and word == 'Y'):

# incrementing the word


# count by 1
num_words += 1

# assigning value N to variable word because


until
# space will not encounter a word can not be
completed
word = 'N'

# condition to check that the encountered character


is a white space
elif (letter == ' '):

# incrementing the space


# count by 1
num_spaces += 1

# assigning value Y to variable word because


after
# white space a word is supposed to occur
word = 'Y'

# loop to iterate every character


for i in letter:

# condition to check white space


if(i !=" " and i !="\n"):
# incrementing character
# count by 1
num_charc += 1

# printing total word count


print("Number of words in text file: ",
num_words)

# printing total line count


print("Number of lines in text file: ",
num_lines)

# printing total character count


print('Number of characters in text file: ',
num_charc)

# printing total space count


print('Number of spaces in text file: ',
num_spaces)

OUTPUT:
Number of words in text file: 25
Number of lines in text file: 4
Number of characters in text file: 91
Number of spaces in text file: 21

Q13: Implement a Python program to copy the contents of


one file to another.
CODE:
# import module
import shutil

# use copyfile()
[Link]('[Link]','[Link]')

OUTPUT:
I Am The Contents Of First File
Geeks For Geeks!

Q14. Create a Python class Student with attributes for name,


roll number, and marks in three subjects. Write a method to
calculate the average marks of the student.

Code:
class Student:
marks = []
def getData(self, rn, name, m1, m2, m3):
[Link] = rn
[Link] = name
[Link](m1)
[Link](m2)
[Link](m3)

def displayData(self):
print ("Roll Number is: ", [Link])
print ("Name is: ", [Link])
#print ("Marks in subject 1: ", [Link][0])
#print ("Marks in subject 2: ", [Link][1])
#print ("Marks in subject 3: ", [Link][2])
print ("Marks are: ", [Link])
print ("Total Marks are: ", [Link]())
print ("Average Marks are: ", [Link]())

def total(self):
return ([Link][0] + [Link][1] +[Link][2])

def average(self):
return (([Link][0] + [Link][1] +[Link][2])/3)

r = int (input("Enter the roll number: "))


name = input("Enter the name: ")
m1 = int (input("Enter the marks in the first subject: "))
m2 = int (input("Enter the marks in the second subject: "))
m3 = int (input("Enter the marks in the third subject: "))

s1 = Student()
[Link](r, name, m1, m2, m3)
[Link]()

OUTPUT:
Enter the roll number: 10
Enter the name: Mahesh Huddar
Enter the marks in the first subject: 20
Enter the marks in the second subject: 30
Enter the marks in the third subject: 25
Roll Number is: 10
Name is: Mahesh Huddar
Marks are: [20, 30, 25]
Total Marks are: 75
Average Marks are: 25.0

Q15: Write a Python program to implement a stack using a


list, with operations for push, pop, and displaying the stack.

CODE:
# Created a Empty List
stack = []

# Pushing the elements in the list


[Link](1)
[Link](2)
[Link](3)

print(&quot;The Stack items are :&quot;)


for i in stack:
print(stack)
stack = []

def pop(stack):
if len(stack) == 0:
return None
else:
return [Link]()

# Pushing the elements in the list


[Link](1)
[Link](2)
[Link](3)

print(&quot;Initial Stack&quot;)
print(stack)

print(&quot;Popped Element: &quot;, pop(stack))

OUTPUT:
The Stack items are :
1
2
3
Initial Stack
[1, 2, 3]
Popped Element: 3
Q17. Write a Python program to create a database named
LibraryDB and a table named Books with columns: BookID
(INT, Primary Key), Title (VARCHAR), Author (VARCHAR), and
Price (FLOAT).
CODE:
import [Link]

mydb = [Link](
host="localhost",
user="yourusername",
password="yourpassword"
)

mycursor = [Link]()

[Link]("CREATE DATABASE mydatabase")

OUTPUT:
#If this page is executed with no error, you have successfully created a
database.

CODE:
import [Link]

mydb = [Link](
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = [Link]()
[Link]("CREATE TABLE Books (BookID(INT,PRIMARY
KEY),Title(varchar),Aurthor(varchar),Price(FLOAT))")

OUTPUT:
#If this page is executed with no error, you have successfully created a table
named "customers".

Q18. Write a Python program to insert multiple records into


the Books table in LibraryDB. Use placeholders and a list of
tuples for the data.
CODE:
import [Link]

conn = [Link](
host='localhost',
user='username',
password='password'
database='gfg'
)

# creating cursor object


cursor = [Link]()
# insert command/statement
insert_st = """INSERT INTO BOOKS (BOOKID,TITLE,PRICE)
VALUES("L102","BHARAT","4200")"""

# row created
[Link](insert_st)
# save changes
[Link]()

OUTPUT:

Q19. Write a Python program to retrieve and display all


records from the Books table, ordered by Price in descending
order.
CODE:
if totalbooks > 0:
print("BOOKS")
d = {}
if book > 0:
d['ncert eng'] = (ncert eng, [Link](countncert eng)) # d[menu_item] =
(cost, order_count)
if book > 0:
d['ncert math'] = (ncert math, [Link](count ncert math)) #
d[menu_item] = (cost, order_count)
if book > 0:
d['ncert cs'] = (book, [Link](countbook)) # d[menu_item] = (cost,
order_count)
if water > 0
d_lst = sorted([Link](), key=lambda x:x[1], reverse = True)
for item in d_lst:
print("Item: %s Cost: $%.2f OrderCount: %i "%(item[0], item[1][0], item[1]
[1]))

output:
ncert cs
ncert math
ncert eng

Q20. Write a Python program to update the Price of a


specific book in the Books table based on its BookID, and
display the updated record.
CODE:
mysql> INSERT INTO BOOKS VALUES
('L102', 'NCERT ENG', 19, 'XYZ', 2000),
('L103', 'NCERT MATH', 20, 'XYZ', 7000),
('L104', 'NCERT CS', 25, 'XYZ', 5000),
mysql> UPDATE BOOKS SET PRICE = PRICE + 100 WHERE BOOKID = ‘L104';
Query OK, 3 rows affected (0.06 sec)
Rows matched: 3 Changed: 3 Warnings: 0
OUTPUT:
mysql> select * from BOOKS;
+------------+-----------+------+------+--------+
| BOOKID | TITLE | AURTHOR| PRICE|
+------------+-----------+------+------+--------+
| L102 | NCERT ENG | XYZ | 2000 |
|L103 | NCERT MATH| XYZ |7000 |
| L104 | NCERT CS| XYZ | 5100 |
Q16.

ANSWERS
i. SELECT(ISSUEDATE)[(ISSUEDATE)]
FROM MEMBER
WHERE aggregate> 2016-01-01
ORDER BY issuedate DESC;
ii. SELECT(BNAME)

FROM BOOK
WHERE book type= Fiction,
iii. SELECT(TYPE,[Link] BOOKS)
FROM BOOK
WHERE book type=comic,literature,fiction;

iv. SELECT( MNAME , ISSUEDATE )


FROM MEMBER
WHERE ISSUDATE>2017-01-01

v. M103 – S ARTHAK JOHN -F1 02

vi. F1 02- Untold Story- M103– S ARTHAK JOHN

vii. German easy

Common questions

Powered by AI

In Python, lists and dictionaries are essential data structures that provide flexible and efficient ways to store and manipulate collections of data. Lists are ordered collections that allow easy access and manipulation of elements through indices, supporting operations such as append, remove, and slicing, making them suitable for sequential data storage or dynamic array behavior. Dictionaries, on the other hand, store data as key-value pairs, which allows fast retrieval, insertion, and deletion through keys. This is particularly useful for scenarios like counting occurrences, looking up data, or when mapping unique keys to values is essential. Their use significantly impacts program clarity, efficiency, and scalability, especially in handling large datasets or complex operations .

Recursion in Python can be utilized beyond traditional mathematical problems like factorials or Fibonacci sequences to solve complex real-world computational tasks effectively. It is particularly useful in scenarios involving hierarchical data structures like parsing HTML/XML trees, solving problems like the Tower of Hanoi, searching operations in maze type scenarios, and backtracking algorithms such as solving Sudoku puzzles or N-Queens problem. Recursion simplifies code needed to navigate hierarchical structures by letting each level of the hierarchy be solved with the same logic without explicit iteration, making it a powerful tool in implementing algorithms in Artificial Intelligence where decision trees or recursive descent parsing are needed .

The factorial algorithm using recursion involves defining the problem in terms of smaller instances of the same problem, allowing for elegant solutions that are sometimes more straightforward than iterative approaches. Recursive solutions divide the problem into smaller pieces and this method can lead to more natural mathematical representations and easier to understand code for problems like computing the factorial. However, recursion can be less efficient due to overhead from the function call stack and may lead to stack overflow errors in languages that do not optimize tail recursion, which does not happen in iterative approaches. Iterative methods use looping constructs to continuously process elements until a condition is met, often leading to better performance for larger inputs as they avoid the overhead of multiple function calls .

File I/O operations in Python, such as reading from or writing to a file, can encounter several potential errors and limitations. Errors may include file not found errors if the specified file path is incorrect, permission errors if the program does not have the necessary access rights, and encoding errors when reading or writing non-UTF-8 encoded files. Moreover, improper handling of file pointers can lead to overwriting or loss of data, hence why using context managers (the 'with' statement) is recommended to ensure files are properly closed after operations. Furthermore, handling very large files can lead to performance issues, requiring buffered or streamed reading strategies to manage memory usage effectively .

Sorting data by specific attributes, such as in sorting a list of tuples by the second element, affects data handling and analysis by organizing data based on relevant criteria. This can improve data readability, make it easier to find specific information, and support subsequent operations like binary search or data visualization, where the order of data plays a crucial role. In data analysis, sorted data is crucial for detecting trends, performing more efficient aggregations, and enabling certain algorithms that rely on ordered inputs to function correctly, such as mergesort or quicksort. Additionally, sorted order is often a preliminary step in preparing datasets for more complex machine learning tasks or operations .

Python classes can model real-world entities by using attributes to represent characteristics and methods to define behaviors of these entities. For instance, a class 'Student' with attributes like name, roll number, and marks can represent a student entity, encapsulating data related to them. Methods manage these objects by implementing actions such as calculating an average mark or displaying information, thus providing a blueprint to interact with the object's state. Methods ensure that operations on the data encapsulated within objects are performed reliably and maintain data integrity, reflecting the real-world rules applicable to these entities .

Using MySQL in Python to implement databases offers numerous benefits, such as leveraging Python’s extensive libraries and MySQL's robustness for managing relational data efficiently, including complex queries, indexing, and ACID compliance for transaction reliability. The integration enables seamless backend operations with Python’s syntax for handling connection pools, cursors, and exception handling. However, challenges include managing connections and cursors efficiently to prevent resource leaks, ensuring data security through proper user authentication and SQL injection prevention techniques, and handling database schema migrations or versioning for application updates. Additionally, balancing database normalization and performance tuning for large-scale applications can be complex .

A stack data structure in Python can be implemented using a list by leveraging Python’s list methods: 'append()' for the push operation, 'pop()' for the pop operation, and simple iteration to display elements. The stack operates on a Last In, First Out (LIFO) principle. Using 'append()', elements are added to the end of the list, mimicking the stack's push operation. To remove elements, the 'pop()' method is used, which removes the last element added. Displaying involves iterating through the list and printing elements, demonstrating the stack's current state. This implementation is straightforward and efficient, suitable for many applications needing stack functionality .

The Greatest Common Divisor (GCD) is crucial in various applications, such as simplifying fractions, where the numerator and denominator need to be reduced to their simplest form. It is also essential in algorithms like the Euclidean algorithm, for implementing modular multiplicative inverses and in computational areas such as cryptography. Moreover, the GCD helps to achieve efficiency in algorithms by representing problems involving cycles or modular arithmetic, and it is key in determining properties like co-primality of numbers, which is significant in number theory and various mathematical proofs .

When designing a program to check for palindromes, it is crucial to consider case sensitivity and special characters. A proper design should transform the string into a uniform case, typically lower case, to ensure that 'A' and 'a' are considered equal. Additionally, ignoring non-alphanumeric characters ensures that the program accurately identifies palindromes in phrases containing spaces and punctuation. These considerations are necessary to ensure correctness, especially when dealing with user-generated input where case sensitivity can lead to incorrect results .

You might also like