šŸ

Variables and Data Types

Beginner
70 XP
30 min
Lesson Content

Variables: Storing Data

Variables are like labeled boxes that store information. In Python, you create variables by simply assigning values - no special declaration needed!

Creating Variables

Python is dynamically typed, meaning you don't need to declare variable types:

# String (text)
name = "Alice"
message = 'Hello, World!'

# Numbers
age = 25
price = 19.99

# Boolean (True/False)
is_student = True
is_active = False

Python Data Types

1. Strings (str)

Text data enclosed in quotes:

first_name = "John"
last_name = 'Doe'
full_name = first_name + " " + last_name
print(full_name) # John Doe

2. Integers (int)

Whole numbers (positive, negative, or zero):

score = 100
temperature = -5
count = 0

3. Floats (float)

Decimal numbers:

pi = 3.14159
price = 19.99
weight = 68.5

4. Booleans (bool)

True or False values (must be capitalized!):

is_student = True
is_complete = False
has_permission = True

Checking Data Types

Use type() to check a variable's type:

name = "Python"
print(type(name)) # <class 'str'>

age = 25
print(type(age)) # <class 'int'>

price = 19.99
print(type(price)) # <class 'float'>

Variable Naming Rules

  • āœ… Start with letter or underscore: name, _private
  • āœ… Can contain letters, numbers, underscores: user_name, score2
  • āœ… Case sensitive: Name ≠ name
  • āŒ Can't start with number: 2name (invalid)
  • āŒ Can't use Python keywords: if, for, class

Best Practices

  • Use descriptive names: user_age not ua
  • Use snake_case: user_name not userName
  • Make names meaningful: total_score not ts
Example Code

Create variables of different types and print them.

# Create variables for a student profile
# 1. Create a string variable 'name' with your name
name = "Your Name"

# 2. Create an integer variable 'age' with your age
age = 20

# 3. Create a float variable 'gpa' with a grade point average
gpa = 3.5

# 4. Create a boolean variable 'is_enrolled' set to True
is_enrolled = True

# 5. Print all variables
print(name)
print(age)
print(gpa)
print(is_enrolled)

Expected Output:

Your Name
20
3.5
True
Study Tips
  • •Read the theory content thoroughly before practicing
  • •Review the example code to understand key concepts
  • •Proceed to the Practice tab when you're ready to code