0% found this document useful (0 votes)
3 views32 pages

Python Programs for Patterns and Functions

Uploaded by

atarpal7895
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)
3 views32 pages

Python Programs for Patterns and Functions

Uploaded by

atarpal7895
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

PYTHON PROGRAMS

1. Write a program in Python to print full pyramid patterns.

def full_pyramid(n):
for i in range(1, n+1):
# Print leading spaces
for j in range(n-i):
print(" ", end="")

# Print asterisks for the current row


for k in range(1,2*i):
print("*", end="")
print()

full_pyramid(5)

Output:

*
***
*****
*******
*********

2. Write a program in Python to print pyramid patterns with numbers.

# Function to demonstrate printing pattern of numbers


def numpat(n):

# initialising starting number


num = 1

# outer loop to handle number of rows


for i in range(0, n):

# re assigning num
num = 1

# inner loop to handle number of columns


# values changing acc. to outer loop
for j in range(0, i+1):

# printing number
print(num, end=" ")

# incrementing number at each column


num = num + 1

# ending line after each row

1
print("")

# Driver code
n=5
numpat(n)

Output:

1
12
123
1234
12345

3. Write a program in Python to calculate the factorial of an integer using recursion.

def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)

num=int(input("Enter the number: "))


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 ", factorial(num))

OUTPUT:
Enter the number: 5
The factorial of 5 is 120

4. Write a program in Python to print Fibonacci Series using recursion.

def fibonacci(n):
if n<=1:
return n
else:
return(fibonacci(n-1)+fibonacci(n-2))

num=int(input("How many terms you want to display: "))


for i in range(num):

2
print(fibonacci(i)," ", end=" ")

OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13

5. Write a recursive Python program to test if a string is Palindrome or not.

def isStringPalindrome(str):
if len(str)<=1:
return True
else:
if str[0]==str[-1]:
return isStringPalindrome(str[1:-1])
else:
return False

#__main__
s=input("Enter the string : ")
y=isStringPalindrome(s)
if y==True:
print("String is Palindrome")
else:
print("String is Not Palindrome")

OUTPUT:
Enter the string: madam
String is Palindrome

6. Write a program in Python to perform the basic arithmetic operations by using functions.

def add(n1, n2):


return n1 + n2

def sub(n1, n2):


return n1 - n2

def mul(n1, n2):


return n1 * n2

def div(n1, n2):


return n1 / n2

print("Please Select operation -\n"

3
"1. Add\n"
"2. Subtract\n"
"3. Multiply\n"
"4. Divide\n")

ch = int(input("Select operation (1-4): "))

n1 = int(input("Enter first number: "))


n2 = int(input("Enter second number: "))

if ch == 1:
print(n1, "+", n2, "=", add(n1, n2))
elif ch == 2:
print(n1, "-", n2, "=", sub(n1, n2))
elif ch == 3:
print(n1, "*", n2, "=", mul(n1, n2))
elif ch == 4:
print(n1, "/", n2, "=", div(n1, n2))
else:
print("Invalid input")

Output:
Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide

Select operation (1-4): 1


Enter first number: 56
Enter second number: 5989
56 + 5989 = 6045

Please select operation -


1. Add
2. Subtract
3. Multiply
4. Divide

Select operation (1-4): 2


Enter first number: 56
Enter second number: 2
56 - 2 = 54

Please select operation -


1. Add
2. Subtract
3. Multiply
4. Divide

4
Select operation (1-4): 3
Enter first number: 526
Enter second number: 8
526 * 8 = 4208

Please select operation -


1. Add
2. Subtract
3. Multiply
4. Divide

Select operation (1-4): 4


Enter first number: 859
Enter second number: 56
859 / 56 = 15.339285714285714

7. Write a program in Python to handle division by zero error by using try-except block.

def safe_divide(numerator, denominator):


try:
result = numerator / denominator
return result
except ZeroDivisionError:
return "Error: Division by zero is not allowed."

def get_user_input():
"""
Gets user input for two numbers and handles potential ValueError.

Returns:
tuple or None: A tuple of two numbers, or None if input is invalid.
"""
try:
num1 = float(input("Enter the numerator: "))
num2 = float(input("Enter the denominator: "))
return num1, num2
except ValueError:
print("Error: Invalid input. Please enter a valid number.")
return None

