Statement of Completion#49be6e77
Python Basics
medium
Mastering Python Basics Through Code Debugging
Resolution
Activities
Project.ipynb
Python Basics Capstone¶
1. Data Analysis at DataWars¶
In [ ]:
2. Missing Sale Alert¶
In [1]:
def check_sales(daily_sales):
if daily_sales > 100:
return "Good sales day!"
else:
return "Missing target"
sales = 150
check_sales(sales)
Out[1]:
'Good sales day!'
3. Bug Hunt: The Missing Projects¶
In [3]:
def add_projects(project1, project2):
total = 0
total += project1 # Line with bug
total += project2
return total
# Test the function
result = add_projects(5, 3)
print(f"Total projects: {result}")
Total projects: 8
4. Temperature Tracker¶
In [8]:
def check_temperature(temp):
if temp >= 38:
return "Fever! Rest needed"
return "Normal temperature"
temp = 37.5
result = check_temperature(temp)
print(result)
Normal temperature
5. Fix the Patient Counter¶
In [10]:
def add_patient(total):
total += 1
return total
patients = 5
new_total = add_patient(patients)
print(f"Total patients: {new_total}")
Total patients: 6
6. Create Patient Record Variables¶
In [126]:
# Create variables for patient information
patient_name = "John Miller"
patient_age = 45
patient_temp = 36.8
has_insurance = True
# Display patient information
print(f"Patient: {patient_name}")
print(f"Age: {patient_age}")
print(f"Temperature: {patient_temp}°C")
print(f"Insurance: {has_insurance}")
Patient: John Miller Age: 45 Temperature: 36.8°C Insurance: True
7. Create Weather App Variables¶
In [20]:
# Create weather variables
location = 'New York City'
temperature = 22.5
conditions = 'Partly cloudy'
rain_chance = 0.30
is_daytime = True
# Display dashboard
print("Weather Dashboard:")
print(location)
print(f"Temperature: {round(temperature, 1)}°C")
print(f"Conditions: {conditions}")
print(f"Rain Chance: {rain_chance * 100}%")
print(f"Daylight: {is_daytime}")
Weather Dashboard: New York City Temperature: 22.5°C Conditions: Partly cloudy Rain Chance: 30.0% Daylight: True
8. Create E-commerce Product Variables¶
In [26]:
# Create product variables
product_name = 'Gaming Laptop XR-5'
price = 1299.99
stock = 5
free_shipping = True
rating = 4.7
# Display product information
print(f"Product: {product_name}")
print(f"Price: ${price}")
print(f"Stock: {stock} units")
print(f"Free Shipping: {free_shipping}")
print(f"Rating: {rating}/5")
Product: Gaming Laptop XR-5 Price: $1299.99 Stock: 5 units Free Shipping: True Rating: 4.7/5
9. Create a Doctor's Appointment Function¶
In [34]:
def schedule_appointment(name, time):
try:
if not name:
raise ValueError('Error: Name required')
return f"Appointment confirmed for {name} at {time}"
except ValueError:
return "Error: Name required"
schedule_appointment('', '15:00')
Out[34]:
'Error: Name required'
10. Restaurant Bill Calculator¶
In [42]:
def calculate_bill(meal_cost, tip_percent):
bill = meal_cost + (meal_cost * (tip_percent/100))
return f"Subtotal: ${meal_cost:.2f}, Total with {tip_percent}% tip: ${bill:.2f}"
bill = calculate_bill(36.50, 15)
print(bill)
Subtotal: $36.50, Total with 15% tip: $41.98
11. Create a Movie Rating Predictor¶
In [52]:
def predict_rating(length, genre):
# Your code here
if length > 180:
return "Too long, likely 2/5"
elif genre.lower() == 'action':
return "Popular! 4/5"
else:
return "Standard 3/5"
predict_rating(150, 'Action')
Out[52]:
'Popular! 4/5'
12. Create a Social Media Post Analyzer¶
In [57]:
def analyze_engagement(likes, comments, shares):
try:
if likes < 0 or comments < 0 or shares < 0:
raise ValueError
elif likes + comments + shares > 1000:
return "Viral post!"
else:
return "Normal post"
except ValueError:
return "Invalid input: numbers must be positive"
analyze_engagement(50, 10, -5)
Out[57]:
'Invalid input: numbers must be positive'
13. Fix the Playlist Manager¶
In [60]:
def manage_playlist(song, rating):
top_song = ""
if rating > 4.0:
top_song = song
elif rating >= 3.0:
print('Good song!')
else:
print('Skip this one')
return top_song
manage_playlist("Random Song", 3.5)
Good song!
Out[60]:
''
14. Pizza Order Calculator¶
In [72]:
def calculate_pizza_price(size):
size = size.lower()
if size == "small":
price = 8.99
elif size == "medium":
price = 12.99
elif size == "large":
price = 15.99
else:
return "Error: Choose small, medium, or large only"
return f"{size.capitalize()} pizza: ${price}"
15. Calculate Student Grade¶
In [86]:
def calculate_grade(score):
if score >= 90:
return "A - Excellent!"
elif score >= 80:
return "B - Good job"
elif score >= 70:
return "C - More practice needed"
else:
return "Below C - Schedule tutoring"
print(calculate_grade(95))
print(calculate_grade(83))
print(calculate_grade(75))
print(calculate_grade(65))
A - Excellent! B - Good job C - More practice needed Below C - Schedule tutoring
16. Coffee Shop Order Validator¶
In [90]:
def validate_coffee_order(size, coffee_type, temperature):
# Convert to lowercase
size = size.lower()
coffee_type = coffee_type.lower()
temperature = temperature.lower()
try:
if size not in ['small', 'medium', 'large']:
raise ValueError("Invalid size")
elif coffee_type not in ['espresso', 'latte', 'cappuccino']:
raise ValueError("Invalid coffee type")
elif temperature not in ['hot', 'iced']:
raise ValueError("Invalid temperature")
else:
return "Valid order"
except ValueError as e:
return f"{e}"
print(validate_coffee_order("medium", "latte", "hot"))
print(validate_coffee_order("huge", "mocha", "warm"))
print(validate_coffee_order("small", "espresso", "cold"))
Valid order Invalid size Invalid temperature
17. Movie Ticket Price Calculator¶
In [102]:
def calculate_ticket_price(age, is_tuesday):
base_price = 12
if age < 12:
price = base_price * 0.5
elif age > 65:
price = base_price * 0.7
else:
price = base_price
if is_tuesday:
price = price - 2
return round(price, 2)
18. Fitness Goal Calculator¶
In [105]:
def calculate_fitness_goal(current_weight, target_weight, weekly_rate):
# Validate weekly rate (0.5-1 kg)
try:
if weekly_rate < 0.5 or weekly_rate > 1:
raise ValueError("Weekly rate must be between 0.5-1 kg")
# Return error if invalid
except ValueError as e:
return f"{e}"
# Calculate weeks needed
weeks = (current_weight - target_weight)/weekly_rate
return round(weeks)
print(calculate_fitness_goal(80, 70, 0.5))
print(calculate_fitness_goal(85, 75, 1.0))
20 10
19. Mobile Data Usage Alert¶
In [109]:
def check_data_usage(gb_used, days_left):
# Calculate remaining data
limit = 50
usage = gb_used/limit
remaining = (limit - gb_used)/days_left
# Return warning or safe message
if usage >= 0.8:
return f"Warning: {limit - gb_used}GB left for {days_left} days"
else:
return f"Safe: {remaining}GB/day available"
print(check_data_usage(40, 10))
print(check_data_usage(20, 15))
Warning: 10GB left for 10 days Safe: 2.0GB/day available
20. Account Login Handler¶
In [124]:
def validate_login(username, password):
try:
if len(username) < 5:
raise ValueError("Username too short")
if not any(char.isdigit() for char in password):
raise ValueError("Password must contain numbers")
return "Login successful"
except ValueError as e:
return f"Error: {str(e)}"
In [ ]: