curtis brown
curtis brown

Reputation: 1

basic for loop problems in python

this is a really easy coding problem, I haven't coded since highschool, and I am super rusty! I'm probably missing something super obvious. I get an invalid syntax error on the for line of the code, an I don't understand why.. how can I get this simple code to work? what am I doing wrong?

p=1
a=p+60
p = p+6*2/2*45
if (p == 271):
    p=3000


print ("this is p:")
print (p)
print ("this is a")
print (a)
for ( p > a ):
        p=p-1
        print (p)

Upvotes: 0

Views: 71

Answers (2)

Angus L'Herrou
Angus L'Herrou

Reputation: 439

Python's for construct is logically equivalent to the foreach construct in many other languages; in other words, it is for iterating over the items in an iterable.

From your code, it looks like you are trying to keep iterating as long as the condition p > a holds true. In Python, this is a situation where you would want to use a while loop:

while p > a:
    p = p - 1
    print(p)

Note also that you don't need parentheses around the condition, unlike in some other languages.

Upvotes: 0

BTables
BTables

Reputation: 4803

You're using a for loop when you should be using a while loop. A for loop will loop through an iterable object or collection and a while loop will continue as long as a condition is True. Also the parentheses are not need for if and for:

p=1
a=p+60
p = p+6*2/2*45
if p == 271:
    p=3000


print ("this is p:")
print (p)
print ("this is a")
print (a)
while p > a :
        p=p-1
        print (p)

Upvotes: 3

Related Questions