PurplProto
PurplProto

Reputation: 143

Can you initiate a variable while declaring a loop in Python?

so I'm playing around in Python to learn what you can and cannot do. Right now I'm trying to make a one line loop like so

while i <= 100: print(i); i += 1

but as you guessed, this doesn't work because I haven't initialised i. I then tried

i = 0; while i <= 100: print(i); i += 1

But that also fails stating invalid syntax "while".

Is there a way to initialise i on the same line?

Upvotes: 1

Views: 1570

Answers (1)

jgritty
jgritty

Reputation: 11935

Just use a for loop

for i in range(101): print(i)

Upvotes: 2

Related Questions