April 2nd, 2005, 04:32 AM

python newbey
i am making a program that automatically does mathematical formulas. i have this so far:
b = 1
while b == 1:
a = input('If you want to calculate the area of a circle, press 1 now. '
'If you want to calculate the perimeter of a rectangle, press 2 now. '
'If you want to calculate the circumference of a circle, press 3 now. '
'If you want to convert fahrenheit to celsius, or vice versa, press 4 now. ')
if a == 1:
radius = input('Enter the radius of the circle:')
print 'The area of the circle is:', radius*radius*3.14
b = input('To go back to the main menu, press 1 now. To quit, press 0 now.')
if a == 2:
lenght = input('Enter the lenght of the rectangle.')
width = input('Enter the width of the rectangle.')
print 'The perimeter of the rectangle is:', 2*lenght+2*width
b = input('To go back to the main menu, press 1 now. To quit, press 0 now.')
if a == 3:
radius = input('Enter the radius of the circle:')
print 'The circumference of the circle is:', 2*radius*3.14
b = input('To go back to the main menu, press 1 now. To quit, press 0 now.')
if a == 4:
temp = input('To convert celsius to fahrenheit, press 1 now. '
'To convert fahrenheit to celsius, press 2 now. ')
if temp == 1:
celsius = input('Enter number of degrees celsius now. ')
print 'That is', 9.0/5.0*celsius+32.0, 'degrees fahrenheit.'
b = input('To go back to the main menu, press 1 now. To quit, press 0 now.')
if temp == 2:
fahrenheit = input('Enter number of degrees fahrenheit now. ')
print 'That is', 5.0/9.0*(fahrenheit32.0), 'degrees celsius. '
b = input('To go back to the main menu, press 1 now. To quit, press 0 now.')
it works, but how can i make it so that there is an option to go back to a particular formula? (a particular a?)? please help.
April 2nd, 2005, 07:37 AM

If you are writing code that you wish to call more than once, make a function out of it:
Code:
def calculate(a):
if a == 1:
radius = input('Enter the radius of the circle:')
print 'The area of the circle is:', radius*radius*3.14
if a == 2:
length = input('Enter the length of the rectangle.')
width = input('Enter the width of the rectangle.')
print 'The perimeter of the rectangle is:', 2*length+2*width
if a == 3:
radius = input('Enter the radius of the circle:')
print 'The circumference of the circle is:', 2*radius*3.14
# Menu
while True:
print 'If you want to calculate the area of a circle, press 1 now. '
print 'If you want to calculate the perimeter of a rectangle, press 2 now. '
print 'If you want to calculate the circumference of a circle, press 3 now. '
print 'If you want to convert fahrenheit to celsius, or vice versa, press 4 now.'
print 'Press 0 to quit'
choice = input()
if choice == 0:
break
calculate(choice)
Comments on this post
April 2nd, 2005, 02:19 PM

thx
thx; your code works, but what i wanted was an option such as: to repeat, press 1; to go back to the main menu, press 2;
to quit, press 3; thx anyway.
April 2nd, 2005, 02:24 PM

quick ?
by the way, what does it mean when u wrote
choice = input()
if choice == 0:
break
calculate(choice)
April 2nd, 2005, 07:46 PM