if __name__ == "__main__":
numbers = get_user_input()
if numbers:
n, d = numbers
division_result = safe_divide(n, d)
print("Result:", division_result)

5
Output:

Enter the numerator: 12


Enter the denominator: 0
Result: Error: Division by zero is not allowed.

8. Write a program in Python to read a text file line by line and display each word separated by '#'.

fin=open("D:\\python programs\\[Link]",'r')
L1=[Link]( )
s=' '
for i in range(len(L1)):
L=L1[i].split( )
for j in L:
s=s+j
s=s+'#'
print(s)
[Link]( )

OUTPUT:
Text in file:
hello how are you?
python is case-sensitive language.

Output in python shell:


hello#how#are#you?#python#is#case-sensitive#language.#

9. Write a program in Python to count vowels, consonants, uppercase and lowercase characters in a text
file.
def count_characters(file_path):
vowels = "aeiouAEIOU"
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
uppercase_count = 0
lowercase_count = 0
vowel_count = 0
consonant_count = 0

try:
with open(file_path, 'r') as file:
content = [Link]()
for char in content:
if [Link]():
if [Link]():
uppercase_count += 1

6
elif [Link]():
lowercase_count += 1

if char in vowels:
vowel_count += 1
elif char in consonants:
consonant_count += 1

print(f"Uppercase characters: {uppercase_count}")


print(f"Lowercase characters: {lowercase_count}")
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")

except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")

file_path = '[Link]'
count_characters(file_path)

The text file contains -


This is the first line.
This is the second line.
Output:

Uppercase characters: 2
Lowercase characters: 35
Vowels: 13
Consonants: 24

10. Write a program in Python to remove all lines contain the character 'a' and write to another file.

def remove_lines_with_character(file_path, character, output_file_path):


try:
with open(file_path, 'r') as file:
lines = [Link]()

# Remove lines containing the specified character


modified_lines = [line for line in lines if character not in line]

with open(output_file_path, 'w') as output_file:


output_file.writelines(modified_lines)

print(f"Lines containing '{character}' removed. Modified content saved to '{output_file_path}'.")

except FileNotFoundError:

7
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")

# Replace 'input_file.txt', 'output_file.txt', and 'a' with the actual paths and character
input_file_path = '[Link]'
output_file_path = '[Link]'
character_to_remove = 'a'

remove_lines_with_character(input_file_path, character_to_remove, output_file_path)

Output:
Lines containing 'a' removed. Modified content saved to '[Link]'.

If the file contains -


Harry Potter books.
There is a difference in the books.
We can see it as harry grows.
The books were written by J. K. Rowling.
Then, the modified text file, file1 conatins -
The books were written by J. K. Rowling.

11. Write a program in Python to create a binary file with name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.

import pickle
def create_student_records(filename="[Link]"):
"""
Creates or overwrites a binary file with student names and roll numbers.
"""
records = []
while True:
name = input("Enter student name (or 'q' to quit): ")
if [Link]() == 'q':
break
try:
roll_number = int(input("Enter roll number: "))
[Link]({'name': name, 'roll_number': roll_number})
except ValueError:
print("Invalid roll number. Please enter an integer.")
with open(filename, 'wb') as file:
[Link](records, file)
print(f"Student records saved to {filename}")
def search_student_by_roll(filename="[Link]"):
"""

8
Searches for a student by roll number in the binary file and displays their name.
"""
try:
with open(filename, 'rb') as file:
records = [Link](file)
except FileNotFoundError:
print(f"Error: File '{filename}' not found. Please create records first.")
return
except EOFError:
print(f"Error: File '{filename}' is empty.")
return
try:
search_roll = int(input("Enter the roll number to search: "))
except ValueError:
print("Invalid input. Please enter an integer for the roll number.")
return
found = False
for record in records:
if record['roll_number'] == search_roll:
print(f"Name: {record['name']}")
found = True
break
if not found:
print(f"Roll number {search_roll} not found in records.")

if __name__ == "__main__":
while True:
print("\n--- Menu ---")
print("1. Create/Update student records")
print("2. Search for a student by roll number")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == '1':
create_student_records()
elif choice == '2':
search_student_by_roll()
elif choice == '3':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")

