# Variables

Courses

Variables
Variables in Python can hold text and numbers. For example:

```x = 2
price = 2.5
word = 'Hello'```

The variable names are on the left and the values on the right. Once a variable is assigned, it can be used in other places of the program.

In the example above, we have three variables: x, price and word. Variables may not contain spaces or special characters.

Text variables may be defined in 3 ways:

```word = 'Hello'
word = "Hello"
word = '''Hello'''```

The type depends on what you prefer.  Once defined variables can be replaced or modified:

```x = 2

# increase x by one
x = x + 1

# replace x
x = 5```

Python supports the operators +, -, / and * as well as brackets.  Variables may be shown on the screen using the print statement.

```x = 5
print(x)

y = 3 * x
print(y)

# more detailed output
print("x = " + str(x))
print("y = " + str(y))

```

The first output of the program above is simply the raw value of the variables. If you want to print a more detailed message like “x = 5”, use the line ‘print(“x = ” + str(x))’. This str() function converts the numeric variable to text.

### 12 thoughts on “Variables”

- January 6, 2016

As stated above the 3 ways to define text variables, may I know the differences among them? As in Java single quotes used for single character where in double quotes is used for strings

- January 6, 2016

All methods can be used to define characters or strings. In Java there is an explicit difference between single and double quotes, but in Python any form can be used for both strings and single characers. In Python it’s simply a matter of preference.

- April 6, 2016

So, there’s no need to instantiate integers or other variables?

- April 12, 2016

Exactly, this is optional.

- June 9, 2016

what is the use of str() function?why we should define +str()?

- June 10, 2016

str() converts a number to (printable) text.

- July 11, 2016

I suppose that by “we have tree variables” you meant “we have three variables”

- July 22, 2016

Thanks, it’s corrected

- August 12, 2016

>>> x=5
>>> print(“x = ” + str(x))
Output: x = 5 its not getting printed as string

- August 20, 2016

Run the code from a file (program.py)

1. save as text file (program.py)
2. python program.py