Python - Else Clauses on Loops
** Else Clauses on Loops
==========================================
my_list = [1, 2, 3, 4, 5]
for i in my_list:
print(i)
else:
print("Hit the For/Else Statement!")
---------------------------------
1
2
3
4
5
Hit the For/Else Statement!
---------------------------------
==========================================
num = 3
if num < 2 :
print("num is less than 2!")
else:
print("num is not less than 2!")
---------------------------------
num is not less than 2!
---------------------------------
==========================================
my_list = [1, 2, 3, 4, 5]
for i in my_list:
print(i)
if i == 3:
break
else:
print("Hit the For/Else Statement!")
---------------------------------
1
2
3
---------------------------------
==========================================
my_list = [1, 2, 3, 4, 5]
for i in my_list:
print(i)
if i == 6:
break
else:
print("Hit the For/Else Statement!")
---------------------------------
1
2
3
4
5
Hit the For/Else Statement!
---------------------------------
==========================================
i = 1
while i <= 5:
print(i)
i += 1
# if i == 3:
# break
else:
print('Hit the While/Else Statement!')
---------------------------------
1
2
3
4
5
Hit the While/Else Statement!
---------------------------------
==========================================
i = 1
while i <= 5:
print(i)
i += 1
if i == 3:
break
else:
print('Hit the While/Else Statement!')
---------------------------------
1
2
---------------------------------
==========================================
def find_index(to_search, target):
for i, value in enumerate(to_search):
if value == target:
break
else:
return -1
return i
my_list = ['HAN', 'Rick', 'John']
index_location = find_index(my_list, 'Steve')
print('Location of target is index: {}'.format(index_location))
---------------------------------
Location of target is index: -1
---------------------------------
==========================================
def find_index(to_search, target):
for i, value in enumerate(to_search):
if value == target:
break
else:
return -1
return i
my_list = ['HAN', 'Rick', 'John']
index_location = find_index(my_list, 'HAN')
print('Location of target is index: {}'.format(index_location))
---------------------------------
Location of target is index: 0
---------------------------------