Python newbie here, running 2.7.
I am trying to create a program that uses a function to generate text, and then outputs the function-generated text to a file.
When just printing the function in powershell (like this: http://codepad.org/KftHaO6x), it iterates, as I want it to:
def writecode (q, a, b, c):
while b < q:
b = b + 1
print "v%d_%d_%d = pairwise (caps[%d],sals[%d],poss[%d],poss[%d],poss[%d],pos_range)" %(a,b,c,a,a,a,b,c)
print "votes%d_%d.append(v%d_%d_%d)" % (b,c,a,b,c,)
print "v%d_%d_%d = pairwise (caps[%d],sals[%d],poss[%d],poss[%d],poss[%d],pos_range)" %(a,c,b,a,a,a,c,b)
print "votes%d_%d.append(v%d_%d_%d)" % (c,b,a,c,b)
writecode (5,1,0,4)
When trying to output the function into a file (like this: http://codepad.org/8GJpp9QY), it only gives 1 value, i.e. does not iterate:
def writecode (q, a, b, c):
while b < q:
b = b + 1
data_to_write = "v%d_%d_%d = pairwise (caps[%d],sals[%d],poss[%d],poss[%d],poss[%d],pos_range)" %(a,b,c,a,a,a,b,c)
data_to_write_two = "votes%d_%d.append(v%d_%d_%d)" % (b,c,a,b,c,)
data_to_write_three = "v%d_%d_%d = pairwise (caps[%d],sals[%d],poss[%d],poss[%d],poss[%d],pos_range)" %(a,c,b,a,a,a,c,b)
data_to_write_four = "votes%d_%d.append(v%d_%d_%d)" % (c,b,a,c,b)
return data_to_write
return data_to_write_two
return data_to_write_three
return data_to_write_four
x = writecode (5,1,0,4)
out_file = open("code.txt", "a")
out_file.write(x)
out_file.close()
Why is this, and how can I make the output function iterate (like it does with print)?
In the version you’re using to write the file, the function returns (via the first
returnstatement) after the first iteration of thewhileloop. Based on what you have you might want something like this:Which works by accumulating each line of output into a list and then returns the single string with all the results joined together with newlines and a trailing newline.