PYTHON: For Loops | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

PYTHON: For Loops

Hey guys, I am fairly new to python and have just completed the "For loops" lesson. However, I can't seem to get my head around it! Could someone please explain the following in *simple words*??? def print_nums(x): for i in range(x): print(i) return print_nums(10) I understand the function however am left wondering what is the I? I know it is a variable but how does this work in the range? Thanks in advance! 😁

25th Feb 2020, 9:58 PM
Cillian
Cillian - avatar
4 Answers
+ 2
The i is known as a dummy variable. It's role is to take on all the values in a list. Range creates a list from 0 to x. Thus i goes from 0 to x, one iteration at a time.
25th Feb 2020, 11:39 PM
Adam McGregor
+ 3
In this structure: for counter in iterable: pass values from iterable are copied into counter in each iteration. So here we have 0, 1, 2, ..., 10 for i during run.
25th Feb 2020, 10:13 PM
Qasem
+ 2
First of all, the "return" will make the loop stop when it is reached. So, that loop will only output "0". If I´m not mistaken, the var i is an integer. It is needed because the loop needs to keep count of the amount of iterations it has performed. def print_nums(x): // x will be the last integer, defined when you call the func for i in range(x): // i is a new integer, starting at 0. It will run until it reaches x print(i) // prints value of i. return // Ends the loop no matter the condition. Do not use unless you want to stop the loop. For example: def print_nums(x): for i in range(x): print(i) // I deleted "return" print_nums(3) Will output 0 1 2 It will not print 3, because by the time it reaches 3, the loop stops, and the print functions comes AFTER the condition check (for i in range (3))
25th Feb 2020, 10:16 PM
Fernando Pozzetti
Fernando Pozzetti - avatar
0
Thanks lads, think I understand it now!
26th Feb 2020, 6:33 AM
Cillian
Cillian - avatar