0

everyone. I am a beginner in Python and I have a question about what words can follow keywords 'for in' in Python?

For example, I define 3 functions here.

def showallwords(wordlist):
    for word in wordlist:
        print(word)

def showallwordsinline(wordlist):
    for line in wordlist:
        print(line)

def printcorrectletters():
    x=-1
    for letters in correctanswer:
        for letters2 in userinput:
            if letters == letters2:
                x = x+1
                break         
    return x

I can put word, line and letter after 'for'. So, these functions have different meaning. Therefore, what kind of or what words can follow 'for' here? Thanks a lot!

Juergen
  • 12,378
  • 7
  • 39
  • 55
Guanfang Dong
  • 333
  • 2
  • 13
  • Why do you think the functions have different meanings dependent on the "word" (variable name) that you put after `for`? The first two for-loops do exactly the same. –  Sep 21 '15 at 02:02

4 Answers4

1

After a for keyword the name of a variable or a list of variable names can follow.

These name or names are the variables that get the successive values assigned which the for loop is looping over.

For example:

for val in range(10):
    print val

val is the name of a variable and gets all the values assigned, that "range(10)" produces. In this case, range(10) produces successive the integers 0 ... 10.

The names of the variable you can choose yourself. You can also choose

for banana_ice in range(10):
    print banana_ice

But of course it makes more sense, to use names that fit into your domain and the usage of the variable.

The list of variables option is already an advanced feature that you can ignore for the beginning. Basically it is similar as the tuple/list unpacking feature, that you have at assignments:

a, b, c = (1, 2, 3)
# will assign a=1, b=2, c=3
Juergen
  • 12,378
  • 7
  • 39
  • 55
1

Take a look at the Python docs for 2.x and 3.x: they call it a target list which, too, is defined there.

Jens
  • 8,423
  • 9
  • 58
  • 78
0

A name or sequence of names.

>>> for (x, y) in ((1, 2), (3, 4)):
...   print x
...   print y
... 
1
2
3
4
Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

in lists also you can use the "for" like follows:

 list=['movies', 'music', 'photos']
 for i in list:
     print i

the output will be:

 movies
 music
 photos

NOTE: in python we do not declare variables, just set a name for your variable and you're good to go

Hamza Boughraira
  • 75
  • 2
  • 2
  • 7