Dynamic Variable Typing in Python

Python uses dynamic typing for variables, meaning you don't need to declare variable types (such as numeric or alphanumeric) because the interpreter determines the type based on the assigned value.

Note: This is a significant difference from languages like C, where declaring a variable type before using it is mandatory. In Python, this step is unnecessary.

    Practical Examples

    Example 1

    Let's assign a numeric value to the variable "year".

    To declare the variable as numeric, simply assign it a number.

    year = 1968

    The interpreter will automatically treat the variable "year" as numeric.

    This allows you to use the variable in mathematical operations without issues.

    Note: The number is not enclosed in quotation marks. If it were, the interpreter would treat it as a string instead of a numeric value.

    Example 2

    Now, let's assign an alphanumeric value to the variable "name".

    To declare the variable as alphanumeric, assign it the string "Andrea".

    name = "Andrea"

    In this case, the data is enclosed in quotation marks. This is required for alphanumeric values.

    The interpreter will automatically recognize the variable "name" as alphanumeric.

    String Variables in Mathematical Calculations

    Alphanumeric variables cannot be used in mathematical operations.

    If you try to add year + name, the interpreter will return an error.

    >>> print(year + name)
    Traceback (most recent call last):
    File "<pyshell#2>", line 1, in <module>
    print(year + name)
    TypeError: unsupported operand type(s) for +: 'int' and 'str'

    Therefore, once you assign a numeric, alphanumeric, or boolean value to a variable, you should only use it in appropriate operations.

    Note: In this respect, Python is different from PHP, which allows string variables to be used in mathematical operations without causing errors.

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Variables in Python

    1. Variables
    2. Variable Types
    3. Strings
    4. Inline Assignment
    5. Lists
    6. Tuples
    7. Sets
    8. Dictionaries