Variables: Naming Your Data

In programming, a variable is a container for storing a value. Think of it as a labeled box where you can put information. In Python, you create a variable by giving it a name and assigning it a value using the equals sign (=).

Python is dynamically typed, which means you don't have to declare the type of data a variable will hold. The interpreter figures it out automatically.

Python


# A variable 'name' storing a string of text
name = "Alice"

# A variable 'age' storing a whole number
age = 30

# You can change the value and even the type!
age = 31
age = "Thirty-one" # This is valid, but not always good practice!

Basic Data Types

Every value in Python has a data type. Here are the most common ones:

  • Integer (int): Whole numbers, like 10, -5, 0.
  • Float (float): Numbers with a decimal point, like 3.14, -0.001.
  • String (str): A sequence of characters, enclosed in single (') or double (") quotes. Example: "Hello World".
  • Boolean (bool): Represents one of two values: True or False. Booleans are the foundation of logic and decision-making.

Python


# Examples of data types
user_id = 101          # int
price = 19.99          # float
product_name = "Book"  # str
is_available = True    # bool

# You can check the type of any variable using the type() function
print(type(price))  # <class 'float'>

Control Flow: Making Decisions

Your programs often need to perform different actions based on different conditions. This is called control flow.

if, elif, else Statements

This structure lets you execute code only if a certain condition is true.

Python


temperature = 25

if temperature > 30:
    print("It's a hot day! ☀️")
elif temperature > 20: # 'elif' is short for 'else if'
    print("It's a pleasant day. 😊")
else:
    print("It's cold, bring a jacket! 🧥")
# Output: It's a pleasant day. 😊

for Loops

A for loop is used for iterating over a sequence (like a list, a tuple, or a string).

Python


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}s.")

while Loops

A while loop repeats as long as a certain condition is true. Be careful not to create an infinite loop!

Python


count = 0
while count < 3:
    print(f"Count is {count}")
    count = count + 1 # Increment the counter
# Output:
# Count is 0
# Count is 1
# Count is 2