Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Loop Examples
It's helpful to see a few of the ways we would want to use these concepts.
So, this bit of code here:
This is written out, verbatum, what is going on in loop logic
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
my_str = "My String!"
upper_case_count = 0
if my_str[0].isupper():
upper_case_count += 1
if my_str[1].isupper():
upper_case_count += 1
if my_str[2].isupper():
upper_case_count += 1
if my_str[3].isupper():
upper_case_count += 1
if my_str[4].isupper():
upper_case_count += 1
if my_str[5].isupper():
upper_case_count += 1
if my_str[6].isupper():
upper_case_count += 1
if my_str[7].isupper():
upper_case_count += 1
if my_str[8].isupper():
upper_case_count += 1
if my_str[9].isupper():
upper_case_count += 1
print(upper_case_count)
Enter to Rename, Shift+Enter to Preview
Can be simplified with using loops, like so:
Much more compact code
1
2
3
4
5
6
7
8
9
my_str = "My String!"
upper_case_count = 0
for char in my_str:
if char.isupper():
upper_case_count += 1
print(upper_case_count)
Enter to Rename, Shift+Enter to Preview
Another nifty thing you can accomplish with a bit of loop logic and Python keyword shortcuts:
This is some basic pattern matching
1
2
3
4
5
6
7
8
9
10
11
12
vowels = "aeiouAEIOU"
my_str = "This is my string!"
vowel_count = 0
for char in my_str:
if char in vowels:
vowel_count += 1
print(vowel_count)
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content