简体   繁体   中英

How do I continue a for loop without going to the next index? - Python

is there any way to continue a for loop without going to the next index?

Example:

for player in range(players):
    name = input("what is your name? ").lower()
    if name == "john cena":
        print("Hey! That's not your real name!")
        [some keyword or function that allows the magic to happen]
    elif name == "donald trump":
        print("Hi Mr. President!")
        [the same keyword or function that allows the magic to happen]

    player_names.append(name)

Shell:

============ RESTART =========

what is your name? luke
what is your name? john cena
Hey! That's not your real name!
what is your name? donald trump
Hi Mr. President!
what is your name? mickey mouse
what is your name? nobody
>>> player_names
["luke", "mickey mouse", "nobody"]

A for loop is intended to allow you to iterate over each element once, without having to worry about how to actually move to the next index.

for each player:
   # do something

If you require more control over when, or if, you would like to move to the next index, you can use a while loop.

while (some_condition_is_true):
   # do something

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