Sure

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

Sure, here are 5 programs that cover various topics from your list.

Feel free to use them as examples


or modify them according to your needs.

**Program 1: User-Defined Function and File Handling**

```python

def write_to_file(filename, data):

with open(filename, 'w') as file:

file.write(data)

def read_from_file(filename):

with open(filename, 'r') as file:

return file.read()

user_input = input("Enter data to write to file: ")

write_to_file("output.txt", user_input)

print("Data written to file.")

file_data = read_from_file("output.txt")

print("Data read from file:", file_data)

```

**Program 2: CSV File Handling**

```python

import csv

def write_csv(filename, data):

with open(filename, 'w', newline='') as file:

writer = csv.writer(file)

writer.writerows(data)

def read_csv(filename):
with open(filename, 'r') as file:

reader = csv.reader(file)

return list(reader)

data_to_write = [['Name', 'Age'], ['Alice', '25'], ['Bob', '30']]

write_csv("data.csv", data_to_write)

print("Data written to CSV file.")

data_from_csv = read_csv("data.csv")

print("Data read from CSV file:", data_from_csv)

```

**Program 3: User-Defined Function with Default Parameters**

```python

def greet(name, greeting="Hello"):

return f"{greeting}, {name}!"

user_name = input("Enter your name: ")

user_greeting = input("Enter a greeting (or press Enter for default): ")

if user_greeting:

result = greet(user_name, user_greeting)

else:

result = greet(user_name)

print(result)

```

**Program 4: Stack Implementation using Lists**

```python

class Stack:

def __init__(self):
self.items = []

def push(self, item):

self.items.append(item)

def pop(self):

if not self.is_empty():

return self.items.pop()

def is_empty(self):

return len(self.items) == 0

stack = Stack()

stack.push(5)

stack.push(10)

stack.push(15)

print("Popped:", stack.pop())

print("Popped:", stack.pop())

print("Is stack empty?", stack.is_empty())

```

**Program 5: Binary File Handling with Pickle**

```python

import pickle

def write_binary_file(filename, data):

with open(filename, 'wb') as file:

pickle.dump(data, file)

def read_binary_file(filename):

with open(filename, 'rb') as file:


return pickle.load(file)

data_to_write = {'name': 'Alice', 'age': 30}

write_binary_file("data.bin", data_to_write)

print("Data written to binary file.")

data_from_binary = read_binary_file("data.bin")

print("Data read from binary file:", data_from_binary)

```

You can continue building on these examples by combining different concepts and adding more
functionality to them.

Of course, here are five more programs that continue to cover various topics from your list:

**Program 6: Function Returning Value and File Manipulation**

```python

def double_numbers(numbers):

return [num * 2 for num in numbers]

def write_list_to_file(filename, data_list):

with open(filename, 'w') as file:

for item in data_list:

file.write(str(item) + '\n')

numbers = [1, 2, 3, 4, 5]

doubled_numbers = double_numbers(numbers)

write_list_to_file("doubled_numbers.txt", doubled_numbers)

print("Doubled numbers written to file.")

```
**Program 7: File Reading and Manipulation**

```python

def reverse_lines(input_filename, output_filename):

with open(input_filename, 'r') as infile, open(output_filename, 'w') as outfile:

lines = infile.readlines()

reversed_lines = [line.strip()[::-1] for line in lines]

for line in reversed_lines:

outfile.write(line + '\n')

reverse_lines("input.txt", "reversed_output.txt")

print("Lines reversed and written to file.")

```

**Program 8: Function with Positional and Keyword Arguments**

```python

def display_info(name, age, city="Unknown"):

print(f"Name: {name}, Age: {age}, City: {city}")

display_info("Alice", 28)

display_info("Bob", 35, city="New York")

```

**Program 9: CSV File Operations and User Input**

```python

import csv

def append_to_csv(filename, data):

with open(filename, 'a', newline='') as file:

writer = csv.writer(file)

writer.writerow(data)
user_data = input("Enter name and age (comma-separated): ").split(',')

append_to_csv("data.csv", user_data)

print("Data appended to CSV file.")

```

**Program 10: Scope of Variables**

