简体   繁体   中英

How to make a For loop without using the In keyword in Python

I was just wondering how I could go about using a For loop without using the "in" keyword in Python?

Since the "in" keyword tests to see if a value is in a list, returning True if the value is in the list and False if the value is not in the list, it seems confusing that a For loop uses the In keyword as well when it could just as well use a word like "of" instead.

However, I tried to use a code like this:

    for i of range(5):
        print i

It returns a syntax error. So I was wondering if there was any way I could use a For loop without also using the In keyword since it is confusing.

No. There is not, it's a part of the language and can't be changed (without modifying the underlying language implementation).

I would argue that it's not confusing at all, as the syntax reads like English, and parses fine as an LL(1) grammar. It also reduces the number of keywords (which is good as it frees up more words for variable naming).

A lot of languages reuse keywords in different contexts, Python does it with as to:

import bar as b

with foo() as f:
    ...

3.3 does it with from too:

from foo import bar

def baz(iter):
    yield from iter 

Even Java does this, extends is usually used to give the base class for a class, but it's also used to specify an upper bound on a type for generics.

class Foo extends Bar {
    void baz(List<? extends Bar> barList) {
        ...
    }
}

Note that even if this was possible, it would be a bad idea, as it would reduce readability for other Python programmers used to the language as it stands.

Edit:

As other answers have given replacements for the for loop using while instead, I'll add in the best way of doing a bad thing:

iterable = iter(some_data)
while True:
    try:
        value = next(iterable)
    except StopIteration:
        break
    do_something(value)

No, although you could use a while loop instead:

some_list = range(5)
while some_list:
    print some_list.pop()

Personally I don't understand why it's unclear though, ever heard of Homonyms? http://en.wikipedia.org/wiki/Homonym

You could do something like that:

iter = len(list)
loop = True
while loop:
  if iter == 0:
    loop = False
  else:
    do_something(list[iter])
    iter =- 1
return 0

Stupid, but doable ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM