Code and Output
Code and Output
print("\nVariable b:")
print("Value:", b)
print("Type:", type(b))
print("ID:", id(b))
print("\nVariable c:")
print("Value:", c)
print("Type:", type(c))
print("ID:", id(c))
print("\nVariable d:")
print("Value:", d)
print("Type:", type(d))
print("ID:", id(d))
print("\nVariable e:")
print("Value:", e)
print("Type:", type(e))
print("ID:", id(e))
print("\nVariable f:")
print("Value:", f)
print("Type:", type(f))
print("ID:", id(f))
Output:
Source code:
Prime number
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
except ValueError:
print("Please enter valid integer numbers.")
Output:
Source code:
Fibonacci series
def fibonacci(n):
"""Generate Fibonacci series up to n terms."""
fib_series = []
a, b = 0, 1
for _ in range(n):
fib_series.append(a)
a, b = b, a + b # Update a and b
return fib_series
if n <= 0:
print("Please enter a positive integer.")
else:
series = fibonacci(n)
print(f"Fibonacci series up to {n} terms: {series}")
except ValueError:
print("Please enter a valid integer.")
Output:
Source code:
# Sample string
text = "Hello, World!"
# Basic slicing
print("Original string:", text)
def word_frequency(text):
words = text.lower().split()
frequency = {}
frequency[word] = frequency.get(word, 0) + 1
sorted_frequency = dict(sorted(frequency.items()))
return sorted_frequency
# Example usage:
result = word_frequency(input_text)print(result)
Output:
Source code:
def sort_words():
# Split the input string into a list of words, stripping any extra spaces
sorted_words = sorted(words)
# Example usage
sort_words()
Output:
Source code:
def shopping_list_manager():
shopping_list = []
while True:
# Menu options
print("Choose an option:")
print("6. Exit")
if choice == '1':
shopping_list.append(item)
if item in shopping_list:
shopping_list.remove(item)
else:
shopping_list.sort()
shopping_list.clear()
break
else:
print("Invalid choice. Please select a valid option.")
if __name__ == "__main__":
shopping_list_manager()
Output:
Source code:
def contact_book_manager():
contact_book = {}
while True:
if choice == '1':
contact_book[name] = phone
print(f"Added: {name}")
print(f"Removed: {name}")
contact_book[name] = phone
print(f"Updated: {name}")
print("Contacts:", contact_book)
contact_book.clear()
print("Goodbye!")
Output:
Source code :
return (a + b, a * b)
# Creating a tuple
length = len(coordinates)
result = sum_and_product(x, y)
print(f"Coordinates: {coordinates}")
class Stack:
def __init__(self):
self.items = []
self.items.append(item)
def pop(self):
"""Remove and return the top item of the stack. Raise an error if the stack is empty."""
if self.is_empty():
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def show_stack(self):
"""Display the current items in the stack."""
if self.is_empty():
else:
print(item)
def main():
stack = Stack()
while True:
print("\nChoose an option:")
print("6. Exit")
if choice == '1':
stack.push(item)
print(f"Pushed {item} onto the stack.")
try:
popped_item = stack.pop()
except IndexError as e:
print(e)
if stack.is_empty():
else:
stack.show_stack()
print("Exiting.")
break
else:
if __name__ == "__main__":
main()
Output:
Source code:
class Queue:
def __init__(self):
self.queue = []
def is_empty(self):
return len(self.queue) == 0
self.queue.append(item)
print(f"Enqueued: {item}")
def dequeue(self):
if self.is_empty():
return None
item = self.queue.pop(0)
print(f"Dequeued: {item}")
return item
def peek(self):
if self.is_empty():
print("Queue is empty.")
return None
return self.queue[0]
def size(self):
return len(self.queue)
def display(self):
print("Queue:", self.queue)
if __name__ == "__main__":
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.display()
Output:
Source code:
file.write(content)
def read_from_file(file_path):
try:
content = file.read()
print(content)
except FileNotFoundError:
except Exception as e:
file_path = 'example.txt'
read_from_file(file_path)
Output:
Source code:
import shutil
import os
try:
if not os.path.isfile(source):
return
shutil.copy(source, destination)
except Exception as e:
source_file = 'path/to/source/file.txt'
destination_file = 'path/to/destination/file.txt'
copy_file(source_file, destination_file)
Output:
Source code:
def read(self):
print(f"Reading '{self.title}' by {self.author}...")
def display_info(self):
print(f"Title: {self.title}, Author: {self.author}, Pages: {self.pages}")
class Circle:
pi = 3.14159 # Class variable
# Instance method
def area(self):
return Circle.pi * (self.radius ** 2)
# Class method
@classmethod
def change_pi(cls, new_pi):
cls.pi = new_pi
# Static method
@staticmethod
def is_valid_radius(radius):
return radius > 0
class Book:
def __init__(self):
self.title = "Untitled" # Default title
self.author = "Unknown" # Default author
self.pages = 0 # Default number of pages
def display_info(self):
print(f"Title: {self.title}, Author: {self.author}, Pages: {self.pages}")
# Base class
class Animal:
self.name = name
def speak(self):
# Derived class
class Dog(Animal):
def speak(self):
class Cat(Animal):
def speak(self):
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Call methods
class Book:
self.title = title
self.author = author
def info(self):
class Library:
def __init__(self):
self.books.append(book)
def show_books(self):
if not self.books:
library = Library()
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
print(library.show_books())
Output:
Source code:
import tkinter as tk
import sqlite3
class ContactManager:
self.root = root
self.root.title("Contact Manager")
self.conn = sqlite3.connect("contacts.db")
self.create_table()
self.create_widgets()
self.populate_contacts()
def create_table(self):
with self.conn:
self.conn.execute('''
''')
def create_widgets(self):
tk.Label(self.root, text="Name").grid(row=0, column=0)
self.name_entry = tk.Entry(self.root)
self.name_entry.grid(row=0, column=1)
self.phone_entry = tk.Entry(self.root)
self.phone_entry.grid(row=1, column=1)
self.contacts_listbox.bind('<<ListboxSelect>>', self.load_contact)
def populate_contacts(self):
self.contacts_listbox.delete(0, tk.END)
def insert_contact(self):
with self.conn:
self.conn.execute("INSERT INTO contacts (name, phone) VALUES (?, ?)", (name,
phone))
self.populate_contacts()
self.clear_entries()
else:
def update_contact(self):
selected = self.contacts_listbox.curselection()
if selected:
contact_id = self.contacts_listbox.get(selected).split(":")[0]
with self.conn:
self.populate_contacts()
self.clear_entries()
else:
def delete_contact(self):
selected = self.contacts_listbox.curselection()
if selected:
contact_id = self.contacts_listbox.get(selected).split(":")[0]
with self.conn:
self.clear_entries()
else:
selected = self.contacts_listbox.curselection()
if selected:
self.name_entry.delete(0, tk.END)
self.phone_entry.delete(0, tk.END)
def clear_entries(self):
self.name_entry.delete(0, tk.END)
self.phone_entry.delete(0, tk.END)
if __name__ == "__main__":
root = tk.Tk()
app = ContactManager(root)
root.mainloop()
Output:
Source code:
print("\nBar Chart")
max_value = max(values)
scale = 50 / max_value
def print_histogram(data):
print("\nHistogram")
bins = [0] * 10
bins[index] += 1
for i in range(10):
total = sum(sizes)
num_symbols = int(percent / 2)
histogram_data = [72, 85, 90, 60, 77, 65, 88, 95, 80, 79]
print_bar_chart(categories, values)
print_histogram(histogram_data)
print_pie_chart(pie_sizes, pie_labels)
Output: