Variables In Python


In Python, variables are used to store values or data that can be used throughout your program. A variable holds a reference to a value and is assigned using the assignment operator (=).

Key Concepts About Variables in Python:

  • Variable Assignment
    You don't need to declare the variable type explicitly in Python. The interpreter will automatically assign the type based on the value you assign to the variable.

    x = 10          # Integer

  • name = "John"   # String

  • height = 5.9    # Float

  • is_active = True  # Boolean


  1. Variable Naming Rules

    • The name must start with a letter (A-Z or a-z) or an underscore (_).

    • The rest of the name can contain letters, numbers, or underscores.

    • Variable names are case-sensitive (myVar and myvar are different variables).

    • Cannot use Python keywords as variable names (e.g., False, if, class, etc.).

  • Valid Examples:

    my_age = 25

  • _value = 100

  • user_name = "Alice"

  • tempVar = 3.14

  •  Invalid Examples:

    1st_value = 10  # Starts with a number (invalid)

  • if = 5          # "if" is a Python keyword (invalid)


  • Dynamic Typing
    Python is dynamically typed, which means you don't need to declare the type of the variable when creating it. The type is inferred from the value assigned to the variable.

    a = 10       # integer

  • a = "Hello"  # now a string (dynamic typing)


  • Multiple Assignment
    You can assign values to multiple variables in a single line:

    x, y, z = 1, 2, 3

  1.  This assigns 1 to x, 2 to y, and 3 to z.

  • Reassigning Variables
    Variables in Python can be reassigned to new values or data types.

    a = 10      # a is an integer

  • a = "Hello" # a is now a string


Examples:

Basic Variable Example:

  • name = "Alice"  # String variable

  • age = 25        # Integer variable

  • height = 5.6    # Float variable

  • is_student = True  # Boolean variable


  • print(name, age, height, is_student)


Multiple Variables Assignment:

  • x, y, z = 10, 20, 30

  • print(x, y, z)


Reassigning Variables:

  • x = 5

  • print(x)   # Prints 5

  • x = "Hello"

  • print(x)   # Prints "Hello"


Swapping Values Using Variables:

  • a = 10

  • b = 20


  • # Swap values of a and b

  • a, b = b, a

  • print(a, b)  # Prints 20 10


Common Pitfalls to Avoid:

  • Avoid using Python keywords as variable names.

  • Remember that variables are case-sensitive, so myVar and myvar are different.

Let me know if you'd like more examples or further explanation on how variables work! 😊


Post a Comment

0 Comments