Loops
To perform repetative actions, we use loops. It performs iteration over the elements of sequences, such as lists, tuples, set, range, strings, and dictionaries.
for...in loop
syntax
python
# variable will hold first element of the sequence
# and will change next iteration
for <variable> in <sequence>:
# action with each element of the sequence
# variable will be created in global scope
# and will be accessible from the whole codeexample with list
python
my_list = [1, 2, 3, 4, 5]
# prints all elements of the list
for x in my_list:
print(x)example with tuple
python
my_tuple = (1, 2, 3, 'abc', True, False)
# prints all elements of the tuple
for x in my_tuple:
print(x)example with dictionary
prints all keys of the dictionary. also we can access value using the key.
python
my_guitar = {
'brand': 'Gibson',
'model': 'SG',
}
for x in my_guitar:
print(x, my_guitar[x])items() method return tuple of the key and value.
python
for item in my_guitar.items():
print(item)
# ('brand', 'Gibson')
# ('model', 'SG')we can also unpack the tuple
python
# key, value = item
for key, value in my_guitar.items():
print(key, value)example with set
prints all elements of the set
python
my_set = {1, 2, 3, 4, 5}
for x in my_set:
print(x)example with string
prints all characters of the string
python
my_string = 'Hello World'
for chr in my_string:
print(chr)example with range
prints all numbers from 0 to 9
python
for num in range(10):
print(num)while loop
we use condition to control the loop. The loop runs until the condition is False. Infinite loop can be created using while True.
syntax
python
while condition:
# actionexample
print all numbers from 1 to 9
python
num = 1
while num < 10:
print(num)
num += 1example with break
run infinite loop initially and break/exit the loop if the answer is yes.
python
while True:
answer = input('Do you want to stop? ')
if answer == 'yes':
breakexample with continue
number guessing game. continue skips the rest of the code in the loop and goes to the next iteration.
python
import random
random_num = random.randint(1, 10)
while True:
guess = int(input('Guess a number between 1 and 10: '))
if guess == random_num:
print('You got it!')
break
print('Wrong guess, Try again!')
continue