Topic 2: Variables and Data Types

1. Introduction

In Python, as in many programming languages, a variable is used to store data that can be used and manipulated throughout a program. The data stored can be of various types, and Python has several built-in data types.

2. What are Variables?

  • Definition: A variable in Python acts as a container for storing data values.

  • Declaration and Assignment: Python is dynamically typed, meaning you don’t need to declare the type of a variable when you create one.

    x = 5 # x is of type int y = "Hello" # y is of type str

3. Basic Data Types

  • Integers (int): Whole numbers, positive or negative.

    my_integer = 10
  • Floats (float): Real numbers with a decimal point.

    my_float = 20.5
  • Strings (str): Sequences of characters, defined by enclosing the characters in quotes (" " or ' ').

    my_string = "Python Rocks!"
  • Booleans (bool): Data type with two values, True or False.

    is_active = True

4. Advanced Data Types (Collections)

  • Lists: Ordered and changeable collection of items. Lists are written with square brackets.

    my_list = [1, 2, 3, "Python", "Java"]
  • Tuples: Ordered and unchangeable collection. Tuples are written with round brackets.

    my_tuple = (10, "Hello", 20.5)
  • Sets: Unordered collection with no duplicate items. Sets are written with curly brackets.

    my_set = {1, 2, 3, 4, 5}
  • Dictionaries: Unordered, changeable, and indexed collection. Dictionaries have keys and values and are written with curly brackets.

    my_dict = {"name": "John", "age": 30, "city": "New York"}

5. Type Function

  • The built-in type() function can be used to find out the type of a variable.

    x = 5 print(type(x)) # Output: <class 'int'>

6. Type Conversion

  • You can use Python to explicitly convert one type to another using various built-in functions.

    x = "123" y = int(x) # Converts string "123" to integer 123

    Other functions include float(), str(), list(), tuple(), set(), and dict().

7. Variable Naming Rules

  • Must start with a letter or an underscore.
  • Cannot start with a number.
  • Can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
  • Variable names are case-sensitive (name, Name, and NAME are three different variables).

8. Conclusion

Understanding variables and data types is fundamental in Python programming. It provides the base upon which more complex operations and logic are built. By mastering these concepts, you’re taking significant steps toward becoming proficient in Python.

With this knowledge, developers can effectively store, manage, and manipulate data in Python, creating a foundation for more advanced operations and procedures. The versatility of Python’s data types facilitates handling a wide range of data processing tasks.