Chapter 2

Variables & Data Types

Learn how to store and work with different types of data in Python - the foundation of all programming!

πŸ“¦ What are Variables?

πŸŽ’ Real-Life Analogy: Variables are Like Labeled Storage Containers

Imagine you're organizing your room:

  • Box labeled "TOYS": Contains your toys - you can put toys in, take them out, replace them
  • Jar labeled "COOKIES": Contains cookies - you know exactly what's inside by reading the label
  • Folder labeled "HOMEWORK": Contains your homework sheets

Variables work exactly the same way! Each variable is a labeled container that stores data:

  • age = 15 - Container labeled "age" stores the number 15
  • name = "Krishna" - Container labeled "name" stores the text "Krishna"
  • score = 95 - Container labeled "score" stores the number 95

Key point: The label stays the same, but you can change what's inside anytime!

πŸ“š Another Way to Think About It: Variables are Like Nicknames

Imagine your friend "Robert" prefers to be called "Bob". "Bob" is like a variable name that points to the person Robert.

In Python: bob = "Robert"

Every time you say "Bob", everyone knows you mean Robert. Every time Python sees bob, it knows to use the value "Robert"!

The Simplest Variable Example:

Creating Your First Variable

Output will appear here...

πŸ” What Just Happened Behind the Scenes?

  1. Variable Creation: When you write name = "Krishna", Python creates a space in memory
  2. Storage: The text "Krishna" is stored in that memory location
  3. Labeling: Python creates a label called "name" that points to this memory location
  4. Reuse: Every time you use name, Python looks up what's stored there

Memory Perspective:

Memory:  [Address 1000] β†’ "Krishna"
Label:   name β†’ points to Address 1000

When you print(name):
1. Python sees "name"
2. Looks up what "name" points to
3. Finds "Krishna" at Address 1000
4. Prints "Krishna"

Why Use Variables?

πŸ’Ύ Store Information

Keep data you need to use multiple times without typing it again and again.

πŸ”„ Change Values

Update stored information easily without rewriting your entire program.

πŸ“– Readable Code

Using meaningful names makes your code easy to understand.

🎯 Organize Data

Group related information with descriptive variable names.

Variables Can Change!

That's why they're called "variables" - they can vary!

Output will appear here...

πŸ“ Variable Naming Rules

Python is picky about variable names! You can't just use any name you want. Here are the rules:

βœ… What's Allowed:

  • Letters: a-z, A-Z (both lowercase and uppercase)
  • Numbers: 0-9 (but NOT as the first character)
  • Underscore: _ (the underscore character)
  • Case-sensitive: name, Name, and NAME are all different!

❌ What's NOT Allowed:

Wrong Why It's Wrong Correct Alternative
2cool Starts with a number cool2 or too_cool
my-name Contains a hyphen (dash) my_name
my name Contains a space my_name
for Reserved keyword in Python for_loop or my_for
@username Contains special character @ username or user_name

Best Practices for Naming:

Python Convention: snake_case

Python programmers use snake_case - all lowercase letters with underscores between words.

# βœ… GOOD - Clear and follows convention
student_name = "Rama"
total_score = 95
is_passing = True
number_of_attempts = 3

# ❌ BAD - Still works, but not recommended
StudentName = "Rama"      # This is camelCase (used in other languages)
TOTAL_SCORE = 95          # ALL CAPS is for constants
n = 3                     # Too short, unclear meaning
x = "Rama"                # Not descriptive

Pro Tip: Use descriptive names! Someone reading your code (including future you!) should understand what the variable stores just by reading its name.

Practice: Which Names Are Valid?

Output will appear here...

🎨 Data Types in Python

Just like in real life, we have different types of information - numbers, words, yes/no answers. Python has different data types to handle each kind!

πŸ—‚οΈ Real-Life Analogy: Data Types are Like Different Containers

