[英]Python code not working as expected
由於某種原因,此代碼將無法正常工作? 我試圖返回1並中斷,但是由於某種原因它給了我一個錯誤,如果數字太長但我不希望這樣做,我希望代碼返回到開頭。
# 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
>>>
我認為您要在此處檢查用戶是否輸入了有效數字。 嘗試:
while True:
x = int(input('Enter an integer: '))
if x > 5000:
print('too long')
else:
break
中斷將停止循環。 由於您的代碼不在循環中,因此我看不到您為什么要使用它。 另外,休息后不需要冒號。 以便您知道我將舉一個例子。
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:
就可以更輕松地完成此操作while count < 20:
但是我在說明一個要點。
編輯:另外,查看收到的其他一些錯誤, print
后也不需要冒號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.