Python Basics: Continued Learning
Python Basics: Continued Learning
Welcome back to your Python journey! You've already learned the fundamentals - great job! Now let's dive deeper into what you can do with the skills you've acquired.
Understanding Your First Programs Better
Let me show you how to build upon your basic knowledge:
Improving Your Hello World Program
# Previous version:
print("Hello, World!")
# Enhanced version:
def greet_user():
name = input("What's your name? ")
print(f"Hello, {name}! Welcome to Python programming!")
greet_user()
Working with Lists More Effectively
You've learned about lists - now let's make them more powerful:
# Creating and manipulating a list of scores
scores = [85, 92, 78, 96, 88]
# Find the highest score
highest_score = max(scores)
print(f"Highest score: {highest_score}")
# Calculate average
average = sum(scores) / len(scores)
print(f"Average score: {average:.1f}") # .1f formats to 1 decimal place
# Sort scores from highest to lowest
scores.sort(reverse=True)
print("Scores in order:", scores)
# Find specific items
if 92 in scores:
print("Someone scored 92!")
Making More Complex Conditional Logic
Let's expand on conditional statements:
# Multiple conditions with logical operators
age = int(input("How old are you? "))
has_license = input("Do you have a driver's license? (y/n) ").lower() == 'y'
if age >= 18 and has_license:
print("You can drive!")
elif age >= 16 or (age < 18 and has_license):
print("You might be able to drive with restrictions")
else:
print("You're not old enough to drive yet")
# Nested conditions
temperature = float(input("What's the temperature? "))
if temperature > 30:
if temperature > 40:
print("Very hot! Stay hydrated!")
else:
print("Hot day, but manageable")
elif temperature < 10:
print("Cold weather - bundle up!")
else:
print("Comfortable temperature")
Better Functions with Parameters
You've written simple functions - now let's make them more useful:
# Function that takes multiple parameters
def calculate_area(length, width):
return length * width
area = calculate_area(5, 3)
print(f"Area: {area}")
# Function with default parameter values
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Uses default greeting
greet("Bob", "Hi there!") # Overrides default
# Function that returns multiple values
def get_name_parts(full_name):
parts = full_name.split()
return parts[0], parts[-1] # Returns first and last name
first, last = get_name_parts("John Smith")
print(f"First: {first}, Last: {last}")
Practical Examples Using What You Know
Example 1: Simple To-Do List Manager
def show_menu():
print("\n=== To-Do List ===")
print("1. Add task")
print("2. View tasks")
print("3. Complete task")
print("4. Exit")
def main():
tasks = []
while True:
show_menu()
choice = input("Choose an option (1-4): ")
if choice == "1":
task = input("Enter new task: ")
tasks.append(task)
print(f"Task '{task}' added!")
elif choice == "2":
if tasks:
print("\nYour tasks:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
else:
print("No tasks yet!")
elif choice == "3":
if tasks:
try:
index = int(input("Enter task number to complete: ")) - 1
completed_task = tasks.pop(index)
print(f"Completed: {completed_task}")
except (ValueError, IndexError):
print("Invalid task number!")
else:
print("No tasks to complete!")
elif choice == "4":
print("Goodbye!")
break
else:
print("Invalid option!")
# Uncomment the line below to run the program
# main()
Example 2: Simple Calculator with Error Handling
def safe_input(prompt, input_type=float):
while True:
try:
return input_type(input(prompt))
except ValueError:
print("Please enter a valid number!")
def calculator():
print("Simple Calculator")
# Get numbers safely
num1 = safe_input("Enter first number: ")
operator = input("Enter operator (+, -, *, /): ")
num2 = safe_input("Enter second number: ")
# Perform calculation
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 != 0:
result = num1 / num2
else:
print("Error: Cannot divide by zero!")
return
else:
print("Invalid operator!")
return
print(f"Result: {num1} {operator} {num2} = {result}")
# Uncomment to run calculator
# calculator()
File Input/Output Basics
You can save data from your programs:
# Writing data to a file
def save_scores():
scores = [85, 92, 78, 96]
with open("scores.txt", "w") as file:
for score in scores:
file.write(f"{score}\n")
print("Scores saved to file!")
# Reading data from a file
def read_scores():
try:
with open("scores.txt", "r") as file:
content = file.read()
print("Contents of scores.txt:")
print(content)
except FileNotFoundError:
print("File not found. Create it first!")
# Uncomment to test:
# save_scores()
# read_scores()
Working with Dictionaries (Quick Introduction)
Since you've learned lists, here's how dictionaries work - they're like advanced lists:
# Dictionary: key-value pairs instead of just indexed values
student = {
"name": "Alice",
"age": 20,
"grade": "A"
}
print(student["name"]) # Alice
student["age"] = 21 # Change age
student["major"] = "Computer Science" # Add new key-value
# Loop through dictionary
for key, value in student.items():
print(f"{key}: {value}")
# Check if key exists
if "grade" in student:
print("Student has a grade!")
Making Your Programs More Interactive
Here's how to make programs more user-friendly:
def get_user_info():
"""Get user information with validation"""
# Get name safely
while True:
name = input("Enter your name: ").strip()
if len(name) > 0:
break
print("Please enter a valid name!")
# Get age safely
while True:
try:
age = int(input("Enter your age: "))
if 0 <= age <= 150:
break
else:
print("Age must be between 0 and 150")
except ValueError:
print("Please enter a valid number!")
return name, age
# Test the function
# user_name, user_age = get_user_info()
# print(f"Hello {user_name}, you are {user_age} years old!")
Debugging Your Code
Learning to find and fix errors in your code:
def calculate_average(numbers):
# Let's add some debugging information
print(f"Input numbers: {numbers}")
if len(numbers) == 0:
print("Warning: No numbers provided")
return 0
total = sum(numbers)
average = total / len(numbers)
print(f"Total: {total}, Average: {average}")
return average
# Test with different inputs
calculate_average([1, 2, 3])
calculate_average([])
Real-World Application: Grade Calculator
Let's create something practical that combines everything you've learned:
def grade_calculator():
"""Simple grade calculator"""
print("=== Grade Calculator ===")
# Collect grades
subjects = []
grades = []
while True:
subject = input("\nEnter subject name (or 'done' to finish): ").strip()
if subject.lower() == 'done':
break
try:
grade = float(input(f"Enter grade for {subject}: "))
if 0 <= grade <= 100:
subjects.append(subject)
grades.append(grade)
else:
print("Grade must be between 0 and 100!")
except ValueError:
print("Please enter a valid number!")
# Calculate results
if len(grades) > 0:
average = sum(grades) / len(grades)
print("\n=== Results ===")
for i, subject in enumerate(subjects):
print(f"{subject}: {grades[i]}")
print(f"Average: {average:.1f}")
# Letter grade
if average >= 90:
letter = "A"
elif average >= 80:
letter = "B"
elif average >= 70:
letter = "C"
elif average >= 60:
letter = "D"
else:
letter = "F"
print(f"Letter Grade: {letter}")
else:
print("No grades entered!")
# Uncomment to run
# grade_calculator()
What You've Mastered So Far
You now know how to:
Create and use variables with different data types
Get input from users
Perform mathematical operations
Make decisions using conditional statements
Repeat actions with loops
Create reusable code with functions
Store multiple items in lists
Work with strings effectively
Next Steps for Your Learning Journey
Now that you've built a solid foundation, here are some topics to explore:
- Error Handling - Making programs more robust
- Modules and Libraries - Using pre-built tools
- Working with Files - Reading from and writing to files
- More Data Structures - Dictionaries and tuples
- Object-Oriented Programming - Creating classes and objects
Keep practicing these concepts, and you'll be amazed at how much more powerful your Python programs can become!
Remember: Every line of code you write makes you a better programmer!