Chapter 1, Elementary Programming¶

Program 1-1 , Page number: 2¶

In [1]:
# An interactive program to calculate the hypotenuse of a right triangle

import math ## library for using sqrt function

def square(a):
"""Returns the square of the given number """
return a*a

print "Enter the lengths of the two legs of a right triangle"
print "The program will display the length of the hypotenuse."
print "Enter zero or negative values to end program"

print "First leg (0.0 to quit)? ",
a_leg = 3
print a_leg
print "Second leg (0.0 to quit)? ",
b_leg = 4
print b_leg

while a_leg>0.0 and b_leg>0.0:
print "The legs of the right triangle are %.2f and %.2f,\n"%(a_leg,b_leg),
# Hypotenuse is square root of a*a + b*b
hypotenuse = math.sqrt(square(a_leg) + square(b_leg))
print "   so the hypotenuse is %.2f\n\n"%hypotenuse,
print "First leg (0.0 to quit)? ",
a_leg = 0.0			# To terminate the loop
print a_leg
print "Second leg (0.0 to quit)? ",
b_leg = 0.0
print b_leg

print "Thank you."

Enter the lengths of the two legs of a right triangle
The program will display the length of the hypotenuse.
Enter zero or negative values to end program
First leg (0.0 to quit)?  3
Second leg (0.0 to quit)?  4
The legs of the right triangle are 3.00 and 4.00,
so the hypotenuse is 5.00

First leg (0.0 to quit)?  0.0
Second leg (0.0 to quit)?  0.0
Thank you.


Program 1-2 , Page number: 3¶

In [2]:
def main():
"""simply returns a string"""
# There's no main() function in python.This main() function is no different that any other user-defined functions
return "Welcome to C programming!\n"

print main()

Welcome to C programming!



Program 1-3 , Page number: 6¶

In [3]:
# Use of braces

def main():
# in python, proper indentation works as braces
# the following lines come under the main() function block due to indentation
print "Give me land, lots of land",
print "And the starry skies above...\n",

main()

Give me land, lots of land And the starry skies above...


Program 1-4 , Page number: 8¶

In [4]:
# A short poem

def main():
print "Mary had a little lamb,",
print "its fleece was white as snow.\n",
print "And everywhere that Mary went,",
print "the lamb was sure to go.\n"

main()

Mary had a little lamb, its fleece was white as snow.
And everywhere that Mary went, the lamb was sure to go.