Python Variables: A Comprehensive Guide with Examples

Article by: Manish Methani

Last Updated: October 7, 2021 at 10:04am IST
3 min 12 sec read

  1. What are Variables in Python? Variables are used to store data in Python. They act as containers that hold values that can be manipulated and changed as needed throughout a program.

  2. Declaring and Assigning Variables In Python, variables can be declared and assigned in a single line of code. Here's an example:

x = 5

In this example, we declare a variable named "x" and assign it the value 5.

      3. Naming Conventions

When naming variables in Python, there are a few rules to follow:

  • Variable names must start with a letter or underscore.
  • Variable names cannot start with a number.
  • Variable names can only contain letters, numbers, and underscores.
  • Variable names are case sensitive.

Here are some examples of valid and invalid variable names:

# Valid variable names
my_var = 1
_my_var = 2
myVar = 3

# Invalid variable names
1var = 4
my-var = 5
MyVar = 6

          4. Data Types

Python has several built-in data types that can be stored in variables. Here are some examples:

# Integer
x = 5

# Float
y = 3.14

# String
z = "Hello, World!"

# Boolean
a = True

        5. Type Conversion

Python allows you to convert data types from one to another. Here's an example:

x = 5
y = "10"

# Convert y to an integer and add it to x
z = x + int(y)

print(z)  # Output: 15

In this example, we convert the string "10" to an integer using the int() function and add it to the integer variable "x".

       6. Variable Scope

In Python, variables have different scopes depending on where they are declared. A variable declared inside a function is only accessible within that function, while a variable declared outside of a function is accessible throughout the entire program.

x = 5  # Global variable

def my_func():
    y = 10  # Local variable
    print(x + y)  # Access global variable inside function

In this example, we declare a global variable named "x" and a local variable named "y" inside the my_func() function. We can access the global variable inside the function using its name.

Conclusion: In this tutorial, we provided a comprehensive guide to Python variables, including how to declare and assign them, variable naming conventions, and the different data types available. We also covered type conversion and variable scope, along with practical examples to help you understand how to use variables in Python. With this knowledge, you're ready to start creating your own Python programs using variables.


Watch Video Tutorials at Codzify YouTube Channel:

Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer