简体   繁体   中英

Merge the code from 2 for-loops into 1 for-loop

I want to make my script as short as possible:

from turtle import *
for _ in range(10):
    lt(72)
    fd(71)
    rt(108)
    fd(71)
for _ in range(10):
    for s in [(29,90),(73,72),(73,90),(29,72)]:
        fd(s[0])
        rt(s[1])

As you can see, there are two for-loops are "for _ in range 10:".

Is there a way I could merge the two loops, and still get the same result?

You can put everything in a list, which will consume a bit more space:

for walk, turn in [(0,-72),(71,108),(71,0)]*10+[(29,90),(73,72),(73,90),(29,72)]*10:
    fd(walk)
    rt(turn)

If you only want one loop, try the following:

for i in range(20):
    if i < 10: 
       lt(72)
       fd(71)
       rt(108)
       fd(71)
    if i > 10: 
        for s in [(29,90),(73,72),(73,90),(29,72)]:
           fd(s[0])
           rt(s[1])

This looks a little unnecessary, but if you really really want to consolidate the two loops, you can try:

from turtle import *

mode1 = True
for i in range(20):
    if mode1:
        lt(72)
        fd(71)
        rt(108)
        fd(71)
        if i == 9:
            mode1 = False
    else: 
        for s in [(29,90),(73,72),(73,90),(29,72)]:
            fd(s[0])
            rt(s[1])

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