Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

loops - How to optionally repeat a program in python

I'm learning python and had a quick question.

I have to write a code to find the cube root, which I've done. I want to give the user the option of calculating another cube root, or quitting.

Here's what I have come up with:

x = int(raw_input('Enter an integer:   '))

## start guessing with 0 
ans = 0

while ans*ans*ans < abs(x):
    ans = ans + 1
    print 'current guess =', ans

print 'last guess = ', ans
print 'ans*ans*ans = ', ans*ans*ans


##if its a perfect cube

if ans*ans*ans == abs(x):
## perfect, but negative
    if x<0:
            ans = -ans
    print 'Cube root of ' + str(x)+ ' is ' + str(ans)

## If its not a cube at all    
else:
    print x, 'is not a perfect cube'



## Now to start a new calculation
again = raw_input('Find another perfect cube? (Y/N)')

if again == "N":
    quit
if again == "Y":

what would go next, in case the person wants to do another problem and chose "Y"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As an alternative to the function route, you could do it in a while loop, though it would be cleaner to use functions. You could do:

choice = 'y'
while choice.lower() == 'y':
    #code for the game
    choice = raw_input ('run again? (y/n)')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...