0% found this document useful (0 votes)
3 views

module2_python

This document covers Python programming concepts focusing on loops and functions, including the structure and usage of for and while loops, as well as the break and continue keywords. It also explains how to define and call functions, with examples demonstrating how to check for right triangles and palindromes. The document emphasizes the importance of functions in reducing code repetition and organizing code effectively.

Uploaded by

ed.paesdev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

module2_python

This document covers Python programming concepts focusing on loops and functions, including the structure and usage of for and while loops, as well as the break and continue keywords. It also explains how to define and call functions, with examples demonstrating how to check for right triangles and palindromes. The document emphasizes the importance of functions in reducing code repetition and organizing code effectively.

Uploaded by

ed.paesdev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

27/12/2024, 16:38 module2_python

Module 2: Loops, Functions

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

2.1.1: For/While 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.

The lower bound of 0 does NOT need to be specify;


it is implemented by default unless another lower bound is specified.

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.

The order of the parameter is ALWAYS:


1. Starting position, inclusive
2. Stopping position, exclusive
3. Incremental value

In this example, x starts at the value of 2 and stops at 9 inclusively, or


10 exclusive,
with x increments by 1 with each iteration.
"""
for x in range(2, 10):
print(i)

9
9
9
9
9
9
9
9

In [ ]: """
The third parameter in range() defines the number of steps to increment the
counter.

In this example, x starts at the value of 0 and stops at 9 inclusively, or


10 exclusive,
with x increments by 3 with each iteration.
"""

for i in range(0, 10, 3):


print(i)

0
3
6
9

In [ ]: """
forEeach loop over the each character in a string.

In this example, the variable 'i' represents every element/character of 'he


llo.'
"""

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.
"""

string = "hello world!"


for i in range(0, len(string), 2):
print(str(i) + "th letter is "+ string[i])

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.

Take a look at the example below

In [ ]: # Note: without updating the variable in the while loop, this will be an IN
FINITE loop!!

count = 0
while (count < 10):
print(count)

# IMPORTANT!!! Updating the counter!


count += 1

0
1
2
3
4
5
6
7
8
9

2.1.2: Continue/Break Keywords

How to maniputate loops (FOR and WHILE):

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: ")

## When break is triggered, the print() below will NOT run


## The program will break out of the loop when this keyword is read.
if user=="end":
print("Terminate the program!!!")
break
print(user)

Enter something to be repeated: a


a
Enter something to be repeated: g
g
Enter something to be repeated: end
Terminate the program!!!

In [ ]: # Without using the keyword "break," this is another implementation of the


same program from above using a variable.

end = False
while end == False:
user = input("Enter something to be repeated: ")
if user=="end":
print("Program Ended!!!")
end = True
else:
print(user)

Enter something to be repeated: a


a
Enter something to be repeated: f
f
Enter something to be repeated: h
h
Enter something to be repeated: d
d
Enter something to be repeated: end
Program Ended!!!

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.

We will implement this with both a while and a for loop.


"""

count = 1

# WHILE loop implementation


while count + 1 <= 20:
if count % 5 == 0:
print("SKIP")
count += 1
continue
print(count)
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

In [ ]: # FOR loop implementation

for i in range (1, 20):


if i % 5 == 0:
print("SKIP")
continue
print(i)

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.

Notes about defining a new function:

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.
"""

def isRightTriangle(a, b, c):

# Reassign variable values to ensure c is the longest length


if (max(a,b,c) != c):

# 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

# Apply the formula


if a**2 + b**2 == c**2:
print("Right Triangle")

# 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

# Prompt the user to enter 3 lengths


def main():
a = input("Enter the length for the first edge of the traingle:")
b = input("Enter the length for the second edge of the traingle:")
c = input("Enter the length for the last edge of the traingle:")

# User inputs are stored as a string, so we cast them to be int


return isRightTriangle(int(a), int(b), int(c))

if __name__ == "__main__":
main()

Enter the length for the first edge of the traingle:5


Enter the length for the second edge of the traingle:4
Enter the length for the last edge of the traingle:3
Right Triangle

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.

Palindrome: If a word/sentence is spelled the same way when it is reversed.


EX: racecar

For this example, let's make this more involved.


In stead checking if a word is a palindrome, we will test if a sentence is
a palindrome.

In order to write this program, we will set a few specifications:


- Treat capitalized letters as lowercase
- Ignore all white spaces and punctuations
- An empty sentence/string IS consider to be a palindrome.
"""

# import the string package


# We will go over packages/libraries more in Module 5
import string

# This implementation of the function RETURN a boolean value, True/False


def isPalindrome(str):

# 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()

# Compare the original string with the string in reversed order


# Notation of str[::-1]: first 2 numbers define the start and end of st
ring, last number of -1 means in reversed order

# Check if the string is the same in reversed order as the original order
if str == str[::-1]:
return True
else:
return False

# Prompt the user to enter the sentence


def main():
userSentence = input("Enter a sentence to be tested as a palindrome:")

if (isPalindrome(userSentence)):
print(userSentence + " is a palindrome!")
else:
print(userSentence + " is NOT a palindrome!")

if __name__ == "__main__":
main()

Enter a sentence to be tested as a palindrome:racecar


racecar is a palindrome!

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 8/11
27/12/2024, 16:38 module2_python

In [ ]: # Consider this implementation of the function that RETURN a string.


# Take note of the difference between the main() and isPalindrom() followin
g this change.

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()

Enter a sentence to be tested as a palindrome:hello


hello is NOT a palindrome!

In [ ]: """
Above we worked through an example that test whether a sentence is a palind
rome.
Now it's your turn.

Exercise: write a function to test if a word from the user is a palindrome.

Function declarations are provided for you.


"""

def isPalindrome(str):

# Prompt the user to enter the sentence


def main():
userInput = input("Enter a WORD to be tested as a palindrome:")

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

In [ ]: # One implementation of solution for above exercise.

def isPalindrome(str):
str = str.lower()
if (str == str[::-1]):
return True
else:
return False

# Prompt the user to enter the sentence


def main():
userInput = input("Enter a WORD to be tested as a palindrome:")

if (isPalindrome(userInput)):
print(userInput + " is a palindrome!")
else:
print(userInput + " is NOT a palindrome!")

if __name__ == "__main__":
main()

Enter a WORD to be tested as a palindrome:racecar


racecar is a palindrome!

In [ ]:

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 11/11

You might also like