To start with, I recommend you read the New Members thread for the explanation on using the [ code ] tags, so that when you post code it will retain it's indentation.
I'll get to the part about how to repeat operations in a moment, but first let's cover the second question.
OK, if you aren't familiar with functions, then what you need to see is that the program is broken into (in this case) two parts, The first part is the definition for calculate() function
Code:
def calculate(a):
if a == 1:
radius = input('Enter the radius of the circle:')
print 'The area of the circle is:', radius*radius*3.14
if a == 2:
length = input('Enter the length of the rectangle.')
width = input('Enter the width of the rectangle.')
print 'The perimeter of the rectangle is:', 2*length+2*width
if a == 3:
radius = input('Enter the radius of the circle:')
print 'The circumference of the circle is:', 2*radius*3.14
This basically gives a name to this block of code. When the program is run, it defines the function, which then gets run whenever the term calculate() appears in the program.
A program can have as many functions as you want to define, and a function can be called an unlimited number of times (at least in priniciple). They are a useful way of breaking programs into more manageable parts, and allow you to use the same code in more than one place without duplication. Any function can call any other function (even itself) so long as the actual start of the program comes after the function definitions. See this thread for some additional information on functions.
How you break the program up into functions is at least in part a matter of personal taste; some programmers (like me) tend to use a lot of small functions, while others prefer to to simply write to use larger pieces for most of the program. It is possible to use functions defined in other program files, using the from and import directives.
Code:
from filename import function
The second half of the source code is the program itself:
Code:
# Menu
while True:
print 'If you want to calculate the area of a circle, press 1 now. '
print 'If you want to calculate the perimeter of a rectangle, press 2 now. '
print 'If you want to calculate the circumference of a circle, press 3 now. '
print 'If you want to convert fahrenheit to celsius, or vice versa, press 4 now.'
print 'Press 0 to quit'
choice = input()
if choice == 0:
break
calculate(choice)
The program execution begins with the while true: clause, which basically means 'loop forever'. The loop begins by printing the menu, then gets the answer. If the a is 0, then it breaks out of the loop; otherwise, it passes a to the function calculate() and continues the loop. This could have been also written as
Code:
# Menu
a = 1
while a != 0:
print 'If you want to calculate the area of a circle, press 1 now. '
print 'If you want to calculate the perimeter of a rectangle, press 2 now. '
print 'If you want to calculate the circumference of a circle, press 3 now. '
print 'If you want to convert fahrenheit to celsius, or vice versa, press 4 now.'
print 'Press 0 to quit'
choice = input()
if a != 0:
calculate(choice)
Either way would be right; the way SFB wrote it is somewhat less redundant, but not quite as clear. There are still other ways to write it, as I will show you in a moment. Now, remember what I said about small functions versus large functions? Well, one of the advantages of smaller functions is that you can separate the parts of the code that do the actual calculations from the parts that read in the data and print out the results. So, if I were writing this, and both from the control flow (looping, etc.) of the program as a whole. I would probably write functions for each of the different operations:
Code:
from sys import exit # this is used later to exit the program
from string import upper # function to convert chars to upper case
PI = 3.14159 # defined constant used by the functions below
def circle_area(radius):
return (radius**2) * PI
def circle_circ(radius):
return (2 * PI * radius)
def rect_perimeter(length, height):
return (2 * length) + (2 * height)
def Fahr2Celsius(fahrenheit):
return 5.0 / 9.0 * (fahrenheit  32.0)
def Celsius2Fahr(celsius):
return 9.0 / 5.0 * celsius + 32.0
def convert_degrees():
"get the option for the temperature conversion"
print 'To convert celsius to fahrenheit, press 1 now. '
direction = input('To convert fahrenheit to celsius, press 2 now. ')
if direction == 1:
celsius = input('Enter number of degrees celsius now. ')
print 'That is ', Celsius2Fahr(celsius), 'degrees fahrenheit.'
elif direction == 2:
fahrenheit = input('Enter number of degrees fahrenheit now. ')
print 'That is', Fahr2Celsius(fahrenheit), 'degrees celsius. '
else:
print "I'm sorry, that wasn't a valid choice."
convert_degrees() # if the answer was valid, repeat the function
def menu():
"print the menu and return the choice"
print 'If you want to calculate the area of a circle, press 1 now. '
print 'If you want to calculate the perimeter of a rectangle, press 2 now. '
print 'If you want to calculate the circumference of a circle, press 3 now. '
print 'If you want to convert fahrenheit to celsius, or vice versa, press 4 now.'
print 'Press 0 to quit'
return input()
def conversion(choice):
if choice == 0:
print "Goodbye."
exit() # quit program
elif choice == 1:
radius = input('Enter the radius of the circle: ')
print 'The area of the circle is:', circle_area(radius)
elif choice == 2:
length = input('Enter the length of the rectangle. ')
width = input('Enter the width of the rectangle. ')
print 'The perimeter of the rectangle is:', rect_perimeter(length, width)
elif choice == 3:
radius = input('Enter the radius of the circle: ')
print 'The circumference of the circle is:', circle_circ(radius)
elif choice == 4:
convert_degrees()
else:
print "I'm sorry, that wasn't a valid choice."
return
repeat = raw_input("Do you want to do repeat that operation? (Y/N) ")
if 'Y' == upper(repeat):
conversion(choice)
# main program loop
while True:
conversion(menu())
print
While this is longer and more complex than your version, it should be easier to understand overall. Let me know if you have any questions about this version of the program.
EDIT: Made one small fix to the code: in the 'invalid entry' else: clause in conversion(), I replaced the recursive call with a return statement. This gets rid of a minor bug that could cause it to ask the repeat question twice.
Last edited by ScholRLEA; April 3rd, 2005 at 07:31 PM.
April 3rd, 2005, 02:54 PM

