π― What Will You Learn?
Welcome to the foundation of your AI Superhero journey! In this session, you'll master the core tools every Python programmer needs. Don't worry if it seems like a lotβwe'll break it down into bite-sized, digestible pieces.
Variables & Types
Learn how to store and work with different kinds of information in your code.
Input & Output
Talk to your users! Ask questions and display amazing results.
Loops & Conditionals
Make smart decisions and repeat tasks like a coding champion.
Lists & Dictionaries
Organize your data like a superhero organizes their arsenal!
π¦ Section 1: Variables & Data Types
What is a Variable?
Think of a variable as a labeled box π¦. You put information inside, give it a name (label), and can use it whenever you need it.
π§ Remember: Think of the Labeled Box Concept
Just like you might have a box labeled "Toys" that holds action figures, or a box labeled "Snacks" that holds your favorite treats, variables are labeled boxes that hold information!
The 6 Essential Python Data Types
1. Integer (int) π’
Definition: Whole numbers (no decimal point). Positive, negative, or zero.
Examples: 42, -5, 0, 2024, 999
age = 12
score = 95
temperature = -3
players = 0
2. Float (float) π
Definition: Decimal numbers (with a decimal point). Used for measurements and prices.
Examples: 3.14, 9.99, 2.5, 0.01
height = 5.5
price = 9.99
pi = 3.14159
discount = 0.25
3. String (str) π
Definition: Text data. Anything in quotes is a string (words, sentences, even numbers as text!).
Examples: "Hello", "Python is fun!", "2024", "π"
name = "Asim"
greeting = "Hello, Superhero!"
city = "New York"
emoji = "π"
4. Boolean (bool) β β
Definition: True/False values. Used for yes/no, on/off decisions.
Examples: True, False (note the capital letters!)
is_sunny = True
is_raining = False
is_homework_done = True
can_play = False
5. List (list) π
Definition: A collection of items in order. Like a shopping list where the order matters.
Examples: [1, 2, 3], ["apple", "banana", "orange"], [True, False, True]
colors = ["red", "blue", "green", "yellow"]
scores = [95, 87, 92, 88]
mixed = ["apple", 5, True, 3.14]
6. Dictionary (dict) ποΈ
Definition: A collection of paired information (key-value pairs). Like a real dictionary where you look up a word to find its meaning.
Examples: {"name": "Asim"}, {"age": 12, "grade": 7}
student = {"name": "Asim", "age": 12, "grade": "7"}
book = {"title": "Python Fun", "pages": 250, "price": 9.99}
superhero = {"name": "Spider-Man", "power": "Web-Slinging"}
π Challenge Yourself!
Create variables of each type with information about yourself: your name (string), age (integer), height in feet (float), whether you like coding (boolean), favorite foods (list), and your daily schedule (dictionary). Go!)
π¬ Section 2: Input & Output in Python
The Conversation Framework
Every program needs to talk to users. This means:
- Input: Getting information FROM the user (asking questions)
- Output: Sending information TO the user (showing results)
Input: Asking Your Users Questions β
Use the input() function to ask users for information:
name = input("What is your name? ")
print("Hello, " + name + "!")
How it works:
- The
input()function shows a question to the user - The user types their answer
- The answer gets stored in the variable (in this case,
name)
π‘ Pro Tip: input() Always Returns Text
Remember: input() always gives you a STRING, even if the user types a number! If you need a number, you need to convert it using int() or float().
Converting Input to Numbers
age_text = input("How old are you? ")
age = int(age_text) # Convert text to number
Or simpler, all in one line:
age = int(input("How old are you? "))
Output: Showing Results to Users πΊ
Use the print() function to display information:
print("Hello, World!")
print("I love Python!")
print(42)
print(3.14)
name = "Asim"
age = 12
print(name)
print(age)
Combining Input & Output: A Complete Example! π
# Get information from the user
superhero_name = input("What's your superhero name? ")
power = input("What's your superpower? ")
age = int(input("How old are you? "))
# Process the information
birth_year = 2024 - age
# Show the results
print("\n--- Your Superhero Profile ---")
print("Name: " + superhero_name)
print("Power: " + power)
print("Age: " + str(age))
print("Probably born in: " + str(birth_year))
π Try It Yourself!
Create a program that asks for 3 pieces of information about yourself (name, favorite food, favorite movie) and then prints them back out in a cool format. Test it!
π Section 3: Decisions & Repetition (If-Else & Loops)
Part A: Making Decisions with If-Else β β
Programs need to make decisions based on information. "If this is true, do this. Otherwise, do that."
Comparison Operators: The Decision Tools
Before using if-else, you need to know how to compare values:
==!=><>=<=Your First If-Else Statement
age = int(input("How old are you? "))
if age >= 13:
print("You can play the video game!")
else:
print("Wait a bit longer, young padawan!")
π‘ Indentation Matters!
In Python, indentation (spacing at the beginning of lines) is SUPER important! The code inside the if block must be indented. Think of it as showing which code "belongs" to the if statement.
Real-World Example: Grade Checker
score = int(input("Enter your test score: "))
if score >= 90:
print("π A - Excellent work, Superhero!")
elif score >= 80:
print("β¨ B - Great job!")
elif score >= 70:
print("π C - Good effort!")
else:
print("πͺ Keep practicing! You'll get there!")
Notice we used elif (meaning "else if"). This lets us check multiple conditions!
Part B: Repeating Code with For Loops π
Sometimes you need to do the same thing multiple times. Instead of writing the code 100 times, use a loop!
Your First For Loop
for count in range(5):
print("Count: " + str(count))
print("Blastoff! π")
How it works: The variable count starts at 0 and goes up to 4 (range(5) means 0 through 4). The code inside the loop runs 5 times, each time with a different value for count.
Looping Through a List
foods = ["Pizza", "Pasta", "Ice Cream", "Fruit"]
for food in foods:
print(f"I love {food}!")
This is a for-in loop. It goes through each item in the list, one by one.
π Loop Analogy
Imagine you have a stack of dishes to wash. A for loop is like saying: "For each dish in the stack, wash it, then move to the next one." Easy!
Complete Example: Printing a Times Table
number = 5
print(f"The {number} Times Table:")
for i in range(1, 11):
result = number * i
print(f"{number} Γ {i} = {result}")
ποΈ Section 4: Lists & Dictionaries - Organizing Data
As a programmer, you'll often work with collections of information. Python gives you two amazing tools: lists and dictionaries.
Part A: Lists π - The Ordered Collection
What is a List?
A list is like a shopping list or a to-do list. Items are stored in order, and you can access them by their position (starting from 0!).
Creating and Using Lists
# Create a list of favorite superheroes
heroes = ["Spider-Man", "Wonder Woman", "Black Panther", "Captain Marvel"]
# Access items by position (remember: counting starts at 0!)
print(heroes[0]) # Spider-Man (first item)
print(heroes[1]) # Wonder Woman (second item)
print(heroes[3]) # Captain Marvel (fourth item)
π‘ Indexing Starts at 0!
In Python, the first item in a list is at position 0, the second at position 1, etc. This might feel weird at first, but it's how all programming languages work. Remember: 0, 1, 2, 3...
List Operations: Adding, Removing, Modifying
scores = [95, 87, 92]
# Add an item
scores.append(88)
print(scores) # [95, 87, 92, 88]
# Remove an item
scores.remove(87)
print(scores) # [95, 92, 88]
# Change an item
scores[0] = 100
print(scores) # [100, 92, 88]
# Get the length (how many items)
print(len(scores)) # 3
Looping Through a List
tasks = ["Complete homework", "Practice coding", "Help a friend", "Celebrate!"]
print("Today's Superhero Tasks:")
for i, task in enumerate(tasks):
print(f"{i + 1}. {task}")
Part B: Dictionaries ποΈ - The Key-Value Collection
What is a Dictionary?
A dictionary is like a real dictionary π. Instead of looking up items by position (0, 1, 2...), you look them up by a "key". Each key has a corresponding "value".
Real-World Example: Phone Book
# Phone book - keys are names, values are numbers
phone_book = {
"Asim": "555-0123",
"Sarah": "555-0456",
"Marcus": "555-0789",
"Emma": "555-1011"
}
# Look up a phone number
print(phone_book["Asim"]) # 555-0123
print(phone_book["Sarah"]) # 555-0456
Adding and Modifying Dictionary Items
student = {"name": "Asim", "grade": 7, "score": 95}
# Add a new key-value pair
student["age"] = 12
print(student)
# Change a value
student["score"] = 98
print(student)
# Delete an item
del student["age"]
print(student)
Looping Through Dictionaries
grades = {
"Asim": 92,
"Sarah": 88,
"Marcus": 95,
"Emma": 87
}
for student, grade in grades.items():
print(f"{student}: {grade}")
Lists vs. Dictionaries: Quick Comparison
π Lists
- Ordered collection
- Access by position (0, 1, 2...)
- Great for sequences
- Example: [1, 2, 3]
ποΈ Dictionaries
- Key-value pairs
- Access by key name
- Great for labeled data
- Example: {"name": "Asim"}
π§ The AI Superhero Problem-Solving Framework
Here's the secret that professional programmers use: don't jump straight to coding. Have a plan first! Use this proven 3-stage framework:
The Three Stages
π― STAGE 1: RESEARCH, DEFINE & REFINE
- Research: Read the problem carefully. What is it asking?
- Define: Break it into smaller, manageable parts
- Refine: Figure out what you already know that helps
π STAGE 2: WRITE THE ALGORITHM (Pseudo Code)
- Write your solution in plain English/simple words
- Don't worry about Python syntax yet
- Focus on the logic and steps
- This is your "blueprint" for the code
π» STAGE 3: CODE IT IN PYTHON
- Translate your algorithm into Python
- Test with examples
- Fix any problems (debugging)
- Celebrate! π
π‘ Why This Framework Works
When you plan before coding, you solve the hard part (thinking) before dealing with Python syntax. It's like building a blueprint before constructing a house. You're 10x less likely to get stuck!
π Homework: Code Like a Superhero!
Now it's your turn! Use the framework above to solve these problems. Remember: Plan first, code second.
Problem Description: Create a program that asks for superhero information and displays a formatted profile.
π Stage 1: Research, Define & Refine
What does the problem ask? Get information from user, store it, display it nicely.
Break it down:
- Input: Ask for superhero name, power, and strength level (1-10)
- Storage: Keep this info in variables (or a dictionary)
- Output: Display a nicely formatted profile
What tools do I need? input(), print(), variables, strings
π Stage 2: Write the Algorithm (Pseudo Code)
ALGORITHM SuperheroProfile
Display "Welcome to SuperheroMaker!"
Ask user for "What's your superhero name?"
Store in variable: name
Ask user for "What's your superpower?"
Store in variable: power
Ask user for "Strength level (1-10)?"
Store in variable: strength
Create a nicely formatted display:
Print "=== SUPERHERO PROFILE ==="
Print "Name: [name]"
Print "Power: [power]"
Print "Strength: [strength]/10"
Print "Status: HERO ACTIVATED! π¦Έ"
END
π» Stage 3: Python Code
print("Welcome to SuperheroMaker!")
name = input("What's your superhero name? ")
power = input("What's your superpower? ")
strength = int(input("Strength level (1-10)? "))
print("\n=== SUPERHERO PROFILE ===")
print(f"Name: {name}")
print(f"Power: {power}")
print(f"Strength: {strength}/10")
print("Status: HERO ACTIVATED! π¦Έ")
Expected Output:
Problem Description: Create a program that evaluates test scores and gives feedback.
π Stage 1: Research, Define & Refine
What does the problem ask? Get a score, determine a grade, show feedback.
- Input: Ask for test score (number)
- Decision: Check score against thresholds
- Output: Show grade and encouraging message
Scoring rules: A: 90+, B: 80-89, C: 70-79, D: 60-69, F: Below 60
π Stage 2: Algorithm
ALGORITHM ScoreChecker
Ask user for test score
IF score >= 90 THEN
Print "A - Excellent! You're a coding star!"
ELSE IF score >= 80 THEN
Print "B - Great job! Very good work!"
ELSE IF score >= 70 THEN
Print "C - Good effort! Keep practicing!"
ELSE IF score >= 60 THEN
Print "D - You're getting there! Don't give up!"
ELSE
Print "F - Keep trying! You'll improve!"
END IF
END
π» Stage 3: Python Code
score = int(input("Enter your test score: "))
if score >= 90:
print("A - Excellent! You're a coding star! β")
elif score >= 80:
print("B - Great job! Very good work! π")
elif score >= 70:
print("C - Good effort! Keep practicing! πͺ")
elif score >= 60:
print("D - You're getting there! Don't give up! π")
else:
print("F - Keep trying! You'll improve! π")
Test it with scores: 95, 85, 75, 65, 55
Problem Description: Create a list of favorite items and display them numbered with a total count.
π Stage 1: Research, Define & Refine
- Create a list of favorite foods/games/movies
- Loop through the list to display each item numbered
- Show the total count at the end
Tools needed: Lists, for loops, len(), print()
π Stage 2: Algorithm
ALGORITHM FavoriteThingsList
CREATE a list with favorite foods:
["Pizza", "Ice Cream", "Burgers", "Tacos", "Sushi"]
Print "My Favorite Foods:"
FOR each food in the list:
Print the position number and the food name
END FOR
Calculate total = length of the list
Print "Total favorites: [total]"
END
π» Stage 3: Python Code
foods = ["Pizza", "Ice Cream", "Burgers", "Tacos", "Sushi"]
print("My Favorite Foods:")
for i, food in enumerate(foods):
print(f"{i + 1}. {food}")
total = len(foods)
print(f"Total favorites: {total}")
Expected Output:
Problem Description: Build a simple grade management system using dictionaries.
π Stage 1: Research, Define & Refine
- Create a dictionary with student names and grades
- Check if each student passed (grade >= 70)
- Display all students with pass/fail status
Tools needed: Dictionaries, for loops, if-else, .items()
π Stage 2: Algorithm
ALGORITHM GradeBook
CREATE dictionary with students and grades:
{"Asim": 92, "Sarah": 88, "Marcus": 75, "Emma": 65}
Print "=== GRADE BOOK ==="
FOR each student and grade in the dictionary:
IF grade >= 70 THEN
Print student name, grade, "PASSED β"
ELSE
Print student name, grade, "NEEDS IMPROVEMENT"
END IF
END FOR
END
π» Stage 3: Python Code
grades = {
"Asim": 92,
"Sarah": 88,
"Marcus": 75,
"Emma": 65
}
print("=== GRADE BOOK ===")
for student, grade in grades.items():
if grade >= 70:
print(f"{student}: {grade} - PASSED β")
else:
print(f"{student}: {grade} - NEEDS IMPROVEMENT")
# Bonus: Find the highest grade
highest_grade = max(grades.values())
highest_student = [name for name, grade in grades.items() if grade == highest_grade][0]
print(f"\nTop student: {highest_student} ({highest_grade})")
Problem Description: Combine EVERYTHING you've learned to build a complete student management system.
π Stage 1: Research, Define & Refine
Requirements:
- Create a student profile (name, age, list of test scores stored as a list)
- Calculate the average score from the list
- Determine pass/fail (average >= 75 = pass)
- Display a complete report
Use: variables, lists, loops, if-else, dictionaries, input(), print()
π Stage 2: Algorithm
ALGORITHM StudentManagement
Ask user for student name
Ask user for age
Ask user for test scores (comma-separated)
CREATE dictionary with:
"name": student name
"age": age
"scores": list of scores converted to numbers
CALCULATE:
average = sum of all scores / number of scores
status = "PASSED" if average >= 75 else "NEEDS IMPROVEMENT"
DISPLAY:
Print student name, age, list of scores, average, status
END
π» Stage 3: Python Code
name = input("Student name: ")
age = input("Age: ")
scores_str = input("Enter test scores (comma-separated): ")
# Convert scores from string to list of numbers
scores = [int(score.strip()) for score in scores_str.split(",")]
# Create student dictionary
student = {
"name": name,
"age": age,
"scores": scores
}
# Calculate average
average = sum(scores) / len(scores)
# Determine status
status = "PASSED β" if average >= 75 else "NEEDS IMPROVEMENT"
# Display report
print("\n=== STUDENT REPORT ===")
print(f"Name: {student['name']}")
print(f"Age: {student['age']}")
print(f"Scores: {student['scores']}")
print(f"Average: {average:.1f}")
print(f"Status: {status}")
π You Did It!
Completing these problems means you've mastered Python fundamentals! You can:
- β Work with all major data types
- β Take input from users and display output
- β Make smart decisions with if-else
- β Repeat actions with loops
- β Organize data with lists and dictionaries
- β Use a professional problem-solving framework
You're officially a Python Superhero! π¦ΈββοΈπ¦ΈββοΈ
π Ready for Session 6?
You've mastered the fundamentals! Next session, we'll build more complex programs and explore file handling, functions, and advanced AI concepts.
π Key Takeaways
- Variables: Labeled boxes that store information
- Data Types: int, float, str, bool, list, dict
- Input/Output: input() to ask questions, print() to show results
- If-Else: Make decisions based on conditions
- Loops: Repeat code multiple times efficiently
- Lists: Ordered collections accessed by position
- Dictionaries: Key-value pairs for labeled data
- Problem-Solving: Research β Algorithm β Code