Python for loop - syntax error

Hi Everyone!

I’m using Python for data analysis at work, relatively new, but one of the first things is to add all sales $ that are greater than 0…the code is below.

Why am I getting a syntax error on the ‘for’ of the loop?

total_sales = 0
total_sales_logic = for i in cust_rep[‘Extended Price’]:
if i > 0
return total_sales += i

Hello @micro4195945409, welcome to the forums. In Python, you shouldn’t store loops to variables (and unlike JS, PHP, Ruby, etc, there aren’t ternary operators). Therefore you should probably use a function like this:

def total_sales_logic():
  total_sales = 0
  for i in cust_rep["Extended Price"]:#I am assuming that cust_rep is a dictionary and the value for "Extended price is a string
    if i > 0:
       return total_sales += 1 

You can then store the return of a function in a variable, like this:

total_sales_logic = total_sales()

However, there could be a problem with this:

If the vale for ‘Extended Price’ is an integer, the loop won’t work because you can’t loop through an int type.

Looping with int

You can loop using int type in some ways, using range()

for i in range(int1, int2):

The fn worked! Thanks for taking the time to help codeneutrino!

1 Like

There is the concept of a conditional expression in Python, which provides the same functionality as a ternary operator:

>>> a = 5
>>> b = 6
>>> c = a ** 2 if a < 4 else a ** b
>>> print(c)
>>> 5 ** 6

An arbitrary example, for demonstration purposes. :slight_smile:

1 Like

Oh, thanks! I didn’t know that!

hi all…another follow up question.

How do you iterate through a column that is a float? i tried looking online, but wasn’t able to find anything really.

Would you have to convert the dtype from float to int, iterate, then convert back to float?

Sorry, I don’t quite understand what you mean by column? Do you mean list?

Only happened acorss this one recently myself on the tail end of a stackoverflow response. It’s pretty handy when performing certain list comprehensions, e.g.

[x if x >= 0 else -x for x in range(-10, 11)]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]