Think about organizing things in your kitchen:

  • Number jar (Integer): Stores whole items - 5 apples, 10 cookies (you can't have 2.5 cookies!)
  • Measuring cup (Float): Stores precise measurements - 2.5 cups of flour, 1.75 liters of milk
  • Label maker (String): Stores text - recipe names, ingredient labels, notes
  • Light switch (Boolean): Only two states - ON or OFF, just like True or False

Why it matters: Just like you wouldn't measure flour with a light switch, Python uses the right data type for each kind of information!

1

Integer (int) - Whole Numbers

Numbers without decimal points: 5, -3, 1000, 0

age = 25

Like counting: 1 apple, 2 apples, 3 apples...

2

Float - Decimal Numbers

Numbers with decimal points: 3.14, -0.5, 2.0

price = 19.99

Like measuring: 2.5 cups, $19.99, 5.9 feet

3

String (str) - Text

Text wrapped in quotes (single or double): "Hello", 'Python'

name = "Krishna"

Like writing: names, messages, labels

4

Boolean (bool) - True/False

Only two values: True or False (note the capital letters!)

is_student = True

Like yes/no questions: Is it raining? Is the door open?

🎯 Quick Memory Trick

int = integer (whole numbers, think "intact" - nothing broken/decimal)

float = floating point (decimal "floats" left/right: 3.14, 19.99)

str = string (like a string of letters tied together)

bool = Boolean (named after mathematician George Boole - invented True/False logic)

Let's Explore Each Type:

1️⃣ Integers - Whole Numbers

Integers are whole numbers - no decimal point, no fractions.

Output will appear here...

When to use integers:

  • Counting things (number of students, items in cart)
  • Ages, years, IDs
  • Whole quantities (5 apples, 10 books)

2️⃣ Floats - Decimal Numbers

Floats can have decimal points. Perfect for precise measurements!

Output will appear here...

When to use floats:

  • Money and prices
  • Measurements (height, weight, distance)
  • Scientific calculations
  • Percentages (like 98.6 for temperature)

3️⃣ Strings - Text Data

Strings are text - anything wrapped in quotes!

Output will appear here...

⚠️ Important: String vs Number

"123" (with quotes) is a string - it's text that looks like a number

123 (no quotes) is an actual number - you can do math with it

# String version - treated as text
age_text = "25"
# Can't do: age_text + 1  <- This would cause an error!

# Number version - can do math
age_number = 25
next_year = age_number + 1  # This works! Result: 26

4️⃣ Booleans - True or False

Booleans only have two possible values: True or False

Output will appear here...

When to use booleans:

  • Yes/No questions (Is it raining? True or False)
  • On/Off states (Is the light on? True or False)
  • Checking conditions (Is age greater than 18?)
  • Game states (Is game over? Has player won?)

⚠️ Common Mistake: Boolean values must start with a capital letter!

is_correct = True   # βœ… Correct
is_correct = true   # ❌ Error! (lowercase doesn't work)
is_correct = FALSE  # ❌ Error! (all caps doesn't work)

πŸ” The type() Function - Finding Data Types

Sometimes you need to know what type of data a variable contains. Python has a built-in function called type() that tells you!

Using type() to Discover Data Types

Output will appear here...

Understanding the Output:

  • <class 'str'> means it's a string (text)
  • <class 'int'> means it's an integer (whole number)
  • <class 'float'> means it's a float (decimal number)
  • <class 'bool'> means it's a boolean (True/False)

Don't worry about the word "class" for now - just focus on the type name inside the quotes!

Why Does This Matter?

Different types behave differently! Watch what happens:

Output will appear here...

πŸ”„ Type Conversion - Changing Data Types

Sometimes you need to convert data from one type to another. Python makes this easy with conversion functions!

Main Conversion Functions:

  • int() - Convert to integer
  • float() - Convert to float
  • str() - Convert to string
  • bool() - Convert to boolean

1️⃣ Converting to Integer - int()

Output will appear here...

⚠️ Warning: You can't convert just anything to int!

# These work:
int("123")      # βœ… Result: 123
int(45.8)       # βœ… Result: 45 (decimal removed)
int(True)       # βœ… Result: 1
int(False)      # βœ… Result: 0

# These DON'T work:
int("hello")    # ❌ Error! Can't convert text to number
int("12.5")     # ❌ Error! String has decimal point

2️⃣ Converting to Float - float()

Output will appear here...

3️⃣ Converting to String - str()

This one almost always works! You can convert any type to a string.

Output will appear here...

Real-World Example: Calculator Input

When you get user input (which we'll learn next!), it's always a string. You need to convert it to do math:

Output will appear here...

πŸ’¬ Getting User Input

So far, we've been hardcoding values. But what if we want the user to provide information? That's where input() comes in!

The input() function:

  • Pauses the program and waits for the user to type something
  • User presses Enter to submit their input
  • Returns whatever the user typed as a string

Basic input() Example:

Note: The input() function works differently in this web environment. In a real Python program on your computer, it would wait for you to type. Here's how it normally works:

# In a real Python environment:
name = input("What is your name? ")
print("Hello,", name)

# What happens:
# 1. Python displays: "What is your name? "
# 2. Cursor waits for you to type
# 3. You type: Krishna
# 4. You press Enter
# 5. Python stores "Krishna" in the name variable
# 6. Prints: "Hello, Krishna"

πŸ”‘ Important: input() ALWAYS returns a string!

age = input("How old are you? ")
# Even if you type 25, age will be "25" (a string), not 25 (a number)

# To use it as a number, convert it:
age = int(input("How old are you? "))
# Now age is 25 (a number) and you can do math with it!

Simulating User Input

Since we're in a web browser, let's simulate what input() would do:

Output will appear here...

Complete input() Example Pattern:

# Pattern for getting text input:
name = input("Enter your name: ")
print("Welcome,", name)

# Pattern for getting number input:
age = int(input("Enter your age: "))
print("You are", age, "years old")

# Pattern for getting decimal number:
height = float(input("Enter your height in feet: "))
print("Your height is", height, "feet")

# Pattern for calculations:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
sum = num1 + num2
print("Sum:", sum)

Pro Tip: Always include a descriptive message in input() so users know what to type!

πŸ“Ί Video Resources

Watch these videos to reinforce your understanding of variables and data types:

Python Variables for Beginners

Programming with Mosh

Clear explanation of variables, naming conventions, and why they're important in Python programming.

Watch Video

Python Data Types Explained

freeCodeCamp

Comprehensive tutorial covering integers, floats, strings, and booleans with practical examples.

Watch Video

Type Conversion in Python

Corey Schafer

Learn how and why to convert between different data types with real-world examples.

Watch Video

πŸ€– AI Learning Prompts

Use these prompts with AI assistants to deepen your understanding. Hover over each prompt to see quick action buttons:

Understanding Variables

I'm learning about variables in Python. Please help me understand:

1. What exactly is a variable and why do we need them?
2. Explain how variables are stored in computer memory (use simple analogies)
3. What happens when I assign a value to a variable? What's going on behind the scenes?
4. Show me 5 examples of good variable names and 5 examples of bad variable names, explaining why
5. Give me a simple exercise to practice creating and using variables

Please explain like I'm a complete beginner who's never programmed before!

Mastering Data Types

Help me master Python data types:

1. Explain the difference between int, float, string, and boolean in simple terms
2. When should I use each data type? Give me real-world scenarios
3. What happens if I try to add a string and a number? Why does this cause an error?
4. Show me examples of type conversion and explain why it's necessary
5. What's the difference between "123" (string) and 123 (integer)? Show me with examples
6. Create 3 practice exercises where I need to choose the right data type

Use analogies and simple language that a 12-year-old could understand!

Type Conversion Practice

I need help with type conversion in Python:

1. Explain what int(), float(), str(), and bool() do
2. Give me examples of when each conversion would fail and why
3. Show me a real-world program that needs type conversion (like a calculator)
4. What happens when I convert a float to an int? Where does the decimal go?
5. Create a mini-project idea where I need to convert between different types

Include step-by-step examples and explain any errors I might encounter!

πŸ’‘ Tips for Using These Prompts:

  • Ask follow-up questions: If something isn't clear, ask the AI to explain differently
  • Request more examples: Practice makes perfect!
  • Ask "why": Understanding the reasoning helps you remember
  • Request exercises: Ask for practice problems to test your knowledge
  • Compare with real life: Ask for analogies you can relate to

✏️ Practice Exercises

How to Approach These Exercises:

  • Read carefully: Make sure you understand what's being asked
  • Try first: Attempt the exercise before looking at hints or solutions
  • Test your code: Run it and check if it works as expected
  • Learn from mistakes: Errors are learning opportunities!
  • Experiment: Try variations to deepen your understanding

Part 1: Guided Exercises

These exercises include detailed explanations to help you understand every step.

Guided Exercise 1: Creating and Using Variables

What You'll Learn: How to create variables, store different types of data, and use them in your program.

Time: 10 minutes

Step 1: Understanding the Task

Create a program that stores information about yourself and displays it nicely.

Step 2: What Information to Store

  • Your name (string)
  • Your age (integer)
  • Your height in feet (float)
  • Whether you're a student (boolean)

Step 3: Write the Code

Output will appear here...

Step 4: Understanding What Happened

Line by line explanation:

  1. name = "Krishna" - Creates a string variable called name
  2. age = 16 - Creates an integer variable for age
  3. height = 5.8 - Creates a float variable for height (notice the decimal point!)
  4. is_student = True - Creates a boolean variable (True/False)
  5. The print statements display all the information we stored

Step 5: Now Make It Your Own!

Change the values to your actual information and add 2 more variables:

Output will appear here...

Guided Exercise 2: Working with Numbers

What You'll Learn: How to work with integers and floats, perform calculations, and understand type differences.

Time: 10 minutes

Task: Create a Simple Calculator

Store two numbers and perform basic operations on them.

Output will appear here...

Guided Exercise 3: String Concatenation

What You'll Learn: How to combine strings and format text output.

Time: 8 minutes

Task: Create a Personalized Greeting

Output will appear here...

Guided Exercise 4: Type Conversion Practice

What You'll Learn: Converting between different data types.

Time: 12 minutes

Task: Convert and Calculate

Output will appear here...

Guided Exercise 5: Working with Booleans

What You'll Learn: Understanding boolean values and how they work.

Time: 8 minutes

Task: Store and Display Boolean States

Output will appear here...

Guided Exercise 6: Variable Reassignment

What You'll Learn: Variables can change their values during program execution.

Time: 10 minutes

Task: Track Game Score

Output will appear here...

Guided Exercise 7: Multiple Data Types Together

What You'll Learn: Using different data types in one program.

Time: 12 minutes

Task: Student Report Card

Output will appear here...

Guided Exercise 8: Temperature Converter

What You'll Learn: Practical application of float variables and calculations.

Time: 10 minutes

Task: Convert Celsius to Fahrenheit

Output will appear here...

Guided Exercise 9: String Formatting with f-strings

What You'll Learn: Modern way to format strings with variables.

Time: 10 minutes

Task: Create Formatted Messages

Output will appear here...

Guided Exercise 10: Age Calculator

What You'll Learn: Combining multiple concepts - variables, calculations, and type conversion.

Time: 12 minutes

Task: Calculate Age in Different Units

Output will appear here...

Part 2: Independent Practice

Now test your skills! Try these exercises on your own.

Challenge 1: Personal Info Card

Difficulty: Easy | Time: 10 minutes

Task: Create variables to store and display:

  • First name and last name (2 separate string variables)
  • Birth year (integer)
  • Current year (integer)
  • Calculate your age from birth year and current year
  • Display everything in a nice format
Output will appear here...

Challenge 2: BMI Calculator

Difficulty: Medium | Time: 15 minutes

Task: Calculate Body Mass Index (BMI) using height and weight.

  • Store weight in kilograms (float)
  • Store height in meters (float)
  • Calculate BMI using formula: BMI = weight / (height * height)
  • Display weight, height, and BMI with proper formatting
Output will appear here...

Challenge 3: Currency Converter

Difficulty: Medium | Time: 12 minutes

Task: Convert an amount from USD to INR and EUR.

  • Store amount in USD (float)
  • Create conversion rate variables (1 USD = 83 INR, 1 USD = 0.92 EUR)
  • Calculate converted amounts
  • Display all amounts formatted to 2 decimal places
Output will appear here...

Challenge 4: Shopping Bill Calculator

Difficulty: Medium | Time: 15 minutes

Task: Create a shopping bill with multiple items.

  • Store 3 item names (strings) and their prices (floats)
  • Calculate subtotal
  • Add 18% tax (GST)
  • Calculate total amount
  • Display a formatted bill
Output will appear here...

Challenge 5: Time Converter

Difficulty: Easy | Time: 10 minutes

Task: Convert hours to minutes, seconds, and milliseconds.

  • Store a number of hours (can be float)
  • Convert to minutes (Γ— 60)
  • Convert to seconds (Γ— 3600)
  • Convert to milliseconds (Γ— 3,600,000)
  • Display all conversions
Output will appear here...

Challenge 6: Grade Calculator

Difficulty: Medium | Time: 15 minutes

Task: Calculate average grade and percentage from 5 subject marks.

  • Store 5 subject names and marks (out of 100)
  • Calculate total marks
  • Calculate average marks
  • Calculate percentage
  • Display a formatted grade sheet
Output will appear here...

πŸŽ‰ Congratulations!

You've completed Chapter 2! You now know:

  • How to create and use variables
  • The four main data types: int, float, str, bool
  • How to check types with type()
  • How to convert between types
  • How to get user input (the concept)

Next Step: Move on to Chapter 3 to learn about operators and string methods!

πŸ“ Knowledge Check - Test Your Understanding!

Answer these questions to check your understanding of Chapter 2. Get instant feedback on each answer!

Question 1 of 5

What is a variable in Python?

Question 2 of 5

Which variable name follows Python naming conventions?

Question 3 of 5

What is the data type of: age = 25

Question 4 of 5

What does int("123") do?

Question 5 of 5

What does the input() function always return?