Homework Solutions
Homework 1: Variables and Data Types
- Declare and Print Variables:
# Declare variables
x = 5 # int
y = 3.14 # float
name = "John" # str
is_admin = True # bool
colors = ["red", "green", "blue"] # list
# Print variables
print("x =", x)
print("y =", y)
print("name =", name)
print("is_admin =", is_admin)
print("colors =", colors)
2. Basic Operations:
# Basic arithmetic operations
a = 5
b = 2
print("a + b =", a + b)
print("a - b =", a - b)
print("a * b =", a * b)
print("a / b =", a / b)
3. String Manipulation :
# String manipulation
s = " Hello, World! "
print("Original string:", s)
print("Upper case:", s.upper())
print("Lower case:", s.lower())
print("Strip whitespace:", s.strip())
Homework 2: Control Structures
- If-Else Statements:
# If-else statement
num = 10
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
For Loops:
# For loop
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print("Square of", num, "is", num ** 2)
While Loops:
# While loop
i = 1
while i <= 10:
print(i)
i += 1
Homework 3: Functions and Modules
- Simple Function:
# Simple function
def greet(name):
return "Hello, " + name + "!"
print(greet("John")) # Output: Hello, John!
Function with Arguments:
# Function with arguments
def add(a, b):
return a + b
print(add(2, 3)) # Output: 5
Importing Modules:
# Importing modules
import math
angle = 45
print("Sine of", angle, "degrees is", math.sin(math.radians(angle)))
print("Cosine of", angle, "degrees is", math.cos(math.radians(angle)))
Homework 4: Lists and Tuples
- List Operations:
# List operations
fruits = ["apple", "banana", "cherry"]
print("Original list:", fruits)
print("Index 0:", fruits[0])
print("Slice 1:2:", fruits[1:2])
fruits.append("orange")
print("After append:", fruits)
fruits.extend(["grape", "kiwi"])
print("After extend:", fruits)
Tuple Operations:
# Tuple operations
colors = ("red", "green", "blue")
print("Original tuple:", colors)
print("Index 0:", colors[0])
print("Slice 1:2:", colors[1:2])
List Comprehension:
# List comprehension
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print("Original list:", numbers)
print("Squares:", squares)
Project Solutions
Project 1: Calculator Program
# Calculator program
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
if b == 0:
return "Error: Division by zero!"
return a / b
print("Simple Calculator")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = int(input("Enter your choice (1-4): "))
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == 1:
result = add(num1, num2)
elif choice == 2:
result = sub(num1, num2)
elif choice == 3:
result = mul(num1, num2)
elif choice == 4:
result = div(num1, num2)
else:
result = "Error: Invalid choice!"
print("Result:", result)
Project 2: To-Do List App
# To-Do List App
tasks = []
def add_task(task):
tasks.append(task)
def remove_task(task):
if task in tasks:
tasks.remove(task)
else:
print("Task not found!")
def mark_completed(task):
if task in tasks:
tasks[tasks.index(task)] += " (Completed)"
else:
print("Task not found!")
while True:
print("To-Do List App")
print("1. Add task")
print("2. Remove task")
print("3. Mark task as completed")
print("4. Quit")
choice = int(input("Enter your choice (1-4): "))
if choice == 1:
task = input("Enter task: ")
add_task(task)
elif choice == 2:
task = input("Enter task to remove: ")
remove_task(task)
elif choice == 3:
task = input("Enter task to mark as completed: ")
mark_completed(task)
elif choice == 4:
break
else:
print("Error: Invalid choice!")
print("Tasks:", tasks)
Project 3: Rock, Paper, Scissors Game
# Rock, Paper, Scissors Game
import random
def play_game():
choices = ["rock", "paper", "scissors"]
computer_choice = random.choice(choices)
user_choice = input("Enter your choice (rock, paper, scissors): ")
if user_choice not in choices:
print("Error: Invalid choice!")
return
print("Computer chose:", computer_choice)
if user_choice == computer_choice:
print("It's a tie!")
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "paper" and computer_choice == "rock") or \
(user_choice == "scissors" and computer_choice == "paper"):
print("You win!")
else:
print("Computer wins!")
play_game()