Loops Flashcards
For and While Loops
Loops
Loops are used to run a specific instruction or a set of instructions to execute again and again until certain condition is met
Analogy
Imagine a kid sitting in a car. The kid will keep asking ‘When will we reach’ again and again until we reach home. So, ‘reaching home’ is the constraint here and the kid asking ‘When will we reach’ is performed in a loop until the constraint is met
For loop - Basic Syntax
syntax:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Every for loop starts at 0 unless specified and goes on until one number before the specified number in the range
For loop - Specific start and end range
for i in range(5,10):
print(i)
Output:
5
6
7
8
9
For loop - Start, Stop, Step
for i in range(0,10,2):
print(i)
Output:
0
2
4
6
8
While loop
For loop - Domestic Loop (iterator is controlled by the code)
While Loop - Wild Loop! We have to take care of the loop
While Loop
timer = 5
while timer != 0:
print(timer)
timer = timer - 1
Output:
5
4
3
2
1
Trivia Time!
timer = 10
while timer != 10:
print(timer)
Infinite number of 10s!
Since we are not updating the condition/iterator - timer
Trivia Time!
timer = 10
while timer == 11:
print(timer)
timer = timer - 1
Nothing will be printed because the entry ticket to enter the while door is that the timer has to be 10.
Since that condition is not met, the while loop is not executed.
Practice 1
Write a python code to print N numbers (1 to N included) using for-loop. Get the value for N from the user
n = input(‘Enter N: ‘)
for i in range (1,N+1):
print(i)
Practice 2
Calculate the sum of first N numbers
n = input(‘Enter N: ‘)
total = 0
for i in range(1,N+1):
total = total + i
Iterating through an array
Elements of an array are called through their index numbers.
For example, the elements of the array vegetables = […] are referenced as vegetable[1], vegetable[2], etc…
vegetables = [‘carrot’, ‘beans’, ‘beetroot’, ‘pumpkin’, ‘broccoli’, ‘radish’]
length = len(vegetables)
for i in range(length):
print(vegetables[i])
Question: Counting vowels and consonants in a string
Hint: A string is also considered as an array and can be referenced using index
name = ‘gnanambhal shivarraman’
vowels = 0
consonants = 0
length = len(name)
for i in range(length):
if name[i] == ‘a’ or name[i] == ‘e’ or name[i] == ‘i’ or name[i] == ‘o’ or name[i] == ‘u’:
vowels = vowels + 1
else if name[i] == ‘ ‘:
continue
else:
consonants = consonants + 1
print(vowels)
print(consonants)