A Byte of Python

Expressions

Example 5.1. Using Expressions

#!/usr/bin/env python 
# Filename: expression.py 
 
length = 5 # assignment statement
breadth = 2 
 
area = length * breadth # typical assignment using value of an expression
 
print 'Area is', area 
print 'Perimeter is', 2 * (length + breadth) # notice use of expressions directly

Output

$ python expression.py
Area is 10 
Perimeter is 14

How It Works

The purpose of this program is that we are given the length and breadth of a rectangle. We have to calculate and print the area and perimeter of the same rectangle.

We store the numerical values of the length and breadth of the rectangle using variables (of the same name). We calculate the expression length * breadth and store the value using the area variable. Then, we just print the area. In the case of the perimeter, we directly print the value of the expression 2 * (length + breadth).

Notice how Python pretty-prints the output for us. Even though we have not specified a space between the string 'Area is' and the variable area, Python puts a space there for us and we get a clean nice output without cluttering our program with spaces.