Skip to main content

Variables

A variable is a named container that holds a data value.


Creating Variables

You don't declare a variable in Python with any special command. It comes into being the first time you give it a value. You don't state a type for it either, and the same variable can later hold a value of a different type.

Example

Prompt
Create a variable x with value 5 and a variable y with value "John", then print both.
Output: complete Python program

Change type

No type is declared here, and x switches from a number to a string:

Prompt
Create a variable x with value 4 (int), then change it to "Sally" (str), and print x.
Output: complete Python program

Casting

Casting lets you choose a variable's data type yourself.

Example

Prompt
Create three variables using casting: x as str(3), y as int(3), z as float(3), then print all three.
Output: complete Python program

Get the Type

The type() function tells you what data type a variable holds.

Example

Prompt
Create a variable x with value 5 and y with value "John", then print the type of each using the type() function.
Output: complete Python program

Single or Double Quotes?

Both single and double quotes work for creating a string variable:

Example

Prompt
Show that string variables can be declared with either double or single quotes by assigning "John" both ways.
Output: complete Python program

Case-Sensitive

Case matters in variable names, so a and A are not the same.

Example

Here you get two separate variables:

Prompt
Demonstrate that variable names are case-sensitive by creating a = 4 and A = "Sally", then print both to show they are different variables.
Output: complete Python program