Python代码未按预期工作

2024-10-03 06:28:34 发布

您现在位置:Python中文网/ 问答频道 /正文

因为某种原因这个代码不起作用?我尝试过返回1和break,但由于某些原因它给了我一个错误,我希望代码返回到开头,如果数字太长,但没有理想的方法。在

# 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
>>> 

Tags: inpymosthomelinefileprintbreak
2条回答

断开会使循环停止。由于您的代码不在循环中,我不明白您为什么要使用它。另外,休息后不需要冒号。我举个例子,让你知道什么时候休息。在

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后面加一个冒号。在

我想你想要的是检查用户是否输入了一个有效的数字。尝试:

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

相关问题 更多 >