You are on page 1of 28

Python Loops

ITERATION
• Looping, repeating code.

• A fixed number of times (FOR LOOP)


• Whilst a condition remains true (WHILE LOOP)
FOR LOOPS
for iterating_var in sequence:
statements(s)

e.g.

for x in range(1,10):
print (x)
What will this print?
FOR LOOP Continued
name="Barry"
for y in name:
print(y)

What’s going to happen here?


Why does it work?
Why t works
Looping through a list?
chaps = ["Allen","Bill","Charlie"]
for boy in chaps:
print(boy)

What’s going to happen?


Nested Loops
• We can place one loop inside another (nesting).
• Consider this example:
chaps = ["Allen","Bill","Charlie"]
for boy in chaps:
print(boy)
for letter in boy:
print (letter)
WHILE LOOPS
while expression:
statement(s)

e.g.
EXAMPLE
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"


Adding an ELSE to a LOOP
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
Common Questions

What's the difference between a for-loop and a while-loop?


A for-loop can only iterate (loop) "over" collections of things. A while-loop can do any kind of iteration (looping) you want.
However, while-loops are harder to get right and you normally can get many things done with for-loops.
Loops are hard. How do I figure them out?
The main reason people don't understand loops is because they can't follow the "jumping"
that the code does. When a loop runs, it goes through its block of code, and at the end it jumps back
to the top. To visualize this, put print statements all over the loop printing out where in the loop Python
is running and what the variables are set to at those points. Write
print lines before the loop, at the top of the loop, in the middle, and at the bottom. Study the output and try to understand
the jumping that's going on.
Putting it all together. . .
This is clever.

clubs = [["minecraft","geek","nerd"],["rugger","jock",""],["drama","board-
creeper","luvvie"]]
for club in clubs:
print (club)
print ("the club name is " + club[0])
print len(club)
for members in club[1:]:
print (members)
SUBROUTINES CAN BE EITHER
PROCEDURES & FUNCTIONS
Both of these are examples of SUBROUTINES.

What does the term sub-plot mean?

A subroutine is a named block of code which we can use (CALL) from


our main program. Once finished it hands control back to the next line
of our main program.
subroutines

prcedures functions
MAIN PROGRAM

Instruction 1 SUB Blah


Sub’s instruction 1

Instruction 2 Sub’s instruction 2

Sub’s instruction 3
Blah
Sub’s instruction 4

Instruction 3 Sub’s instruction 5

Instruction 4
Procedure example
def welcome():
#simple procedure that prints a welcome message.
print("Welcome to my program")

def main():
welcome()

if __name__ == '__main__':
main()
def welcome():
#simple procedure that prints a welcome message. Procedures
print("Welcome to my program")
def myStarter():
print("Fresh Gazpacho")
def myMain():
print("Homemade Pasta and fresh Green Pesto")
def myPudding():
print("Lemon Cheesecake")
def main():
welcome()
myStarter()
myMain()
myPudding()
if __name__ == '__main__':

main()
Let’s have an argument
All subroutines can be provided with one or more arguments. These are
parameters which are provided to the subroutine when it’s used (CALLED)

def theBest(nameOfPerson):
print ("OMG " + nameOfPerson + " is just the best person in the world")
def main():
theBest("Tom")
if __name__ == '__main__':
main()
We can use multiple arguments
def loves(name1,name2):
print ("OMG "+ name1 + " is crushing so hard on "+ name2 + " it's almost
stalking")

def main():
loves("Miss Higginson", "Mr Bailey")
if __name__ == '__main__':
main()
Arguments can be other data types.
def doTheSquare(n1):
print (str(n1) + " squared is " + str(n1*n1))
#note that I've had to cast the integers to strings as
#you can't join with + a mix of integers and strings

def main():
doTheSquare(5)
if __name__ == '__main__':
main()
How do functions differ from procedures?
• The key point is that a function returns a value. This seems really
simple – but it’s actually got quite big implications.
• When a function is called, it’s evaluated and replaced by it’s return
value.
• Let’s look at some examples.
def returnBigger (n1,n2):
if n1>n2:
return n1
else:
return n2

def main():
print (returnBigger(7,9))

if __name__ == '__main__':
main()
def checkPalinfrom(wordToCheck):

Palindrome Checker
reversedWord = wordToCheck[::-1]
if wordToCheck==reversedWord:
return True
else:
return False

def main():
print (checkPalinfrom("madam"))

chosenWord=""
while chosenWord <> "q":
chosenWord=raw_input("enter a word to check or q to quit")
print(checkPalinfrom(chosenWord))
print ("all finished")

if __name__ == '__main__':
main()
Variable
Scope
Variable
Scope

local global
person="barry"
This BREAKS
def main():
print person
someSub

def someSub:
print person
if __name__ == '__main__':
main()
names=[]
Global Variables
def main():
global names
userInput = ""
while userInput <> "q":
userInput = raw_input("enter a name to add to the list or q to quit
and print the list")
names.append(userInput)
print names

if __name__ == '__main__':
main()

You might also like