```python

global_variable = 10

def modify_global():

global global_variable

global_variable += 5

def local_scope_demo():

local_variable = 20

print("Local variable:", local_variable)

modify_global()

print("Global variable:", global_variable)

local_scope_demo()

# Uncomment the next line to see an error since local_variable is not defined here

# print("Local variable outside function:", local_variable)

```

Feel free to experiment with these programs, combine concepts, and explore further. Each program
provides a unique perspective on the topics you've mentioned, and you can continue building your
understanding by adapting and expanding these examples.

Certainly! Here are five more programs that continue to cover the topics you've mentioned:

**Program 11: User-Defined Function and File Manipulation**

```python
def write_lines_to_file(filename, lines):

with open(filename, 'w') as file:

for line in lines:

file.write(line + '\n')

def read_and_reverse_lines(filename):

with open(filename, 'r') as file:

lines = file.readlines()

reversed_lines = [line.strip()[::-1] for line in lines]

return reversed_lines

lines_to_write = ["Hello, world!", "Python is fun!", "Programming rocks!"]

write_lines_to_file("lines.txt", lines_to_write)

print("Lines written to file.")

reversed_lines = read_and_reverse_lines("lines.txt")

print("Reversed lines:", reversed_lines)

```

**Program 12: Stack Implementation and File Handling**

```python

class Stack:

def __init__(self):

self.items = []

def push(self, item):

self.items.append(item)

def pop(self):

if not self.is_empty():

return self.items.pop()
def is_empty(self):

return len(self.items) == 0

stack = Stack()

stack.push("apple")

stack.push("banana")

stack.push("cherry")

print("Popped:", stack.pop())

print("Is stack empty?", stack.is_empty())

with open("stack_output.txt", "w") as file:

while not stack.is_empty():

item = stack.pop()

file.write(item + '\n')

print("Stack items written to file.")

```

**Program 13: CSV File Reading and Manipulation**

```python

import csv

def update_csv_row(filename, row_index, new_data):

with open(filename, 'r') as file:

rows = list(csv.reader(file))

rows[row_index] = new_data

with open(filename, 'w', newline='') as file:

writer = csv.writer(file)

writer.writerows(rows)

data_to_update = ['Alice', '28']


update_csv_row("data.csv", 1, data_to_update)

print("CSV data updated.")

```

**Program 14: File Paths and Function Calling**

```python

def add_numbers(a, b):

return a + b

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

result = add_numbers(num1, num2)

with open("result.txt", 'w') as file:

file.write(str(result))

print("Result:", result, "written to file.")

```

**Program 15: Function with Variable Number of Arguments**

```python

def calculate_sum(*args):

return sum(args)

nums = [5, 10, 15, 20]

total = calculate_sum(*nums)

print("Sum of numbers:", total)

```

These additional programs should help you further explore the topics you've mentioned. You can
continue to mix and match these concepts and create more complex programs as you become more
comfortable with the concepts and their interactions.
Certainly! Here's a program that includes a mix of various concepts you mentioned within
approximately 30 lines of code:

```python

import csv

import pickle

# User-defined function to calculate the average of a list of numbers

def calculate_average(numbers):

total = sum(numbers)

return total / len(numbers)

# Read data from a CSV file and calculate the average

def read_csv_and_calculate_average(filename):

with open(filename, 'r') as file:

reader = csv.reader(file)

data = [float(row[0]) for row in reader]

avg = calculate_average(data)

return avg

# Write data to a binary file using pickle

def write_binary_data(filename, data):

with open(filename, 'wb') as file:

pickle.dump(data, file)

# Read data from a binary file and return it

def read_binary_data(filename):

with open(filename, 'rb') as file:

data = pickle.load(file)

return data
# Main program

if __name__ == "__main__":

# CSV file handling

data_to_write = [10.5, 20.3, 15.8, 18.2]

csv_filename = "data.csv"

with open(csv_filename, 'w', newline='') as file:

writer = csv.writer(file)

writer.writerows([[num] for num in data_to_write])

print("Data written to CSV file:", data_to_write)

avg = read_csv_and_calculate_average(csv_filename)

print("Average from CSV:", avg)

# Binary file handling

binary_data = {'name': 'Alice', 'age': 30}

binary_filename = "binary_data.bin"

write_binary_data(binary_filename, binary_data)

print("Binary data written:", binary_data)

loaded_data = read_binary_data(binary_filename)

print("Loaded binary data:", loaded_data)

```

