Understanding Variables and Data Types in Python

Feb 3, 2025

Variables in Python

Definition

  • A variable is a container for a value.
  • Each variable should have a unique name.

Data Types

There are four basic data types discussed:

  1. Strings
  2. Integers
  3. Floats
  4. Booleans

1. Strings

  • A string is a series of text which can be enclosed in double or single quotes. (Preference: double quotes)
  • Example of a string variable: first_name.
  • To assign a variable: use the assignment operator (=).
  • Print a string variable using a print statement without quotes.
  • Use f-strings for formatted output:
    • Syntax: f"{variable}"
    • Example: print(f"Hello, {first_name}")

2. Integers

  • An integer is a whole number.
  • Example: A person's age (e.g., age = 25).
  • Print an integer variable without quotes:
    • Example: print(f"You are {age} years old.")
  • Integers can be used in arithmetic expressions.

3. Floats

  • A float is a floating point number that includes a decimal portion.
  • Example: Price (e.g., price = 10.99).
  • Print a float variable:
    • Example: print(f"The price is ${price}")
  • Other examples include GPA (e.g., gpa = 3.2) and distance (e.g., distance = 5.5).

4. Booleans

  • A boolean is either True or False.
  • Example: is_student = True.
  • Booleans are often used within if statements.
    • Example:
      if is_student:
          print("You are a student.")
      else:
          print("You are not a student.")
      

Examples of Booleans

  1. is_for_sale - checks if an item is for sale.
  2. is_online - checks if someone is online.

Conclusion

  • Variables are a reusable container for a value.
  • Four basic data types: Strings, Integers, Floats, and Booleans.

Assignment

  • Post four variables in the comments section:
    1. A string
    2. An integer
    3. A float
    4. A boolean
  • Aim for unique examples.