Monday, January 4, 2016
#PythonTuesday #Coding --- Break the Loop...
Just my simple example to illustrate the difference between for loop and while loop in Python.
# for loop
ingredients = ["Cheese", "Herbs", "Tomato", "Garlic", "Eggs"]
for x in ingredients:
print x
# while loop with the same ingredients…
mylist = [ ]
mylist.append("Cheese")
mylist.append("Herbs")
mylist.append("Tomato")
mylist.append("Garlic")
mylist.append("Eggs")
while True:
print(mylist)
if mylist[3] == "Garlic": #check if item 3 (mylist[3]) is Garlic or not.
break
#We are able to exit from this while loop because this condition is true. We have defined the item 3 as "Garlic"--- append starts from 0. We can break this while loop and system will only print mylist once...
#If we change this if statement, the result will be different:
while True:
print(mylist)
if mylist[3] == "Cheese": #This time we check if the item 3 is Cheese or not.
break
#Only under the condition that item 3 is Cheese, then we are able to break this while loop. Now the boolean condition didn't yield true 'cause obviously item 3 is Garlic. So the system will print mylist forever...
###################################################
Back to the CodeCombat game --- At the level of “The Second Kithmaze”, our goals include:
• Your hero must survive.
• Navigate the maze.
• Under 6 statements.
With ‘’while loop”, we can easily navigate the maze as following:
while True:
self.moveRight()
self.moveUp()
self.moveRight()
self.moveDown()
Screenshot of "The Second Kithmaze":
At the level of “Dread Door”, a while loop is used to attack the door:
• Destroy the door.
• Under 3 statements.
Code:
while True:
self.attack(“Door”)
Under this while loop, our hero will keep kicking the door. We can imagine if her health point is less than 5 for example, then we can break this while loop and let her fall asleep right away…
Screenshot of "Dread Door":
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment