• Python Basics

  • Python Variables

  • Operators in Python

  • Conditional Statements in Python

  • Python Lists

  • Python Tuples

  • Python Sets

  • Python Dictionaries

  • Loops in Python

  • Python Arrays and Functions

  • Conclusion

Variable in Python

What are Variables?

In Python, variables are used to store data values. Think of them as containers that hold information for you to use later in your program.

Creating Variables in Python

You don’t need a special command to declare a variable in Python. A variable is automatically created when you assign a value to it.

Example:

python
1x = 5  # x is holding the number 5
2y = "Alex"  # y is holding the string "Alex"
3print(x)
4print(y)

In the example above, x stores the value 5 (an integer), and y stores "Alex" (a string). You can create variables to hold different types of data.

Variables Can Change Type

In Python, the same variable can hold different types of values throughout your code. This means you can change the type of data a variable holds at any time.

Example:

python
1x = 10       # x is an integer
2x = "Hello"  # x is now a string
3print(x)

Here, x is first an integer (10), but later, it is changed to a string ("Hello").

Casting in Python

If you want to specifically define the data type of a variable, you can use casting.

Example:

python
1x = str(3)    # x will be '3' (string)
2y = int(3)    # y will be 3 (integer)
3z = float(3)  # z will be 3.0 (float)

In this example, we are telling Python exactly what type of value we want for each variable.

Checking the Type of a Variable in Python

You can check the type of data stored in a variable using the type() function.

Example:

python
1x = 5
2y = "Dex"
3print(type(x))  # Output will be <class 'int'>
4print(type(y))  # Output will be <class 'str'>

Python Single or Double Quotes

In Python, you can use either single quotes or double quotes to define a string. Both work the same way.

Example:

python
1x = 'Baba'
2y = "Baba"

Both x and y hold the same string value, "Baba".