Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Using Expressions

Example 5.1. Using Expressions

#!/usr/bin/python # Filename: expression.py

length = 5 breadth = 2

area = length * breadth
print 'Area is', area
print 'Perimeter is', 2 * (length + breadth)

Output

$ python expression.py Area is 10
Perimeter is 14

How It Works

The length and breadth of the rectangle are stored in variables by the same name. We use these to calculate the area and perimieter of the rectangle with the help of expressions. We store the result of the expressionlength * breadth in the variablearea and then print it using theprint statement. In the second case, we directly use the value of the expression2 * (length + breadth) in the print statement.

Also, notice how Python 'pretty-prints' the output. Even though we have not specified a space between 'Area is' and the variablearea, Python puts it for us so that we get a clean nice output and the program is much more readable this way (since we don't need to worry about spacing in the output). This is an example of how Python makes life easy for the programmer.