|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
A little help (Just starting!)
Sorry if this seems a bit stupid, but I'm just learning Python (as a first programming language, too). Anyways, here it goes. I'm writing a simple little program like this:
Code:
import sys
print """
Choose a shape from the list:
1) Triangle
2) Square
3) Circle
4) Quit
"""
shape = raw_input("Choose an option[1,2,3,4]? ")
if shape == '1':
ht = input('What is the height of your triangle? ')
base = input('How long is the base? ')
print "The triangle's area is: ", 05*base*ht
elif shape == '2':
side = input('How long are the square sides? ')
print "The square's area is: ", side*side
elif shape == '3':
rad = input('What radius is your circle? ')
print "The circle's area is: ", 3.14159*rad*rad
elif shape == '4':
quit = sys.exit()
else:
print "Sorry, you did not enter a valid choice."
But, what I want to know is how to make the program restart (so it presents you with the list of choices again) after you make your choice. Any help is greatly appreciated! -Tim |
|
#2
|
||||
|
||||
|
Try a while loop:
Code:
while True:
#your code indented here
Grim ![]()
__________________
*** Experimental Python Markup CGI V2 *** |
|
#3
|
||||
|
||||
|
If you put the body of your program inside a while True loop then your program will keep running untill you make a call to the break keyword i.e.
Code:
#!/usr/bin/env python
while True:
choice = raw_input("1 or 2")
if choice == '1':
print 'you said one... You Win, YAY'
elif choice == '2':
print 'you said two... bad luck, bye'
break
else:
print 'I said 1 or 2 dummy, try again'
Also, you should probably use int(raw_input()) over input since it is possable for input() to be used to executure arbitary code since input() is actually the same as doing eval(input()). Which is why you can do things like 1 + 2 though input(). Have fun, Mark. |
|
#4
|
||||
|
||||
|
Ooops, lucks like you beat me there Grim
.Mark. |
|
#5
|
|||
|
|||
|
Ah, I knew it had something to do with loops, but I couldn't quite figure out how they worked. Thanks a lot.
![]() |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > A little help (Just starting!) |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|