This program incorporates user-defined functions, CSV file handling, binary file handling using the
pickle module, and calculations. It demonstrates how these concepts can be combined to create a
functional program within the specified line count.

Certainly! Here are the programs for each of the tasks you mentioned:

**1. Read a text file line by line and display each word separated by a #**

```python

def process_text_file(file_name):
with open(file_name, 'r') as file:

for line in file:

words = line.strip().split()

formatted_line = '#'.join(words)

print(formatted_line)

text_file_name = 'sample.txt'

process_text_file(text_file_name)

```

**2. Display the number of vowels/consonants/uppercase/lowercase characters in a text file**

```python

def count_characters(file_name):

vowels = "AEIOUaeiou"

consonants = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"

upper_count = lower_count = vowel_count = consonant_count = 0

with open(file_name, 'r') as file:

content = file.read()

for char in content:

if char.isupper():

upper_count += 1

elif char.islower():

lower_count += 1

if char in vowels:

vowel_count += 1

elif char in consonants:

consonant_count += 1

print("Uppercase:", upper_count)

print("Lowercase:", lower_count)
print("Vowels:", vowel_count)

print("Consonants:", consonant_count)

text_file_name = 'sample.txt'

count_characters(text_file_name)

```

**3. Remove lines containing 'a' and write to another file**

```python

def remove_lines_with_character(file_name, character, new_file_name):

with open(file_name, 'r') as file:

lines = file.readlines()

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

with open(new_file_name, 'w') as new_file:

new_file.writelines(filtered_lines)

input_file_name = 'input.txt'

output_file_name = 'output.txt'

remove_lines_with_character(input_file_name, 'a', output_file_name)

```

**4. Create and search in a binary file with name and roll number**

```python

import pickle

def create_binary_file(data, file_name):

with open(file_name, 'wb') as file:

pickle.dump(data, file)
def search_roll_number(file_name, target_roll):

with open(file_name, 'rb') as file:

data = pickle.load(file)

for roll, name in data.items():

if roll == target_roll:

print(f"Roll Number: {roll}, Name: {name}")

break

else:

print("Roll Number not found.")

students = {101: 'Alice', 102: 'Bob', 103: 'Charlie'}

binary_file_name = 'students.bin'

create_binary_file(students, binary_file_name)

search_roll_number(binary_file_name, 102)

```

**5. Create and update a binary file with roll number, name, and marks**

```python

import pickle

def create_binary_file(data, file_name):

with open(file_name, 'wb') as file:

pickle.dump(data, file)

def update_marks(file_name, target_roll, new_marks):

with open(file_name, 'rb') as file:

data = pickle.load(file)

if target_roll in data:

data[target_roll]['marks'] = new_marks
with open(file_name, 'wb') as file:

pickle.dump(data, file)

print("Marks updated.")

else:

print("Roll Number not found.")

students = {

101: {'name': 'Alice', 'marks': 85},

102: {'name': 'Bob', 'marks': 92},

103: {'name': 'Charlie', 'marks': 78}

binary_file_name = 'students_marks.bin'

create_binary_file(students, binary_file_name)

update_marks(binary_file_name, 102, 95)

```

**6. Random number generator (simulate a dice)**

```python

import random

def roll_dice():

return random.randint(1, 6)

print("Rolled:", roll_dice())

```

**7. Stack implementation using a list**

```python

class Stack:

def __init__(self):
self.items = []

def push(self, item):

self.items.append(item)

def pop(self):

if not self.is_empty():

return self.items.pop()

def is_empty(self):

return len(self.items) == 0

stack = Stack()

stack.push(1)

stack.push(2)

stack.push(3)

print("Popped:", stack.pop())

print("Popped:", stack.pop())

print("Is stack empty?", stack.is_empty())

```

**8. Create a CSV file for user-id and password, and search for password by user-id**