Output:

9
--- Menu ---
1. Create/Update student records
2. Search for a student by roll number
3. Exit
Enter your choice: 1
Enter student name (or 'q' to quit): Rahul
Enter roll number: 1
Enter student name (or 'q' to quit): Praful
Enter roll number: 2
Enter student name (or 'q' to quit): Naman
Enter roll number: 3
Enter student name (or 'q' to quit): Ajay
Enter roll number: 4
Enter student name (or 'q' to quit): Subhash
Enter roll number: 5
Enter student name (or 'q' to quit): q
Student records saved to [Link]

--- Menu ---


1. Create/Update student records
2. Search for a student by roll number
3. Exit
Enter your choice: 5
Invalid choice. Please try again.

--- Menu ---


1. Create/Update student records
2. Search for a student by roll number
3. Exit
Enter your choice: 2
Enter the roll number to search: 4
Name: Ajay

--- Menu ---


1. Create/Update student records
2. Search for a student by roll number
3. Exit
Enter your choice: 3
Exiting program.

12. Write a program in Python to create a binary file with roll number, name and marks. Input a roll
number and update the marks.

10
import pickle
def create_student_record_file(filename="student_records.dat"):
"""Creates or appends student records to a binary file."""
with open(filename, 'ab') as file:
while True:
try:
roll_no = int(input("Enter roll number (0 to finish): "))
if roll_no == 0:
break
name = input("Enter name: ")
marks = float(input("Enter marks: "))
student_data = {'roll_no': roll_no, 'name': name, 'marks': marks}
[Link](student_data, file)
except ValueError:
print("Invalid input. Please enter a number for roll number and marks.")
print("Student records saved to", filename)
def update_student_marks(filename="student_records.dat"):
"""Updates the marks of a student based on their roll number."""
try:
roll_to_update = int(input("Enter the roll number of the student to update: "))
except ValueError:
print("Invalid input. Please enter a number for the roll number.")
return
updated_records = []
found = False
try:
with open(filename, 'rb') as infile:
while True:
try:
record = [Link](infile)
if record['roll_no'] == roll_to_update:
try:
new_marks = float(input(f"Enter new marks for {record['name']} (current marks:
{record['marks']}): "))
record['marks'] = new_marks
found = True
print("Marks updated successfully.")
except ValueError:
print("Invalid input. Please enter a number for marks.")
updated_records.append(record)
except EOFError:
break
except FileNotFoundError:
print("File not found. Please create student records first.")

11
return
if not found:
print(f"Roll number {roll_to_update} not found.")
return
with open(filename, 'wb') as outfile:
for record in updated_records:
[Link](record, outfile)
def display_records(filename="student_records.dat"):
"""Displays all student records from the binary file."""
try:
with open(filename, 'rb') as file:
print("\n--- Student Records ---")
while True:
try:
record = [Link](file)
print(f"Roll No: {record['roll_no']}, Name: {record['name']}, Marks: {record['marks']}")
except EOFError:
break
print("-----------------------")
except FileNotFoundError:
print("File not found. Please create student records first.")

if __name__ == "__main__":
while True:
print("\n1. Create/Add Student Records")
print("2. Update Student Marks")
print("3. Display All Records")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
create_student_record_file()
elif choice == '2':
update_student_marks()
elif choice == '3':
display_records()
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")

Output:

1. Create/Add Student Records

12
2. Update Student Marks
3. Display All Records
4. Exit
Enter your choice: 1
Enter roll number (0 to finish): 1
Enter name: Ajay
Enter marks: 86
Enter roll number (0 to finish): 2
Enter name: Naman
Enter marks: 95
Enter roll number (0 to finish): 3
Enter name: Praful
Enter marks: 77
Enter roll number (0 to finish): 4
Enter name: Rahul
Enter marks: 80
Enter roll number (0 to finish): 5
Enter name: Subhash
Enter marks: 90
Enter roll number (0 to finish): 0
Student records saved to student_records.dat

1. Create/Add Student Records


2. Update Student Marks
3. Display All Records
4. Exit
Enter your choice: 2
Enter the roll number of the student to update: 2
Enter new marks for Naman (current marks: 95.0): 100
Marks updated successfully.

1. Create/Add Student Records


2. Update Student Marks
3. Display All Records
4. Exit
Enter your choice: 4
Exiting program.

13. Write a program in Python to write a random number generator that generates random numbers
between 1 and 6 (simulates a dice).

import random
def roll_dice():
"""
Generates a random integer between 1 and 6, simulating a dice roll.
"""
return [Link](1, 6)

13
# Example usage:
if __name__ == "__main__":
print("Rolling the dice...")
result = roll_dice()
print(f"The dice rolled a: {result}")

# You can call roll_dice() multiple times to simulate multiple rolls


print(f"Another roll: {roll_dice()}")

Output:

Rolling the dice...


The dice rolled a: 3
Another roll: 5

14. Write a Python program to implement a stack using list.

Note - Write the program written in the book.

15. Write a program in Python to create a CSV file by entering user-id and password, read and search
the password for given userid.

import csv
import os
FILE_NAME = 'user_data.csv'
def create_csv_if_not_exists():
"""Create the CSV file with headers if it doesn't already exist."""
if not [Link](FILE_NAME):
with open(FILE_NAME, 'w', newline='') as file:
writer = [Link](file)
[Link](['user_id', 'password'])
def add_user():
"""Adds a new user-id and password to the CSV file."""
user_id = input("Enter a new user ID: ")
password = input("Enter a new password: ")
with open(FILE_NAME, 'a', newline='') as file:
writer = [Link](file)
[Link]([user_id, password])
print("User added successfully!")
def search_password():
"""Searches for and retrieves the password for a given user ID."""
search_id = input("Enter the user ID to search for: ")
found = False
with open(FILE_NAME, 'r') as file:

14
reader = [Link](file)
# Skip the header row
next(reader, None)
for row in reader:
if row[0] == search_id:
print(f"Password for {search_id} is: {row[1]}")
found = True
break
if not found:
print(f"User ID '{search_id}' not found.")

def main():
"""The main function to run the program."""
create_csv_if_not_exists()
while True:
print("\nMenu:")
print("1. Add a new user")
print("2. Search for a password by user ID")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_user()
elif choice == '2':
search_password()
elif choice == '3':
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

Output:

Menu:
1. Add a new user
2. Search for a password by user ID
3. Exit
Enter your choice: 1
Enter a new user ID: student1
Enter a new password: Stud@123
User added successfully!

Menu:
1. Add a new user
2. Search for a password by user ID
3. Exit
Enter your choice: 1
Enter a new user ID: student2
Enter a new password: Stud2@123

15
User added successfully!

Menu:
1. Add a new user
2. Search for a password by user ID
3. Exit
Enter your choice: 1
Enter a new user ID: student3
Enter a new password: Stud3@3
User added successfully!

Menu:
1. Add a new user
2. Search for a password by user ID
3. Exit
Enter your choice: 1
Enter a new user ID: student4
Enter a new password: Stud4@4
User added successfully!

Menu:
1. Add a new user
2. Search for a password by user ID
3. Exit
Enter your choice: 1
Enter a new user ID: student5
Enter a new password: Stud5@123
User added successfully!

Menu:
1. Add a new user
2. Search for a password by user ID
3. Exit
Enter your choice: 2
Enter the user ID to search for: student3
Password for student3 is: Stud3@3

Menu:
1. Add a new user
2. Search for a password by user ID
3. Exit
Enter your choice: 3

SQL QUERIES

16
16. To write SQL Queries for the following questions based on the given table:

17
17. To write SQL Queries for the following questions based on the given table:

19
20
18. To write SQL Queries for the following questions based on the given table:

21
22
19. To write SQL Queries for the following questions based on the given table:

23
24
20. To write SQL Queries for the following questions based on the given table:

25
PYTHON – MySQL CONNECTIVITY

26
21. Create a program in Python to integrate MySQL with Python (creating database and table).

27
28
22. Create a program in Python to integrate MySQL with Python (inserting and displaying records).

29
23. Create a program in Python to integrate MySQL with Python (searching and displaying record).

30
24. Create a program in Python to integrate MySQL with Python (updating records).

31
32

You might also like