Reputation: 1
I am trying to write the simplest code possible that will continuously print out Perfect Squares. My code so far reads this
x = 1
y = 1
while True:
final = x * y
print final
x = x + 1
y = y + 1
When I run it, I get a syntax error. The red bit is on the "final" in "print final"
Apologies if it is a really basic error, but I'm stumped.
Thanks for taking the time to read this
Upvotes: 0
Views: 1360
Reputation: 93
I would reccomend using Python 3 if you're not already. Also, as x and y are the same value at all times you only need one of them. So instead of reading:
x = 1
y = 1
while True:
final = x * y
print final
x = x + 1
y = y + 1
You should write:
x = 1
while True:
final = x * x
print(final)
x = x + 1
Hope this helped! Jake.
Upvotes: 1
Reputation: 34531
I assume you're using Python 3. print
is now a function in Python 3.
Do print(final)
instead of print final
.
Also, it seems like your x
and y
values are holding the same thing. Why not discard one of them and use just one?
x = 1
while True:
final = x * x
print(final)
x = x + 1
Or better yet, use the builtin exponentiation operator **
.
x = 1
while True:
final = x **2
print(final)
x += 1
Also, your code seems to be going into an infinite loop. You may need a condition to break
it.
For example, if you want to break when x
reaches 10
, just add a condition in the while
loop, like follows:
x = 1
while True:
final = x **2
print(final)
x += 1
if x == 10:
break
OR Specify a condition in the while
statement, like follows:
x = 1
while x < 10:
final = x **2
print(final)
x += 1
OR Use a for
loop.
for i in range(10):
print(i**2)
Upvotes: 5
Reputation: 60024
In Python 3, print
is no longer a statement but a function, so you must enclose what you want to print in parentheses:
print(final)
Here's a link about the function.
You also have an IndentationError, y = y + 1
should be given a space.
And you can simplify that to y += 1
(which is the same thing, in regards to integers)
You can also add a condition to the while-loop:
x = 0
while x < 5:
print x ** 2
x += 1
Prints:
0
1
4
9
16
Upvotes: 2