--Originally published at Quirino´s Projects
When we want to repeat some code n times, depending on a variable, or until a condition is met, we can use While and For loops
For
A for loop takes a data type, could be a string, a list, a dictionary, and basically every type of data that can be access by its elements, and runs n times were n is the number of elements of the list, and creates a variable each loop with each element
And example, we have a list
myList = [0,1,2,3,4]
And we want to print each element individually, in this case we use the for loop like this
for i in myList:
print (i)
Here the i in the first loop takes the value of 0, then gets printed, then takes the value of 1, then gets printed, and so on the i becomes the value of the index of the list
Here is an example of a program that eliminates spaces from strings
myString = input(“Give me a string: “)
newString =””
for i in myString:
if i != ” “:
newString += i
print (newString)
This program checks each character in the string, if the string is different that a blank space, is not added to the new string
While
A while loop is a loop that runs the code within forever until the condition given is evaluated to False
while True:
print(“I will be printed for ever”)
This is a not correct way of using loop, but serves to explain for While
n = 10
while n <100:
print (“Value of number is {0}”.format(n))
n -= 2