Reputation: 33
For some reason this code will not work? I have tried return 1 and break but for some reason it gives me a error, i would like the code to return to the beginning if the number is too long but have no ideal how to do it.
# 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
>>>
Upvotes: -1
Views: 1024
Reputation: 901
I think what you wanted here is to check if the user enter a valid number. Try:
while True:
x = int(input('Enter an integer: '))
if x > 5000:
print('too long')
else:
break
Upvotes: 3
Reputation: 384
Break would stop a loop. Since your code is not in a loop, I cannot see why you would want to use it. Also, a colon is not required after break. Just so you know what break does I'll give an example.
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
Of course, this could be done easier by just doing a while count < 20:
but I am illustrating a point.
Edit: Also, looking at some of the other errors you received, you Do Not need a colon after print
either.
Upvotes: 0