![]() |
This article has links to websites or programs outside of Scratch and Wikimedia projects (such as Wikipedia). Remember to stay safe while using the internet as we cannot guarantee the safety of other websites. |
In both Python and Scratch there are loops. Loops are used to make code run multiple times. There are many different types of loops in both Scratch and Python.
Repeat () Loop
The repeat () block is a loop block that makes the code inside it repeat a certain number of times. This can be created using a for loop in Python. Here's an example of how a project can be made that says "Hello World" ten times.
for i in range(10):
print("Hello World")
when green flag clicked repeat [10] say [Hello World]
Repeat Until () Loop
The Repeat Until () block is a loop block that makes the code inside it repeat until a boolean value is true. Just like the Repeat () block, this can also be created using a while loop in Python. Here's an example of how a project that says "Hello World" until the variable stop is set to 1 could be created:
stop = 0
while not stop == 1:
print("Hello World")
when green flag clicked set [stop v] to [0] repeat until <(stop) = [1]> say [Hello World]
Forever Loop
The Forever block is a loop block that repeats the code inside it forever. Like the Repeat () and Repeat Until () block, this can be created using a while loop in Python. Below is an example of how a project that says "Hello World" forever can be created:
while True:
print("Hello World")
when green flag clicked forever say [Hello World]
Python For Loop
Along with while loops, in Python there are also for loops. For loops are used to iterate through a sequence.[1] Here's an example of a for loop that says each item in a list in Python and how it can be made in Scratch:
colors = ["red", "orange", "yellow", "green", "blue"]
for i in colors:
print(i)
when green flag clicked set [i v] to [1] repeat until <(i) \> (length of [colors v])> say (item (i) of [colors v]) change [i v] by [1]
References
- ↑ https://www.w3schools.com/python/python_for_loops.asp, about for loops