Python Variables

Variables are containers that hold data values.

Creating Variables

There isn’t a variable declaration command in Python.

As soon as you give a variable a value, it is created.

Example

x = 5
y = “John
print(x)
print(y)

Variables can alter their type after they have been set, and they are not required to be defined with a certain type.

Example

x = 4       # x is of type int
x = Sally # x is now of type str
print(x)
Python Variables

Casting

Example

x = str(3)    # x will be ‘3’
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0

Acquire the Type

The type() method returns the data type of a variable.

x = 5
y = John
print(type(x))
print(type(y))

Single or Double Quotes?

String variables can be declared using single or double quotes:

Example

x = John
# is the same as
x = John

Case-Sensitive

Variable names are case-sensitive.

Example

This will create two variables:

a = 4
A = Sally
#A will not overwrite a
Python Quiz

Exercise

What is a correct way to declare a Python variable?