[Tutor] Function problem
Eri Mendz
jerimed at myrealbox.com
Sat Nov 6 10:26:28 CET 2004
On Fri, 5 Nov 2004, Danny Yoo wrote:
>
> On Fri, 5 Nov 2004, Eri Mendz wrote:
>
>> The problem of my script below is in the proceed function: if Y is
>> selected, instead of staying in the option menu, the program just shows
>> the option menu then exits.
[...]
> The breaks cause us to jump out of the while loop if either temperature
> choice gets selected.
>
> I'm guessing that you're using a C switch statement idiom. But since that
> idiom isn't applicable in Python, you should just drop them.
>
Got it working now, thanks for the tip. Indeed the break keyword is the
culprit. Here is the corrected code:
import sys
def print_options():
print '''
THIS IS A TEMPERATURE CONVERSION PROGRAM.
Options:
[C] - convert to Celsius
[F] - convert to Fahrenheit
[P] - print options
[Q] - quit
'''
print_options()
def f2c(ctemp):
return (9/5.0)*ctemp + 32
def c2f(ftemp):
return (ftemp - 32) * 5/9.0
def proceed():
proceed = raw_input("do another conversion? [Y|N]: ")
if proceed == 'y' or proceed =='Y':
print_options()
else:
confirmQuit()
def confirmQuit():
ask = raw_input("Really quit program? [Y|N]: ")
if ask == 'y' or ask == 'Y' or ask == 'ye' or ask == 'yes':
sys.exit("bye")
else:
print_options()
# begin
while 1:
choice = raw_input("select options: ")
if choice == 'c' or choice == 'C':
try:
getftemp = int(raw_input("enter fahrenheit temperature: "))
print "temp in C is: ", c2f(getftemp)
proceed()
except ValueError:
print "error: not a valid input!"
print_options() # new added: return to main menu
# break
elif choice == 'f' or choice == 'F':
try:
getctemp = int(raw_input("enter centigrade temperature: "))
print "temp in F is: ", f2c(getctemp)
proceed()
except ValueError:
print "error: not a valid input!"
print_options() # ditto
# break
elif choice =='p' or choice == 'P':
print_options()
elif choice =='q' or choice == 'Q':
confirmQuit()
else:
print "invalid option"
print_options() # ditto
print "bye"
How do i make the program accept decimal numbers, not just integers?
Inputting the former is caught by the exception and i want to correct
that. I also want to use regular expression for the Y|N portion; e.g.,
something like if ask == [Y|y|ye|yes] or ask == [N|n|no|nope]... to that
effect. Any help is appreciated.
--
Regards,
Eri Mendz
Using PC-Pine 4.61
More information about the Tutor
mailing list