我正在学习python并且有一个快速的问题。
我必须编写一个代码来查找我已经完成的多维数据集根目录。 我想让用户选择计算另一个立方根,或者退出。
以下是我的想法:
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":
如果这个人想要做另一个问题并选择“Y”,接下来会发生什么?
答案 0 :(得分:1)
你可以将所有内容都放在一个函数中:
def my_func():
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":
my_func()
if __name__ == '__main__':
my_func()
答案 1 :(得分:1)
作为函数路径的替代方法,您可以在while循环中执行此操作,但使用函数会更清晰。你可以这样做:
choice = 'y'
while choice.lower() == 'y':
#code for the game
choice = raw_input ('run again? (y/n)')
答案 2 :(得分:0)
还有另一种方式,类似于@xgord答案。 使用while循环。我写的东西更长,但对我来说更简单
repeat = False
while not repeat:
# game code
play = input("Play again? (y/n)")
if play == "y":
repetition = False
else:
exit()