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

New Free Tools on Dev Shed!

#1
January 26th, 2005, 11:32 PM
 Verashiden
Contributing User

Join Date: Jan 2005
Posts: 84
Time spent in forums: 2 Days 7 h 39 m 44 sec
Reputation Power: 9
Weird program problem

^^ Hiya, I'm new here and new to Python. At any rate I was experiment with functions and menus and came across an interesting situation

Code:
#This program calculates various areas
def print_options():
print "Options:"
print " 'p' print options"
print " 's' calculate square"
print " 'r' calculate rectangle"
print " 'c' calculate circle"
print " 'q' quit program"

def area_of_square (s_area):
return l**2

def area_of_rectangle (r_area):
return l*w

def area_of_circle (c_area):
return 3.14*r**2

choice = "p"
while choice != "q":
if choice == "s":
l = input ("Input length:")
print "The area is:", area_of_square(l)
elif choice == "r":
l = input ("Input length:")
w = input ("Input width:")
print "The area is:", area_of_rectangle (l*w)
elif choice == "c":
print "The area is:", area_of_circle (r)
elif choice == "q":
print_options ()
choice = raw_input ("Options:")

Looks okay to me but when I un the program I only get

Code:
Options:

It won't print what the options actually are. The odd thing is that the rest of the program runs fine if you input the correct letter. So... what did I do wrong?

#2
January 27th, 2005, 01:23 AM
 Zone
Contributing User

Join Date: Jan 2005
Posts: 37
Time spent in forums: 1 Day 2 h 30 m 30 sec
Reputation Power: 9
I see the following things at first glance:

- the input() function is for use with gui apps, which I assume you are not doing. The function you are looking for is raw_input(). replace all of your inputs with raw_inputs

- the raw_input function will give you a string. You'll need to transform to a float or int to do what you want. try r = int(raw_input('Enter radius:')).

- you are doing the arguments wrong to your functions. For example, in your area_of _rectangle function, change the first line to be: def area_of_rect(l,w):
now when you call it, just call it like this:
print "area of rectangle is ",area_of_rect(l,w)
The l and w in the function body are local in scope, and do not have anything to do with the l and w where you call the function. To make this more concrete, you could say: area = area_of_rect(5,9)
now, you would pass the values 5 and 9 to the function, which take these numbers and assign them to the local variables l and w in the function. it would return the answer, 45, which would then be stored in your variable called area. It is important to note that python uses 'pass by reference' semantics, however, and thus if you pass a mutable object (like a list or dictionary) to a function, that function can change the value of that mutable object back in the caller. Read the online docs about parameter passing if you have more questions.

- it looks like you've got the call to print_options() in the wrong place, i.e. it should be called if choice is p, not q. Mind your p's and q's, I guess I could say.

hope this helps

#3
January 27th, 2005, 08:31 AM
 Konstandinos
Contributing User

Join Date: Nov 2004
Location: Cape Town, South Africa
Posts: 131
Time spent in forums: 22 h 40 m 25 sec
Reputation Power: 12
Fix the indentation in the code under the last elif statement.

#4
January 27th, 2005, 04:19 PM
 monkeyman23555
Contributing User

Join Date: Nov 2004
Location: There where the rabbits jump
Posts: 556
Time spent in forums: 2 Days 23 h 24 m 55 sec
Reputation Power: 11
I guess that you want to kept it like that but ill put this up anway.

Maybe helps you but em it has all the functions in it you would need. If I understand what your program it is for. It is my first so don't laugh.
Attached Files
 calc.zip (2.0 KB, 215 views)

#5
January 27th, 2005, 05:13 PM
 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 Verashiden Looks okay to me but when I un the program I only get Code: Options: It won't print what the options actually are. The odd thing is that the rest of the program runs fine if you input the correct letter. So... what did I do wrong?

Not to worry, this is just Python asking you to supply some input. At the end of your while loop you have the line: choice = raw_input ("Options:")

The reason your seeing "Options:" is because pythons input functions (raw_input() and input()) print the string passed to them so that the user know that the program ready and waiting for them to type something. When the user presses the enter key, everything the user has typed is assigned to the choice variable.

In any case, if you enter either 's', 'r', 'c' or 'q' everything should should be fine .

Hope this helps,

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

Last edited by netytan : January 27th, 2005 at 05:23 PM.

#6
January 27th, 2005, 06:26 PM
 Verashiden
Contributing User

Join Date: Jan 2005
Posts: 84
Time spent in forums: 2 Days 7 h 39 m 44 sec
Reputation Power: 9
All right... so trying this...

Code:
#This programs calculates areas of various shapes
def print_options():
print "Options:"
print " 'p' print options"
print " 's' calculate square"
print " 'r' calculate rectangle"
print " 'c' calculate circle"
print " 'q' quit program"

def area_of_square (l):
return l**2

def area_of_rectangle (l,w):
return l*w

