0% found this document useful (0 votes)
7 views6 pages

Python Programs for Basic Patterns and Analysis

The document contains multiple Python programs demonstrating various concepts, including generating patterns using nested loops, counting letters in a string, converting character cases, and performing operations on lists and dictionaries. Each program includes user interaction for input and displays results based on the operations performed. The programs cover string analysis, tuple statistics, list manipulation, linear search, and employee management.

Uploaded by

Masked noob
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)
7 views6 pages

Python Programs for Basic Patterns and Analysis

The document contains multiple Python programs demonstrating various concepts, including generating patterns using nested loops, counting letters in a string, converting character cases, and performing operations on lists and dictionaries. Each program includes user interaction for input and displays results based on the operations performed. The programs cover string analysis, tuple statistics, list manipulation, linear search, and employee management.

Uploaded by

Masked noob
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

COMPUTER SCIENCE RECORD EXPERIMENTS (10-20)

Write a python program for generating the following pattern using nested loop:
*****
****
***
**
*
for i in range(5, 0, -1):
# Inner loop: prints '*' based on the current value of i
for j in range(0, i):
print("*", end="")
print()

Write a python program for generating the following pattern using nested loop:

A
AB
ABC
ABCD
ABCDE
for i in range(1, 5 + 1):
for j in range(0, i):
print(chr(65 + j), end="")
print()

Write a python program for counting the number of uppercase letters, lowercase letters, vowels
and consonants in a string.
def main():
user_str = ""
while True:
print("\n--- String Analysis Menu ---")
print("1. Input New String")
print("2. Count Uppercase & Lowercase")
print("3. Count Vowels & Consonants")
print("4. Show Full Report")
print("5. Exit")
choice = input("Select an option (1-5): ")
if choice == '1':
user_str = input("Enter your string: ")
print("String saved!")
elif choice == '2' or choice == '3' or choice == '4':
if user_str == "":
print("Error: No string found. Use Option 1 first.")
continue
# Index 0: Upper, Index 1: Lower, Index 2: Vowels, Index 3: Consonants
counts = [0, 0, 0, 0]
vowels = "aeiouAEIOU"
for char in user_str:
if [Link]():
# Check Case
if [Link]():
counts[0] = counts[0] + 1
else:
counts[1] = counts[1] + 1
# Check Vowels
if char in vowels:
counts[2] = counts[2] + 1
else:
counts[3] = counts[3] + 1
if choice == '2':
print("Uppercase letters:", counts[0])
print("Lowercase letters:", counts[1])

elif choice == '3':


print("Vowels:", counts[2])
print("Consonants:", counts[3])
elif choice == '4':
print("Full Report for:", user_str)
print("Uppercase:", counts[0])
print("Lowercase:", counts[1])
print("Vowels:", counts[2])
print("Consonants:", counts[3])

elif choice == '5':


print("Exiting program.")
break
else:
print("Invalid choice!")
Write a python program for converting the case of characters in a string.
def convert_case(input_string):
result = ""
for char in input_string:
if 'A' <= char <= 'Z':
result += chr(ord(char) + 32)
elif 'a' <= char <= 'z':
result += chr(ord(char) - 32)
else:
result += char
return result

user_input = input("Enter a string: ")


print("Converted String:", convert_case(user_input))

Write a Python Program to read a tuple of ‘n’ integers and find the maximum, minimum &
mean of numeric values stored in it.
# Input the number of elements
n = int(input("Enter the number of elements (n): "))
# Creating a list first (because tuples are immutable and cannot be built one by one)
temp_list = []
for i in range(n):
num = int(input("Enter integer " + str(i + 1) + ": "))
temp_list.append(num)
numbers = tuple(temp_list)
if len(numbers) > 0:
maximum = max(numbers)
minimum = min(numbers)
# Mean is the sum divided by the total count
mean = sum(numbers) / len(numbers)

# Display results using simple print statements


print("----------------------------")
print("Tuple contents:", numbers)
print("Maximum value:", maximum)
print("Minimum value:", minimum)
print("Mean (Average):", mean)
print("----------------------------")
else:
print("The tuple is empty.")

Write a Python Program to input a list of ‘n’ numbers and swap elements at the even location
with the elements at the odd location.
numbers = []
while True:
print("\n--- List Operations Menu ---")
print("1. Input/Reset List")
print("2. Traverse and Print List")
print("3. Get Element by Index")
print("4. Find Index of a Number")
print("5. Exit")

choice = input("Enter your choice (1-5): ")

if choice == '1':
n = int(input("How many numbers do you want to enter? "))
numbers = []
for i in range(n):
val = float(input(f"Enter number for index {i}: "))
[Link](val)
print("List updated successfully.")

elif choice == '2':


if not numbers:
print("List is empty!")
else:
print("Traversing list:")
for index, val in enumerate(numbers):
print(f"Index {index} -> Value: {val}")

elif choice == '3':


idx = int(input(f"Enter index to view (0 to {len(numbers)-1}): "))
if 0 <= idx < len(numbers):
print(f"Value at index {idx} is {numbers[idx]}")
else:
print("Error: Index out of range!")

elif choice == '4':


val = float(input("Enter number to search for: "))
if val in numbers:
print(f"Number {val} first found at index {[Link](val)}")
else:
print("Number not found in list.")

elif choice == '5':


print("Goodbye!")
break
else:
print("Invalid choice. Please select 1-5.")

Write a Python Program to input a list of ‘n’ numbers to search for a given element using
LINEAR SEARCH technique.
def linear_search(numbers, target):
# Traverse through the entire list
for index in range(len(numbers)):
# Check if the current element matches the target
if numbers[index] == target:
return index # Return the index if found

return -1 # Return -1 if the element is not in the list

n = int(input("Enter the number of elements: "))


data_list = []
for i in range(n):
val = float(input("Enter element ",i))
data_list.append(val)

search_val = float(input("Enter the number you want to search for: "))


# Call the search function
result = linear_search(data_list, search_val)
if result != -1:
print("Success! Element found at index ",result)
else:
print("Element was not found in the list.")

Write a Python Program to read the ID and name of ‘n’ employees and store them in a dictionary.
Also display all employees’ information in ascending order based upon their ID from the
dictionary

employees = {}
while True:
print("\n--- Employee Management Menu ---")
print("1. Add Employees")
print("2. Display All Employees ")
print("3. Exit")

choice = input("Enter your choice (1-3): ")

if choice == '1':
n = int(input("How many employees do you want to add? "))
for _ in range(n):
emp_id = int(input("Enter Employee ID (Numeric): "))
emp_name = input("Enter Employee Name: ")
# Adding to dictionary
employees[emp_id] = emp_name
print("Successfully added employees.")

elif choice == '2':


if not employees:
print("The dictionary is empty!")
else:
print("\n--- Employee List ")
for i in [Link]():
print(i)
print("-" * 30)

# Sorting dictionary keys (IDs) and iterating


for emp_id in sorted([Link]()):
print(employees[emp_id])
elif choice == '3':
print("Exiting program. Goodbye!")
break

else:
print("Invalid choice! Please try again.")

You might also like