Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
April 2nd, 2005, 04:32 AM
 hye345
Registered User

Join Date: Apr 2005
Posts: 14
Time spent in forums: 1 h 13 m 59 sec
Reputation Power: 0
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:
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:
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*(fahrenheit-32.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.

#2
April 2nd, 2005, 07:37 AM
 sfb
Contributing User

Join Date: Nov 2003
Posts: 624
Time spent in forums: 3 Days 6 h 10 m 21 sec
Reputation Power: 34
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:

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:
print 'The circumference of the circle is:', 2*radius*3.14

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)```
Yegg` agrees!

#3
April 2nd, 2005, 02:19 PM
 hye345
Registered User

Join Date: Apr 2005
Posts: 14
Time spent in forums: 1 h 13 m 59 sec
Reputation Power: 0
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.

#4
April 2nd, 2005, 02:24 PM
 hye345
Registered User

Join Date: Apr 2005
Posts: 14
Time spent in forums: 1 h 13 m 59 sec
Reputation Power: 0
quick ?

by the way, what does it mean when u wrote

choice = input()
if choice == 0:
break

calculate(choice)

#5
April 2nd, 2005, 07:46 PM
 Schol-R-LEA
Commie Mutant Traitor

Join Date: Jun 2004
Location: Norcross, GA (again)
Posts: 1,800
Time spent in forums: 1 Month 2 Weeks 3 Days 2 h 27 m 30 sec
Reputation Power: 1569
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:

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:
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

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

"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:
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:
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:
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.
__________________
Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
#define KINSEY (rand() % 7) λ Scheme is the Red Pill
Scheme in ShortUnderstanding the C/C++ Preprocessor
Taming PythonA Highly Opinionated Review of Programming Languages for the Novice, v1.1

FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. \$4500 obo. tverres@et.ins.gov

Last edited by Schol-R-LEA : April 3rd, 2005 at 07:31 PM.

#6
April 3rd, 2005, 02:54 PM
 hye345
Registered User

Join Date: Apr 2005
Posts: 14
Time spent in forums: 1 h 13 m 59 sec
Reputation Power: 0
damn!!!!!!!

thx a lot man

#7
April 3rd, 2005, 10:45 PM
 hydroxide
Contributing User

Join Date: Feb 2005
Posts: 78
Time spent in forums: 21 h 40 m 18 sec
Reputation Power: 9
Quote:
 Originally Posted by Schol-R-LEA 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.
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.
netytan agrees: input() is eval.

#8
April 4th, 2005, 12:30 AM
 Schol-R-LEA
Commie Mutant Traitor

Join Date: Jun 2004
Location: Norcross, GA (again)
Posts: 1,800
Time spent in forums: 1 Month 2 Weeks 3 Days 2 h 27 m 30 sec
Reputation Power: 1569
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.

#9
April 4th, 2005, 08:04 AM
 netytan
Hello World :)

Join Date: Mar 2003
Location: Hull, UK
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
Quote:
 Originally Posted by Schol-R-LEA 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).

Mark.
__________________
programming language development: www.netytan.com Hula

#10
April 5th, 2005, 02:21 AM
 hydroxide
Contributing User

Join Date: Feb 2005
Posts: 78
Time spent in forums: 21 h 40 m 18 sec
Reputation Power: 9
Quote:
 Originally Posted by Schol-R-LEA 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 call-cc *brrrrrr* ]

Quote:
 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.

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > python newbey