1

I've just completed Tatiana Tylosky's tutorial for Python and created my own Python pypet.

In her tutorial, she shows how to do a "for" loop consisting of:

cat = {
    'name': 'Fluffy',
    'hungry': True,
    'weight': 9.5,
    'age': 5,
    'photo': '(=^o.o^=)__',
}

mouse = {
    'name': 'Mouse',
    'age': 6,
    'weight': 1.5,
    'hungry': False,
    'photo': '<:3 )~~~~',
}

pets = [cat, mouse]    

def feed(pet):
    if pet['hungry'] == True:
        pet['hungry'] = False
        pet['weight'] = pet['weight'] + 1
    else:
        print 'The Pypet is not hungry!'

for pet in pets:
    feed(pet)
    print pet

I'd like to know how to repeat this "for" loop so that I feed both the cat and the mouse three times. Most of the Python guides I've read say that you have to do something like:

for i in range(0, 6):

In this case, however, the "for" loop uses the list "pets." So the above code can't be used? What should I do? I've tried some wacky-looking things like:

for pet in pets(1,4):
    feed(pet)
    print pet

Or:

for pet in range(1,4):
    feed(pet)
    print pet

Naturally it doesn't work. What should I do to get the "for" loop to repeat?

Hadoren
  • 165
  • 1
  • 2
  • 12

3 Answers3

1

I would enclose your feed for loop in a for loop that iterates three times. I would use something like:

for _ in range(3):
    for pet in pets:
        feed(pet)
        print pet

for _ in range(3) iterates three times. Note that I used _ because you are not using the iteration variable, see e.g. What is the purpose of the single underscore "_" variable in Python?

Community
  • 1
  • 1
intboolstring
  • 6,891
  • 5
  • 30
  • 44
0

Programming languages let you embed one structure in another. Put your current loop under a for loop that runs three times, as @intboolstring's answer already showed. Here are two more things you should do now:

  1. Don't compare against True. if pet["Hungry"] == True: is better written as

    if pet["Hungry"]:
        ...
    
  2. Switch to Python 3. Why are you learning an outdated version of the language?

alexis
  • 48,685
  • 16
  • 101
  • 161
  • I've made that change, thanks. I'm actually using Python 3, but I just copied the code from the tutorial in order to make things simpler. My own code is a bit more complicated (perhaps too much so). – Hadoren Jun 14 '16 at 14:50
0

If you don't want to use nested for loops you could also extend the pet list temporarily like this:

for pet in pets * 3:
    feed(pet)

that works because pet * 3 creates the following list: [cat, mouse, cat, mouse, cat, mouse]

If you need more control over the feeding order ( e.g. first feed all cats then all mice) the nested for loop approach might be better.

Wombatz
  • 4,958
  • 1
  • 26
  • 35