Python Variables and Operators

Python Variables

Using variables is one of the most powerful features in Python. Use assignment statements to create variables and give them values.

From the chevron prompt in the Python interpreter:

>>> x = 12
>>> message = “You are doing a good job!”

 

In the code samples above, two variables were created. Now you could tell Python:

>>> print x
12
>>> print message
“You are doing a good job!”

 

You can name variables with almost whatever you want, but it is good practice to give them a name that is meaningful.

The two main rules for naming variables are:

Python Operators

You need to know how to use operators ‘+, -, *, /, and **’. The operator ‘**’ is for exponentiation.

The order of operations follows the same PEMDAS rules. For example:

>>> x = 2 + 3 * 5
>>> print x
17

 

Beware of the Division Operator

The division operator might not do what you expect.

>>> y = 1 / 2
>>> print y
0

 
Why zero? When both operands are integers, the result is an integer. In other words, the decimal part gets chopped off. To solve this you have to use float types.

>>> y = float(1) / float(2)

 

One other operator, that is surprising useful, is ‘%’, the modulus operator. It yields the remainder.

>>> y = 5 % 2
>>> print y
1

 

Finally, use the ‘+’ operator for concatenation. That is, joining strings together.

>>> print ‘Hello,’ + ‘ World!’
Hello, World!

 

Leave a Reply

Your email address will not be published. Required fields are marked *