0

Basically, this is what I am trying to do. I have an CSV file that I read in using Python 3. So, here is the basic layout of the rows:

Row1: On
Row2: <empty>
Row3: <empty>
Row4: On
Row5: On
Row6: <empty>
Row7: Off
Row8: <empty>

The code to access this would be:

for row in file:
     var = row[0]
     print(var)

The output I would like to see for each line after running the script would be:

for row in file:
     print(var)

On
On
On
On
On
On
Off
Off

I am not sure how to do it, but I am trying to keep track of the variable as the program moves through the for loop. Here is the logic:

for loop:
  1.  If row[0] has the string 'On', then assign 'On' to var
  2.  If the next row[0] is empty, then I want the var to retain the previous value of 'On'.
  3.  Var will not change from 'On' until row[0] has a different value such as 'Off'.  Then, Var will be assigned 'Off'.

Hopefully this question makes sense. I am not sure how to do this in Python 3.

2
  • What do you mean when you say a row is empty? A blank line? Commas with no values between them? Empty strings? Commented Nov 1, 2015 at 0:33
  • 2
    So just declare var = None outside the loop? Then, if row != "": var = row? Or am I missing something? Commented Nov 1, 2015 at 0:33

2 Answers 2

1
# set an initial value for `var`
var = None
for row in file:
    # `row` should now contain the text content of a line
    if row:
        # if the string is not empty
        # set var to the value of the string
        var = row
    # print the value of var
    print(var)

In Python, empty strings are "falsey" while non-empty strings are "truthy". By using the statement if row: we would only proceed into the if statement when row contains non-empty strings, such as "On", or "Off".

Sign up to request clarification or add additional context in comments.

Comments

0

A simple if/else will do

var = some_initial_value
for row in file:
     var = row[0] if row[0] else var
     print(var)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.