April 3rd, 2005, 10:45 PM

Originally Posted by ScholRLEA
Code:
PI = 3.14159 # defined constant used by the functions below
def conversion(choice):
elif choice == 1:
radius = input('Enter the radius of the circle: ')
print 'The area of the circle is:', circle_area(radius)
Two things:
1/ Do not use input(). EVER. The automatic eval may appear handy but it's not only a security hole, it's also likely to make your program crash. Given that you're going to have to do exception handling anyway, you should use raw_input instead, and do the conversion yourself.
try entering the following as your radius, for instance:
Code:
globals().__setitem__("sys", __import__("sys")) or sys.stdout.write("Whoops! Something bad could happen here!") or 4
2/ Instead of defining pi yourself, use math.pi:
Code:
from math import pi
OH.
Comments on this post
April 4th, 2005, 12:30 AM

Many thanks, OH; while I'm fairly well versed in programing in general, I'm still learning many of the details of the language itself (something I've found is an endless process, especially in languages like Python which are still actively evolving).
The second one should have been obvious, and in fact it occurred to me that there might be a defined PI constant already, but I was concentrating on explaining what I was recommending. I should have checked to see first.
As for the input() function, I wasn't aware of the security issues involved  indeed, every tutorial and reference I've seen so far used it consistently. I doubt I'm the only one who isn't aware of this.
April 4th, 2005, 08:04 AM

Originally Posted by ScholRLEA
As for the input() function, I wasn't aware of the security issues involved  indeed, every tutorial and reference I've seen so far used it consistently. I doubt I'm the only one who isn't aware of this.
You're not the first Schol' but we try to point it out whenever we see it being used. I'm at a loss to explain why input() is being used in tutorials , anyone who knows enough to write about Python should know that input() shouldn't be used.
It's possible the writer was attempting not to confuse the new reader (but that's not really an excuse).
Nice thread all,
Mark.
April 5th, 2005, 02:21 AM

Originally Posted by ScholRLEA
Many thanks, OH; while I'm fairly well versed in programing in general,
As for the input() function, I wasn't aware of the security issues involved  indeed, every tutorial and reference I've seen so far used it consistently. I doubt I'm the only one who isn't aware of this
Yeah  I figured that you were a competent programmer in general from your other posts [Hey ... you're a Schemer and can cope with callcc *brrrrrr* ]
Originally Posted by netytan
You're not the first Schol' but we try to point it out whenever we see it being used. I'm at a loss to explain why input() is being used in tutorials
, anyone who knows enough to write about Python should know that input() shouldn't be used.
It probably functions as a broad indicator as to whose tutorials not to use ;P
raw_input(), BTW, returns a string [which can be then converted as necessary]
input() is a misfeature. Hopefully it will be deprecated soon, so that it can be removed from later versions of Python2 and resurface as Py3k's spelling of raw_input().
OH.