module2_python
module2_python
Learning Objectives:
1. Understand the structure of the for and while loops and the difference between iterate over index vs.
element. Recognize the effects of break and continue keywords.
2. Construct new functions and make function calls. Understanding the role of parameter.
2.1: Loops
Python has one implementation/structure of the FOR loop that works for both the regular for loop and the
forEach loop from other programming languages.
There are a few structural differences for the Python FOR loop. Consider them in the examples below.
In [ ]: """
The variable i serves as the counter over the RANGE of [0,10),
inclusive of lower but exclusive of upper bound.
Also by default, if there does NOT exists a third parameter for range(),
then i increments by 1.
"""
for i in range(10):
print(i)
0
1
2
3
4
5
6
7
8
9
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 1/11
27/12/2024, 16:38 module2_python
In [ ]: """
This examples specifies a lower bound that differs from the default value o
f 0.
9
9
9
9
9
9
9
9
In [ ]: """
The third parameter in range() defines the number of steps to increment the
counter.
0
3
6
9
In [ ]: """
forEeach loop over the each character in a string.
for i in "hello!":
print(i)
h
e
l
l
o
!
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 2/11
27/12/2024, 16:38 module2_python
In [ ]: """
We could also iterate over the string by index.
Consider the following example that iterates over the string by index,
starting at index 0 and ending at the last element, with the counter increm
ents by 2,
so ONLY printing every other element in the string.
"""
0th letter is h
2th letter is l
4th letter is o
6th letter is w
8th letter is r
10th letter is d
The structure of the WHILE loop remains mostly identical to other programming languages.
In [ ]: # Note: without updating the variable in the while loop, this will be an IN
FINITE loop!!
count = 0
while (count < 10):
print(count)
0
1
2
3
4
5
6
7
8
9
Break: skip the remaining codes in the loop and the remanining iterations, break out of the innnermost
loop.
Continue : skip the remaining codes in the loop and continue to the next iteration of the loop
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 3/11
27/12/2024, 16:38 module2_python
In [ ]: # Consider a program that echos the user input, except for "end"
# This program runs infinity, except when the user input "end" to terminate
it
while True:
user = input("Enter something to be repeated: ")
end = False
while end == False:
user = input("Enter something to be repeated: ")
if user=="end":
print("Program Ended!!!")
end = True
else:
print(user)
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 4/11
27/12/2024, 16:38 module2_python
In [ ]: """
Let's consider a loop that counts from 1-20, but skip all numbers that are
mulitple of 5.
In this case, we could NOT use the break keyword, because that will termina
te the loop.
We want to "continue" the loop except for a few numbers.
count = 1
1
2
3
4
SKIP
6
7
8
9
SKIP
11
12
13
14
SKIP
16
17
18
19
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 5/11
27/12/2024, 16:38 module2_python
1
2
3
4
SKIP
6
7
8
9
SKIP
11
12
13
14
SKIP
16
17
18
19
2.2: Functions
Functions are useful when you are given a problem that could be broken down into multiple steps and some
steps are used repetitively. Then, having a function for those steps are convenient because it reduces code
repetition and makes code more organized.
1. Define/initialize a new function with the def keyword before the function name
2. Do NO define the return type in the function declaration.
3. Do NOT forget about the function parameter if your function needs information from the main() or other
functions.
4. RETURN statement is NOT required, depending on the functions.
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 6/11
27/12/2024, 16:38 module2_python
In [ ]: """
We will write our own function that tests whether a traingle of 3 sides is
a right triangle.
Since we could not control the order the sides that user gives us (such tha
t c is the longest length),
we need to need to manually check if c is the longest length (length a and
b can be any order).
Otherwise, our Pythagorean Theorem will failed.
"""
# tmp stores the previous c values, that's not the longest length
tmp = c
c = max(a,b,c)
if a == c:
a = tmp
elif b == c:
b = tmp
# If the program sees a return statement, this is the END of the progra
m/function
return True
# These two lines will ONLY run when the IF condition is false
print("NOT a right triangle")
return False
if __name__ == "__main__":
main()
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 7/11
27/12/2024, 16:38 module2_python
In [ ]: """
Another example: determine if the user input is a palindrome.
# Since we could not control what user enters for the sentence, let's san
itize the sentence first.
# We will remove all punctuations and white spaces from the sentence, mak
e all letters lowercase
exclude = set(string.punctuation)
str = ''.join(ch for ch in str if ch not in exclude)
str = str.replace(" ", "").lower()
# Check if the string is the same in reversed order as the original order
if str == str[::-1]:
return True
else:
return False
if (isPalindrome(userSentence)):
print(userSentence + " is a palindrome!")
else:
print(userSentence + " is NOT a palindrome!")
if __name__ == "__main__":
main()
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 8/11
27/12/2024, 16:38 module2_python
import string
def isPalindrome(str):
exclude = set(string.punctuation)
str = ''.join(ch for ch in str if ch not in exclude)
str = str.replace(" ", "").lower()
if str == str[::-1]:
return str + " is a palindrome!"
else:
return str + " is NOT a palindrome!"
def main():
userSentence = input("Enter a sentence to be tested as a palindrome:")
print(isPalindrome(userSentence))
if __name__ == "__main__":
main()
In [ ]: """
Above we worked through an example that test whether a sentence is a palind
rome.
Now it's your turn.
def isPalindrome(str):
if (isPalindrome(userInput)):
print(userInput + " is a palindrome!")
else:
print(userInput + " is NOT a palindrome!")
if __name__ == "__main__":
main()
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 9/11
27/12/2024, 16:38 module2_python
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 10/11
27/12/2024, 16:38 module2_python
def isPalindrome(str):
str = str.lower()
if (str == str[::-1]):
return True
else:
return False
if (isPalindrome(userInput)):
print(userInput + " is a palindrome!")
else:
print(userInput + " is NOT a palindrome!")
if __name__ == "__main__":
main()
In [ ]:
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 11/11