472,328 Members | 1,730 Online

# Program failing after converting global variables/ to local 48
I converted this program from using global variables to local variables. When I did that my while loop stopped working in my main function(module). Anyone, any idea why? I underlined the area where I think the problem occured after my changes.

Old Code working FINE
Expand|Select|Wrap|Line Numbers
1. from math import *
2.
5.     print "\nSlect one of the following:"
6.     print "1. Calculate Area of Rectangle"
7.     print "2. Calculate Area of Circle"
8.     print "3. Quit"
11.         menuSel=input("Please re-enter a valid selection of 1, 2, or 3: ")
12.     return
13.
14. def rectangle():
15.     print "You have chosen a rectangle."
16.     b=input("enter base  : ")
17.     h=input("enter height:")
18.     print "The area is ", b*h
19.     return
20.
21. def circle():
22.     print "You have chosen a circle."
24.     print "The area is ",pi*r**2
25.     return
26.
27.
28. def main():
32.             rectangle()
34.             circle()
36.     return
37.
38. main()
39. raw_input("\nPress enter to exit.")
40.
New Code NOT working

Expand|Select|Wrap|Line Numbers
1. from math import *
2.
4.     print "\nSlect one of the following:"
5.     print "1. Calculate Area of Rectangle"
6.     print "2. Calculate Area of Circle"
7.     print "3. Quit"
10.         menuSel=input("Please re-enter a valid selection of 1, 2, or 3: ")
11.     return
12.
13. def rectangle():
14.     print "You have chosen a rectangle."
15.     b=input("enter base  : ")
16.     h=input("enter height:")
17.     print "The area is ", b*h
18.     return
19.
20. def circle():
21.     print "You have chosen a circle."
23.     print "The area is ",pi*r**2
24.     return
25.
26.
27. def main():
29.     while choice!=3:
30.         if choice==1:
31.             rectangle()
32.         elif choice==2:
33.             circle()
35.     return
36.
37. main()
38. raw_input("\nPress enter to exit.")
39.
Dec 6 '06 #1
1 1696 bartonc
6,596 Expert 4TB
You have to return the value from you functions. ie:
Expand|Select|Wrap|Line Numbers
2.     print "\nSlect one of the following:"
3.     print "1. Calculate Area of Rectangle"
4.     print "2. Calculate Area of Circle"
5.     print "3. Quit"
8.         menuSel=input("Please re-enter a valid selection of 1, 2, or 3: ")
In fact, if you don't need value returned (some languages call this a "procedure"), there is no need to put the return at the end. Such functions (and the way you wrote them) return None. Return can also be used to jump out of a fuction at any point. ie:

Expand|Select|Wrap|Line Numbers
1. if time_to_exit:
2.     return
Dec 6 '06 #2