Chapter 1: The Basics / Lesson 2

Variables and Basic Data Types

8 min ยท The Basics

What are Variables?

Variables are containers for storing data values in your program. Think of them as labeled boxes where you can put different types of information. Variables allow you to store data, reuse it, and manipulate it throughout your program.

In Python, creating a variable is simple - you just assign a value to a name using the = operator. Python automatically determines the type based on the value you assign.

variables.py
name = "Alice" age = 25 height = 5.6 is_student = True # Variables can be reassigned age = 26 # age is now 26 # Variables can be used in expressions next_age = age + 1 # next_age is 27

Basic Data Types

Python has several built-in data types. Understanding these types is fundamental to programming in Python:

  • str (String) โ€” Text data enclosed in quotes: "Hello", 'Python', """Multi-line"""
  • int (Integer) โ€” Whole numbers: 42, -7, 1000, 0
  • float (Floating Point) โ€” Decimal numbers: 3.14, -0.5, 2.0
  • bool (Boolean) โ€” Logical values: True or False (must be capitalized)
  • None โ€” Represents the absence of a value (similar to null in other languages)

Working with Strings

Strings can be created with single, double, or triple quotes. Triple quotes allow multi-line strings:

strings.py
single_quote = 'Hello' double_quote = "Hello" triple_quote = """This is a multi-line string""" # All are equivalent for single-line strings print(single_quote == double_quote) # True # Escape sequences in strings message = "He said \"Hello\"" # Use backslash to include quotes path = "C:\\Users\\Name" # Escape backslashes

Working with Numbers

Python supports both integers and floating-point numbers. Here are some important points:

numbers.py
# Integers positive = 42 negative = -7 zero = 0 large = 1000000 # Floats (decimal numbers) pi = 3.14159 negative_float = -0.5 scientific = 1.5e3 # 1500.0 (scientific notation) # Note: Division always returns float result = 10 / 2 # 5.0 (float, not int) integer_div = 10 // 2 # 5 (integer division)

Working with Booleans

Boolean values represent truth. They're essential for control flow and logic:

booleans.py
is_active = True is_complete = False # Booleans are used in comparisons age = 18 can_vote = age >= 18 # True print(True and False) # False print(True or False) # True print(not True) # False

Checking Types

Use the type() function to check what type a variable is. This is useful for debugging and understanding your data:

types.py
x = 42 print(type(x)) # <class 'int'> y = "Hello" print(type(y)) # <class 'str'> z = 3.14 print(type(z)) # <class 'float'> # Check if a variable is a specific type print(isinstance(x, int)) # True print(isinstance(y, str)) # True

Variable Assignment and Reassignment

Variables in Python can be reassigned to new values at any time. The variable doesn't have a fixed type - it can hold different types of values:

reassignment.py
# Create a variable value = 10 print(value) # 10 # Reassign to a different type value = "Hello" print(value) # Hello # Reassign again value = 3.14 print(value) # 3.14 # Multiple assignment x, y, z = 1, 2, 3 a = b = c = 10 # All three are 10

Variable Naming Rules

Python has specific rules for variable names. Following these rules ensures your code works correctly:

๐Ÿ“ Naming Rules

โ€ข Must start with a letter (a-z, A-Z) or underscore (_)

โ€ข Can contain letters, numbers, and underscores

โ€ข Cannot start with a number

โ€ข Case-sensitive: name and Name are different

โ€ข Cannot use Python keywords (if, for, def, etc.)

โ€ข Use snake_case (lowercase with underscores) by convention

naming_examples.py
# Valid variable names my_variable = 10 user_name = "Alice" _age = 25 name2 = "Bob" # Invalid variable names (will cause errors) # 2name = "Invalid" # Can't start with number # my-variable = 10 # Can't use hyphens # if = 10 # Can't use keywords # my variable = 10 # Can't use spaces

Best Practices for Variable Names

โœ… Good Variable Names

Use descriptive names that explain what the variable stores: user_age, total_price, is_logged_in

โŒ Avoid These

Don't use single letters (except in loops) or abbreviations: x, temp, usr - these make code hard to understand!

Using Variables in Expressions

Variables can be used in calculations and expressions. The variable's current value is used:

expressions.py
x = 10 y = 5 # Use variables in calculations sum = x + y # 15 difference = x - y # 5 product = x * y # 50 quotient = x / y # 2.0 print(f"Sum: {sum}") print(f"{x} + {y} = {sum}")
๐ŸŽ‰

Lesson Complete!

Great work! Continue to the next lesson.

main.py
๐Ÿ“ค Output
Click "Run" to execute...