-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14_for_else_loop.py
More file actions
55 lines (50 loc) · 1.89 KB
/
Copy path14_for_else_loop.py
File metadata and controls
55 lines (50 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#======================================================================================
# FOR ELSE LOOP
#--------------------------------------------------------------------------------------
# In python, a for loop can have an else block.
# Use else with loops only when there's a break.
# The else part runs only if the loop finishes normally.
# The else part does not run if the loop is stopped by a break
#=====================================================================================
items = [ 1, 3, 4, 7, 9]
for i in items:
print(i)
else:
print("Loop completed successfully")
items = [ 1, 3, 4, 7, 9]
for i in items:
if i % 2 == 0:
print("Even number found",i)
break
else:
print("All numbers are odd")
#--------------------------------------------------------------------------------------
# Real world use cases
#--------------------------------------------------------------------------------------
# check for missing names in a list
names = ["jack", "grace", "alex", None, "jane"]
for name in names:
if name is None:
print("Found a missing name")
break
else:
print("All names are available")
# check if all files are csv files
files = ["sales.csv", "customers.csv", "employees.csv", "report.csv"]
for file in files:
if not file.endswith(".csv"):
print("Not all files are csv files")
break
else:
print("All files are csv")
#--------------------------------------------------------------------------------------
# python challenge
#--------------------------------------------------------------------------------------
# check whether any filename appears more than once
file_list = [ "report.csv", "data.xlsx", "summary.docx", "report.csv", "data.csv"]
for file in file_list:
if file_list.count(file) > 1:
print("Duplicate file found")
break
else:
print("All files are unique")