Python Variables

Explore how variables in Python are used to store data values. Understand how variables are created simply by assigning a value, with no explicit declaration command required.



Python Variables

Variables are containers for storing data values.

Creating Variables

Python does not have a command for declaring a variable. A variable is created the moment you first assign a value to it.

Example

x = 7
y = "Alice"
print(x)
print(y)
Output

7
Alice

Variables do not need to be declared with any particular type, and can even change type after they have been set.

Example

x = 10       # x is of type int
x = "Bob"    # x is now of type str
print(x) 
Output

Bob

Casting

If you want to specify the data type of a variable, this can be done with casting.

Example

x = str(8)    # x will be '8'
y = int(8)    # y will be 8
z = float(8)  # z will be 8.0
>

Get the Type

You can get the data type of a variable with the type() function.

Example

x = 10
y = "Alice"
print(type(x))
print(type(y)) 
Output

<class 'int'>
<class 'str'>

You will learn more about data types and casting later in this tutorial.

Single or Double Quotes?

String variables can be declared either by using single or double quotes:

Example

x = "Alice"
# is the same as
x = 'Alice' 

Case-Sensitive

Variable names are case-sensitive.

Example

This will create two different variables:


a = 10
A = "Bob"
# A will not overwrite a