2014-02-13 85 views
0

由於某些原因,此代碼不起作用?我已經嘗試過返回1並中斷,但由於某種原因,它給了我一個錯誤,我希望代碼返回到開頭,如果數字太長,但沒有理想的如何去做。Python代碼不能按預期工作

# Find the cube root of a perfect cube 

x = int(input('Enter an integer: ')) 
if x > 5000: 
    break: 
    print('too long') 
### this code is broken ^^^^^ 



ans = 0 
while ans**3 < x: 
    ans = ans + 1 
if ans**3 != x: 
    print(str(x) + ' is not a perfect cube') 
else: 
    print('Cube root of ' + str(x) + ' is ' + str(ans)) 


IndentationError: unexpected indent 
>>> runfile('/home/dux/pyyyyy.py', wdir=r'/home/dux') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile 
    execfile(filename, namespace) 
    File "/home/dux/pyyyyy.py", line 7 
    print('wrong'): 
       ^
SyntaxError: invalid syntax 
>>> runfile('/home/dux/pyyyyy.py', wdir=r'/home/dux') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile 
    execfile(filename, namespace) 
    File "/home/dux/pyyyyy.py", line 7 
    break: 
     ^
SyntaxError: invalid syntax 
>>> runfile('/home/dux/pyyyyy.py', wdir=r'/home/dux') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile 
    execfile(filename, namespace) 
    File "/home/dux/pyyyyy.py", line 8 
    print('wrong') 
    ^
IndentationError: unexpected indent 
>>> runfile('/home/dux/pyyyyy.py', wdir=r'/home/dux') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile 
    execfile(filename, namespace) 
    File "/home/dux/pyyyyy.py", line 7 
    break: 
     ^
SyntaxError: invalid syntax 
>>> 
+0

你確定你知道[什麼'break'確實](http://docs.python.org/2/tutorial/controlflow.html)? – goncalopp

+0

您是否爲breakpoint或yield而產生了「break」? – ereOn

回答

0

休息會停止循環。由於你的代碼不在循環中,我不明白你爲什麼要使用它。另外,休息後不需要冒號。只是讓你知道我會舉一個例子。

count = 0 
while True: 
    print('Hello') #Prints Hello 
    if count == 20: #Checks if count is equal to 20 
     break #If it is: break the loop 
    count += 1 #Add 1 to count 

當然,這可以通過只是做了while count < 20:,但我出點來完成更容易。

編輯:另外,看看你收到的一些其他錯誤,你不要print也需要冒號。

3

我想你在這裏想要的是檢查用戶是否輸入一個有效的數字。嘗試:

while True: 
    x = int(input('Enter an integer: ')) 
    if x > 5000: 
     print('too long') 
    else: 
     break