» Area Calculation Program by revolution |
|
(Login to remove green text ads)
I pulled this from the instant python hacking from the hetland.org/python site linked from python.org. It is a basic area calculation script written in python and hopefully it will help get you started working and show the power of python.
Code:
# Area calculation program
print "Welcome to the Area calculation program"
print "---------------------------------------"
print
# Print out the menu:
print "Please select a shape:"
print "1 Rectangle"
print "2 Circle"
# Get the user's choice:
shape = input("> ")
# Calculate the area:
if shape == 1:
height = input("Please enter the height: ")
width = input("Please enter the width: ")
area = height*width
print "The area is", area
else:
radius = input("Please enter the radius: ")
area = 3.14*(radius**2)
print "The area is", area
New things in this example:
1. print used all by iself prints out an empty line
2. == checks whether two things are equal, as opposed to =, which assigns the value on the right side to the variable on the left. This is an important distinction!
3. ** is Python's power operator - thus the squared radius is written radius**2.
4. print can print out more than one thing. Just separate them with commas. (They will be separated by single spaces in the output.)
The program is quite simple: It asks for a number, which tells it whether the user wants to calculate the area of a rectangle or a circle. Then, it uses an if-statement (conditional execution) to decide which block it should use for the area calculation. These two blocks are essentially the same as those used in the previous area examples. Notice how the comments make the code more readable. It has been said that the first commandment of programming is: "Thou shalt comment!" Anyway - it's a nice habit to acquire.
|
|