Python Variables

Python Variables Tutorial

1. What is a Variable?

A variable is a container for storing data in Python. Unlike other programming languages, Python does not require explicit declaration of variable types. The type is determined automatically based on the assigned value.

x = 10      # Integer
y = 3.14    # Float
name = "Alice"  # String
is_valid = True  # Boolean

Python is dynamically typed, meaning you don't need to specify the type explicitly.


2. Variable Naming Rules

  • Must start with a letter (a-z, A-Z) or an underscore (_).
  • Cannot start with a number.
  • Can contain letters, numbers, and underscores (_).
  • Case-sensitive (name and Name are different).
  • Cannot use Python keywords (e.g., if, while, class).

Valid Variable Names:

my_var = 10
_name = "Python"
age123 = 25

Invalid Variable Names:

123name = "John"  # Cannot start with a number
my-var = 20       # Hyphens are not allowed
if = 30           # "if" is a reserved keyword

3. Assigning Values to Variables

(a) Single Assignment

x = 10
y = "Hello"

(b) Multiple Assignment

a, b, c = 5, 10, 15
print(a, b, c)  # Output: 5 10 15

(c) Assigning the Same Value to Multiple Variables

x = y = z = 100
print(x, y, z)  # Output: 100 100 100

4. Variable Types (Dynamic Typing)

Python allows changing the data type of a variable at runtime.

x = 10   # Integer
x = "Hello"  # Now x is a String
print(x)  # Output: Hello

Python automatically updates the variable type.


5. Type Checking (type())

You can check the type of a variable using type().

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

y = 3.14
print(type(y))  # Output: <class 'float'>

z = "Python"
print(type(z))  # Output: <class 'str'>

6. Type Casting (Type Conversion)

You can convert data types explicitly.

(a) Convert to Integer (int())

x = "100"
y = int(x)  # Converts string to integer
print(y, type(y))  # Output: 100 <class 'int'>

(b) Convert to Float (float())

x = "3.14"
y = float(x)  # Converts string to float
print(y, type(y))  # Output: 3.14 <class 'float'>

(c) Convert to String (str())

x = 42
y = str(x)  # Converts integer to string
print(y, type(y))  # Output: "42" <class 'str'>

(d) Convert to Boolean (bool())

print(bool(0))    # Output: False
print(bool(1))    # Output: True
print(bool(""))   # Output: False (empty string)
print(bool("Hi")) # Output: True (non-empty string)

Useful when handling user inputs, files, or API responses.


7. Global and Local Variables

(a) Local Variables (Defined inside a function, accessible only within the function)

def my_function():
    x = 10  # Local variable
    print(x)  # Output: 10

my_function()
print(x)  # Error: x is not defined outside the function

(b) Global Variables (Defined outside functions, accessible anywhere)

x = 50  # Global variable

def my_function():
    print(x)  # Output: 50 (Accessible inside function)

my_function()
print(x)  # Output: 50

(c) Modifying Global Variables inside a Function

Use the global keyword.

x = 5

def change_x():
    global x
    x = 10

change_x()
print(x)  # Output: 10

Use global carefully, as modifying global variables can lead to unexpected issues.


8. Constants in Python

Python does not have built-in support for constants. However, by convention, variables written in UPPERCASE are treated as constants.

PI = 3.14159
GRAVITY = 9.8

Constants should not be modified, but Python does not enforce this rule.


9. Deleting Variables (del statement)

You can delete a variable using del.

x = 10
del x
print(x)  # Error: x is not defined

10. Printing Variables (print())

(a) Printing Variables Directly

x = "Python"
print(x)  # Output: Python

(b) Concatenating Strings and Variables

name = "Alice"
age = 25

print("My name is " + name + " and I am " + str(age) + " years old.")
# Output: My name is Alice and I am 25 years old.

Use str() when concatenating non-string variables with strings.

(c) Using f-strings (Python 3.6+)

name = "Bob"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Bob and I am 30 years old.

Conclusion

  • Variables store data and are dynamically typed in Python.
  • Naming rules must be followed (e.g., cannot start with a number).
  • Use type() to check a variable’s data type.
  • Use global to modify global variables inside functions.
  • Constants are written in uppercase by convention.

🚀 Mastering Python variables is essential for writing efficient programs!

Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment