-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmoreLoops.py
64 lines (55 loc) · 1.64 KB
/
moreLoops.py
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
56
57
58
59
60
61
62
63
# A Definite Loop with Strings for example: for loop
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print('Happy New Year: ', friend)
print('Done')
# Finding the largest value
largest_so_far = -1
print('Before', largest_so_far)
for the_num in [9, 41, 12,3,74,15]:
if the_num > largest_so_far: # if-block
largest_so_far = the_num # end if-block
print(largest_so_far, the_num) # so it's printing this line every time in loops
print('After', largest_so_far)
# Finding the smallest number
smallest = None # None is None (special)type of data
print("Before:", smallest)
for itervar in [41, 12, 9, 74, 15]:
if smallest is None or itervar < smallest:
smallest = itervar
break # ""break" stop at first loop so it's never loop
print("Loop:", itervar, smallest)
print("Smallest:", smallest)
# Counting in a loop and adding in loops
count = 0
sum = 0
print('Before', count, sum)
for value in [9, 41, 12, 3, 74, 15]:
count += 1
sum = sum + value
print(count, sum, value)
print('After', count, sum, sum/count)
# Filtering in a loop
print('Before')
for value in [9, 41, 12, 3, 74, 15]:
if value > 20:
print('Large number', value)
print('After')
# Search Using a Boolean variable
found = False
print('Before', found)
for value in [9, 41, 12, 3, 74, 15]:
if value == 3:
found = True
print(found, value)
print('After', found)
# Looping through strings. the shorter code the better!!
fruit = 'banana'
for letter in fruit:
print(letter)
# using a While loop go thought a string
index = 0
while index < len(fruit):
letter = fruit[index]
print(index, letter)
index += 1