def area_of_circle (r):
return 3.14*r**2

choice = "p"
while choice != "q":
if choice == "s":
l = input (raw_input("Input length:"))
print "The area is:", area_of_square(l)
elif choice == "r":
l = int (raw_input("Input length:"))
w = int (raw_input("Input width:"))
print "The area is:", area_of_rectangle (l,w)
elif choice == "c":
r = int (raw_input ("Input radius:"))
print "The area is:", area_of_circle (r)
elif choice == "q":
print_options ()
choice = raw_input ("Options:")

Is this right or not? It works but I want t o see what a good version would look like.

#7
January 27th, 2005, 06:51 PM
 CyBerHigh
Contributing User

Join Date: Jun 2004
Posts: 461
Time spent in forums: 4 Days 12 h 36 m 28 sec
Reputation Power: 24
why is input for gui apps? Why can't ti work for command line apps?

I have used both, but i have never head that it was only for gui.

#8
January 27th, 2005, 11:59 PM
 Zone
Contributing User

Join Date: Jan 2005
Posts: 37
Time spent in forums: 1 Day 2 h 30 m 30 sec
Reputation Power: 9
Quote:
 Originally Posted by CyBerHigh why is input for gui apps? Why can't ti work for command line apps? I have used both, but i have never head that it was only for gui.

This might be wrong on my part to have said that it is for gui applications. Using input() actually uses raw_input() to read a string, and then evaluates that string as if it were a python program. Using input(), the following would work:

>>> a = input('give me a list of nums from 0 to 99')

and the user could type:

range(0,100)

Now the variable a would be a list object with elements 0 to 99.

I suppose when you are just entering integers, input works just as well. I typically use raw_input, because then I can do error handling, and look at what I actually got from the user. If I use input, and the user types in something bogus, I get an error right away.

It turns out that input() is identical to eval(raw_input()). I have typically seen input() used in gui apps, but you are definitely right, there is no requirement for it to be so. Hope I didn't confuse anyone!

#9
January 28th, 2005, 01:50 AM
 Zone
Contributing User

Join Date: Jan 2005
Posts: 37
Time spent in forums: 1 Day 2 h 30 m 30 sec
Reputation Power: 9
Quote:
 Originally Posted by Verashiden Is this right or not? It works but I want t o see what a good version would look like.

I certainly hesitate to hold up my code as a 'good' version, but I'll submit it anyway and accept any spears others have for me. Here's how I would do it if were to write the same program, trying to keep the general idea the same:

Code:
from math import pi

def print_options():
print """Options:
'p' - print options
's' - calculate square
'r' - calculate rectangle
'c' - calculate circle
'q' - quit program"""

def square(l):
return l**2

def rect(l,w):
return l*w

def circle(r):
return pi * r**2

def is_number(stuff):
if stuff.count('.') <=1 and stuff.replace('.','').isdigit(): return True
else: return False

def getChoice():
choice = raw_input('Enter your choice: ')
if choice in ['p','s','r','c','q']:
return choice
else:
print 'Invalid selection. Try again.'
return getChoice()

print_options()
while True:
choice = getChoice()
if choice == 'p': print_options()
elif choice == 's':
l = raw_input("Enter length of a side:")
if is_number(l): print "the area is ",square(float(l))
else: print "Invalid number."
elif choice == 'r':
l = raw_input("Enter length:")
w = raw_input("Enter width:")
if is_number(l) and is_number(w): print "the area is ",rect(float(l),float(w))
else: print "Invalid number entered"
elif choice == 'c':
if is_number(r): print "the area is ",circle(float(r))
else: print "Invalid Number."
elif choice == 'q':
break

A few things to note about my way, that are probably worth showing a newbie...

the from math import pi - it's easy and more precise than 3.14, and illustrates the idea of importing only what you need from a module

the triple quoted string in the print_options function

the error checking is_number() function... In real life I would probably accomplish this task using exceptions, but I would program for a bit before using these, imho

the use of 'in' in the getChoice() function

the recursive call in the getChoice function which allows the user to enter 1000 bogus inputs... yes, there's other ways to do this, but this works well, and is pretty clean in my opinion

Hope this helps, let me know if you have questions, of if anyone has comments that could help me out with my coding style

#10
January 28th, 2005, 08:54 PM
 Verashiden
Contributing User

Join Date: Jan 2005
Posts: 84
Time spent in forums: 2 Days 7 h 39 m 44 sec
Reputation Power: 9
Interesting. I don't get what float does. May you explain?

#11
January 29th, 2005, 01:39 PM
 Zone
Contributing User

Join Date: Jan 2005
Posts: 37
Time spent in forums: 1 Day 2 h 30 m 30 sec
Reputation Power: 9
float() just converts to a floating point number (in our case from a string to a floating point), such as:

>>>float('3.14')
3.14

it also works for other types, like int:

>>>float(3)
3.0

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Weird program problem