```python

import csv

def create_csv_file(data, file_name):

with open(file_name, 'w', newline='') as file:

writer = csv.writer(file)

writer.writerows(data)

def search_password(file_name, target_user_id):


with open(file_name, 'r') as file:

reader = csv.reader(file)

for row in reader:

if row[0] == target_user_id:

print(f"User ID: {row[0]}, Password: {row[1]}")

break

else:

print("User ID not found.")

user_data = [['user1', 'pass123'], ['user2', 'abc456'], ['user3', 'qwerty']]

csv_file_name = 'user_data.csv'

create_csv_file(user_data, csv_file_name)

search_password(csv_file_name, 'user2')

```

These programs cover a range of tasks as per your request. Feel free to modify and combine them to
meet your specific requirements.

Certainly! Here's the continuation with the remaining tasks:

**9. Read a text file line by line and display each word separated by a #**

```python

def process_text_file(file_name):

with open(file_name, 'r') as file:

for line in file:

words = line.strip().split()

formatted_line = '#'.join(words)

print(formatted_line)

text_file_name = 'sample.txt'
process_text_file(text_file_name)

```

**10. Display the number of vowels/consonants/uppercase/lowercase characters in a text file**

```python

def count_characters(file_name):

vowels = "AEIOUaeiou"

consonants = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"

upper_count = lower_count = vowel_count = consonant_count = 0

with open(file_name, 'r') as file:

content = file.read()

for char in content:

if char.isupper():

upper_count += 1

elif char.islower():

lower_count += 1

if char in vowels:

vowel_count += 1

elif char in consonants:

consonant_count += 1

print("Uppercase:", upper_count)

print("Lowercase:", lower_count)

print("Vowels:", vowel_count)

print("Consonants:", consonant_count)

text_file_name = 'sample.txt'

count_characters(text_file_name)

```
**11. Remove lines containing 'a' and write to another file**

```python

def remove_lines_with_character(file_name, character, new_file_name):

with open(file_name, 'r') as file:

lines = file.readlines()

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

with open(new_file_name, 'w') as new_file:

new_file.writelines(filtered_lines)

input_file_name = 'input.txt'

output_file_name = 'output.txt'

remove_lines_with_character(input_file_name, 'a', output_file_name)

```

**12. Create and search in a binary file with name and roll number**

```python

import pickle

def create_binary_file(data, file_name):

with open(file_name, 'wb') as file:

pickle.dump(data, file)

def search_roll_number(file_name, target_roll):

with open(file_name, 'rb') as file:

data = pickle.load(file)

if target_roll in data:

print(f"Roll Number: {target_roll}, Name: {data[target_roll]}")

else:

print("Roll Number not found.")


students = {101: 'Alice', 102: 'Bob', 103: 'Charlie'}

binary_file_name = 'students.bin'

create_binary_file(students, binary_file_name)

search_roll_number(binary_file_name, 102)

```

**13. Create and update a binary file with roll number, name, and marks**

```python

import pickle

def create_binary_file(data, file_name):

with open(file_name, 'wb') as file:

pickle.dump(data, file)

def update_marks(file_name, target_roll, new_marks):

with open(file_name, 'rb') as file:

data = pickle.load(file)

if target_roll in data:

data[target_roll]['marks'] = new_marks

with open(file_name, 'wb') as file:

pickle.dump(data, file)

print("Marks updated.")

else:

print("Roll Number not found.")

students = {

101: {'name': 'Alice', 'marks': 85},

102: {'name': 'Bob', 'marks': 92},


103: {'name': 'Charlie', 'marks': 78}

binary_file_name = 'students_marks.bin'

create_binary_file(students, binary_file_name)

update_marks(binary_file_name, 102, 95)

```

**14. Random number generator (simulate a dice)**

```python

import random

def roll_dice():

return random.randint(1, 6)

print("Rolled:", roll_dice())

```

**15. Stack implementation using a list**

```python

class Stack:

def __init__(self):

self.items = []

def push(self, item):

self.items.append(item)

def pop(self):

if not self.is_empty():

return self.items.pop()
def is_empty(self):

return len(self.items) == 0

stack = Stack()

stack.push(1)

stack.push(2)

stack.push(3)

print("Popped:", stack.pop())

print("Popped:", stack.pop())

print("Is stack empty?", stack.is_empty())

```

Feel free to adapt and use these programs for your needs, or combine them to create more
comprehensive applications. Each program demonstrates a specific concept or task as outlined in
your original request.

You might also like