I'm a student in python and have an assignment that requires me to write code without using pandas. I need to assign a print statement to a variable, and I'd like to include a for loop so that it's dynamic.
For now, I've hard-coded the number of print statements, and that's good enough for the assignment, but I'd like to know for future reference if there's some way to put a for loop into a variable.
What I've done (and this works fine since I know how many print statements I need):
x = (
f"{names[i]} : {percent[i]}% ({votes[i]})"\n
f"{names[i]} : {percent[i]}% ({votes[i]})"\n
f"{names[i]} : {percent[i]}% ({votes[i]})"\n
)
print(x)
What I could do so that I don't need to know the end of the range in advance:
for i in range(0,len(candidates)):
print(f"{names[i]} : {percent[i]}% ({votes[i]})")
This second piece of code works beautifully so long as I don't assign it to a variable. The problem is that I'm required to assign it to a variable.
When I do this:
x = for i in range(0,len(candidates)):
print(f"{names[i]} : {percent[i]}% ({votes[i]})")
print(x)
I get:
SyntaxError: invalid syntax
pointing to the line saying for i in range(0,len(candidates)):
I assume this means I can't assign a for loop to a variable. Is there a work-around that would let me do it?