Source code:
# Create different types of variables
a = 10 # Integer
b = 3.14 # Float
c = "Hello, World!" # String
d = [1, 2, 3] # List
e = (1, 2, 3) # Tuple
f = { 'key': 'value' } # Dictionary
# Use id() and type() functions
print("Variable a:")
print("Value:", a)
print("Type:", type(a))
print("ID:", id(a))
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
def find_primes_in_range(start, end):
"""Find and return all prime numbers in a given range."""
primes = []
for num in range(start, end + 1):
if is_prime(num):
primes.append(num)
return primes
# Get user input for the range
try:
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
if start > end:
print("Starting number must be less than or equal to ending number.")
else:
primes = find_primes_in_range(start, end)
print(f"Prime numbers between {start} and {end}: {primes}")
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
# Get user input for the number of terms
try:
n = int(input("Enter the number of terms in Fibonacci 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)
# Slicing the first 5 characters
first_five = text[:5]
print("First five characters:", first_five)
# Slicing from index 7 to the end
from_seven = text[7:]
print("Substring from index 7 to the end:", from_seven)
# Slicing from index 0 to 4 (up to but not including 5)
up_to_five = text[0:5]
print("Substring from index 0 to 4:", up_to_five)
# Slicing with a step
every_second = text[::2]
print("Every second character:", every_second)
# Slicing with negative indices
last_five = text[-5:]
print("Last five characters:", last_five)
# Reversing the string using slicing
reversed_text = text[::-1]
print("Reversed string:", reversed_text)
Output:
Source code:
def word_frequency(text):
# Split the text into words, convert to lowercase for uniformity
words = text.lower().split()
# Create a dictionary to hold word frequencies
frequency = {}
# Count the frequency of each word
for word in words:
# Remove punctuation if needed (simple implementation)
word = ''.join(char for char in word if char.isalnum())
if word: # Ensure the word is not empty
frequency[word] = frequency.get(word, 0) + 1
# Sort the keys alphanumerically
sorted_frequency = dict(sorted(frequency.items()))
return sorted_frequency
# Example usage:
input_text = "Hello world! Hello everyone. Welcome to the world of programming."
result = word_frequency(input_text)print(result)
Output:
Source code:
def sort_words():
# Accept input from the user
input_sequence = input("Enter a comma-separated sequence of words: ")
# Split the input string into a list of words, stripping any extra spaces
words = [word.strip() for word in input_sequence.split(',')]
# Sort the words alphabetically
sorted_words = sorted(words)
# Join the sorted words back into a comma-separated string
sorted_sequence = ', '.join(sorted_words)
# Print the result
print("Sorted words:", sorted_sequence)
# Example usage
sort_words()
Output:
Source code:
def shopping_list_manager():
# Initialize an empty shopping list
shopping_list = []
print("Welcome to the Shopping List Manager!")
while True:
# Display the current shopping list
print("\nCurrent shopping list:", shopping_list)
# Menu options
print("Choose an option:")
print("1. Add an item")
print("2. Remove an item")
print("3. Sort the list")
print("4. Check the number of items")
print("5. Clear the list")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
if choice == '1':
item = input("Enter the item to add: ")
shopping_list.append(item)
print(f"'{item}' has been added to the shopping list.")
elif choice == '2':
item = input("Enter the item to remove: ")
if item in shopping_list:
shopping_list.remove(item)
print(f"'{item}' has been removed from the shopping list.")
else:
print(f"'{item}' is not in the shopping list.")
elif choice == '3':
shopping_list.sort()
print("The shopping list has been sorted.")
elif choice == '4':
print("Number of items in the shopping list:", len(shopping_list))
elif choice == '5':
shopping_list.clear()
print("The shopping list has been cleared.")
elif choice == '6':
print("Exiting the Shopping List Manager. Goodbye!")
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 = {}
print("Welcome to the Contact Book Manager!")
while True:
print("\nCurrent Contacts:", contact_book)
print("\n1. Add\n2. Remove\n3. Update\n4. Search\n5. List\n6. Clear\n7. Exit")
choice = input("Choose an option (1-7): ")
if choice == '1':
name = input("Enter name: ")
phone = input("Enter phone: ")
contact_book[name] = phone
print(f"Added: {name}")
elif choice == '2':
name = input("Enter name to remove: ")
contact_book.pop(name, None) # Removes if exists
print(f"Removed: {name}")
elif choice == '3':
name = input("Enter name to update: ")
if name in contact_book:
phone = input("Enter new phone: ")
contact_book[name] = phone
print(f"Updated: {name}")
elif choice == '4':
name = input("Enter name to search: ")
print(f"{name}: {contact_book.get(name, 'Not found')}")
elif choice == '5':
print("Contacts:", contact_book)
elif choice == '6':
contact_book.clear()
print("All contacts cleared.")
elif choice == '7':
print("Goodbye!")
Output:
Source code :
# Function to calculate the sum and product of two numbers
def sum_and_product(a, b):
return (a + b, a * b)
# Creating a tuple
coordinates = (10, 20)
# Using tuple functions
length = len(coordinates)
x, y = coordinates # Tuple unpacking
# Getting sum and product
result = sum_and_product(x, y)
# Accessing tuple elements
sum_result, product_result = result
# Output the results
print(f"Coordinates: {coordinates}")
print(f"Length of coordinates tuple: {length}")
print(f"Sum: {sum_result}, Product: {product_result}")
Output:
Source code:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
"""Add an item to the top of the stack."""
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():
raise IndexError("pop from empty stack")
return self.items.pop()
def is_empty(self):
"""Check if the stack is empty."""
return len(self.items) == 0
def size(self):
"""Return the number of items in the stack."""
return len(self.items)
def show_stack(self):
"""Display the current items in the stack."""
if self.is_empty():
print("The stack is empty.")
else:
print("Current stack (top to bottom):")
for item in reversed(self.items):
print(item)
def main():
stack = Stack()
while True:
print("\nChoose an option:")
print("1. Push an item")
print("2. Pop an item")
print("3. Check if the stack is empty")
print("4. Get the size of the stack")
print("5. Show the stack")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
if choice == '1':
item = input("Enter an item to push: ")
stack.push(item)
print(f"Pushed {item} onto the stack.")
elif choice == '2':
try:
popped_item = stack.pop()
print(f"Popped {popped_item} from the stack.")
except IndexError as e:
print(e)
elif choice == '3':
if stack.is_empty():
print("The stack is empty.")
else:
print("The stack is not empty.")
elif choice == '4':
print(f"The size of the stack is: {stack.size()}")
elif choice == '5':
stack.show_stack()
elif choice == '6':
print("Exiting.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Output:
Source code:
class Queue:
def __init__(self):
self.queue = []
def is_empty(self):
return len(self.queue) == 0
def enqueue(self, item):
self.queue.append(item)
print(f"Enqueued: {item}")
def dequeue(self):
if self.is_empty():
print("Queue is empty. Cannot dequeue.")
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:
def write_to_file(file_path, content):
with open(file_path, 'w') as file:
file.write(content)
print(f"Content written to '{file_path}'.")
def read_from_file(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
print(f"Content read from '{file_path}':")
print(content)
except FileNotFoundError:
print(f"The file '{file_path}' does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
file_path = 'example.txt'
write_to_file(file_path, "Hello, this is a test file.\nWelcome to file handling in Python!")
read_from_file(file_path)
Output:
Source code:
import shutil
import os
def copy_file(source, destination):
try:
if not os.path.isfile(source):
print(f"The source file '{source}' does not exist.")
return
shutil.copy(source, destination)
print(f"File '{source}' has been copied to '{destination}'.")
except Exception as e:
print(f"An error occurred: {e}")
source_file = 'path/to/source/file.txt'
destination_file = 'path/to/destination/file.txt'
copy_file(source_file, destination_file)
Output:
Source code:
# Define a class called Book
class Book:
def __init__(self, title, author, pages):
self.title = title # Instance variable for book title
self.author = author # Instance variable for book author
self.pages = pages # Instance variable for number of pages
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}")
# Create instances (objects) of the Book class
book1 = Book("To Kill a Mockingbird", "Harper Lee", 281)
book2 = Book("1984", "George Orwell", 328)
# Call methods on the objects
book1.read() # Output: Reading 'To Kill a Mockingbird' by Harper Lee...
book1.display_info() # Output: Title: To Kill a Mockingbird, Author: Harper Lee, Pages: 281
book2.read() # Output: Reading '1984' by George Orwell...
book2.display_info() # Output: Title: 1984, Author: George Orwell, Pages: 328
Output:
Source code:
class Circle:
pi = 3.14159 # Class variable
def __init__(self, radius):
self.radius = radius
# 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
# Create an instance of Circle
circle1 = Circle(5)
# Using instance method
print(f"Area of circle1: {circle1.area()}") # Output: Area of circle1: 78.53975
# Using class method to change the value of pi
Circle.change_pi(3.14)
print(f"New area of circle1 after changing pi: {circle1.area()}") # Output: New area of circle1:
78.5
# Using static method to validate radius
print(Circle.is_valid_radius(circle1.radius)) # Output: True
print(Circle.is_valid_radius(-5)) # Output: False
Output:
Source code:
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}")
# Create an instance of Book using the default constructor
my_book = Book()
my_book.display_info() # Output: Title: Untitled, Author: Unknown, Pages: 0
# You can also print the attributes directly
print(f"Book's title: {my_book.title}, author: {my_book.author}, pages: {my_book.pages}")
# Output: Book's title: Untitled, author: Unknown, pages: 0
Output:
Source code:
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "I am an animal."
# Derived class
class Dog(Animal):
def speak(self):
return "Woof! My name is " + self.name
class Cat(Animal):
def speak(self):
return "Meow! My name is " + self.name
# Create instances of Dog and Cat
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Call methods
print(dog.speak()) # Output: Woof! My name is Buddy
print(cat.speak()) # Output: Meow! My name is Whiskers
Output:
Source code:
# Class representing a Book
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def info(self):
return f"{self.title} by {self.author}"
# Class representing a Library
class Library:
def __init__(self):
self.books = [] # A library contains books
def add_book(self, book):
self.books.append(book)
def show_books(self):
if not self.books:
return "No books in the library."
return "\n".join(book.info() for book in self.books)
# Create instances of Book
book1 = Book("1984", "George Orwell")
book2 = Book("To Kill a Mockingbird", "Harper Lee")
book3 = Book("The Great Gatsby", "F. Scott Fitzgerald")
# Create an instance of Library
library = Library()
# Add books to the library
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
# Show all books in the library
print(library.show_books())
Output:
Source code:
import tkinter as tk
from tkinter import messagebox
import sqlite3
class ContactManager:
def __init__(self, root):
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('''
CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
phone TEXT NOT NULL
''')
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)
tk.Label(self.root, text="Phone").grid(row=1, column=0)
self.phone_entry = tk.Entry(self.root)
self.phone_entry.grid(row=1, column=1)
tk.Button(self.root, text="Insert", command=self.insert_contact).grid(row=2, column=0)
tk.Button(self.root, text="Update", command=self.update_contact).grid(row=2, column=1)
tk.Button(self.root, text="Delete", command=self.delete_contact).grid(row=2, column=2)
self.contacts_listbox = tk.Listbox(self.root, width=50)
self.contacts_listbox.grid(row=3, column=0, columnspan=3)
self.contacts_listbox.bind('<<ListboxSelect>>', self.load_contact)
def populate_contacts(self):
self.contacts_listbox.delete(0, tk.END)
for row in self.conn.execute("SELECT * FROM contacts"):
self.contacts_listbox.insert(tk.END, f"{row[0]}: {row[1]} - {row[2]}")
def insert_contact(self):
name, phone = self.name_entry.get(), self.phone_entry.get()
if name and phone:
with self.conn:
self.conn.execute("INSERT INTO contacts (name, phone) VALUES (?, ?)", (name,
phone))
self.populate_contacts()
self.clear_entries()
else:
messagebox.showwarning("Input Error", "Provide both name and phone.")
def update_contact(self):
selected = self.contacts_listbox.curselection()
if selected:
contact_id = self.contacts_listbox.get(selected).split(":")[0]
name, phone = self.name_entry.get(), self.phone_entry.get()
with self.conn:
self.conn.execute("UPDATE contacts SET name=?, phone=? WHERE id=?", (name,
phone, contact_id))
self.populate_contacts()
self.clear_entries()
else:
messagebox.showwarning("Selection Error", "Select a contact to update.")
def delete_contact(self):
selected = self.contacts_listbox.curselection()
if selected:
contact_id = self.contacts_listbox.get(selected).split(":")[0]
with self.conn:
self.conn.execute("DELETE FROM contacts WHERE id=?", (contact_id,))
self.populate_contacts()
self.clear_entries()
else:
messagebox.showwarning("Selection Error", "Select a contact to delete.")
def load_contact(self, event):
selected = self.contacts_listbox.curselection()
if selected:
contact = self.contacts_listbox.get(selected).split(": ")
self.name_entry.delete(0, tk.END)
self.name_entry.insert(0, contact[1].split(" - ")[0])
self.phone_entry.delete(0, tk.END)
self.phone_entry.insert(0, contact[1].split(" - ")[1])
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:
def print_bar_chart(categories, values):
print("\nBar Chart")
max_value = max(values)
scale = 50 / max_value
for category, value in zip(categories, values):
bar_length = int(value * scale)
print(f"{category}: {'#' * bar_length} ({value})")
def print_histogram(data):
print("\nHistogram")
bins = [0] * 10
for score in data:
index = min(int(score // 10), 9)
bins[index] += 1
for i in range(10):
print(f"{i * 10}-{(i + 1) * 10 - 1}: {'#' * bins[i]} ({bins[i]})")
def print_pie_chart(sizes, labels):
print("\nPie Chart (Approximation)")
total = sum(sizes)
for size, label in zip(sizes, labels):
percent = (size / total) * 100 # Removed the stray '5'
num_symbols = int(percent / 2)
print(f"{label}: {'#' * num_symbols} ({percent:.1f}%)")
# Data for charts
categories = ['A', 'B', 'C', 'D']
values = [10, 15, 7, 20]
histogram_data = [72, 85, 90, 60, 77, 65, 88, 95, 80, 79]
pie_sizes = [30, 20, 40, 10]
pie_labels = ['Group 1', 'Group 2', 'Group 3', 'Group 4']
# Generate the charts
print_bar_chart(categories, values)
print_histogram(histogram_data)
print_pie_chart(pie_sizes, pie_labels)
Output: