when you coding, many times you need repeat to do same or similar things again and again. You could use copy and paste to repeat the code.
But that's bad code example, because you could you loop and tell computer how many time you need repeat.
Below is the example to print "Hello World" 100 time.
for x in range(100):
print("Hello World!")
The variable x
could be print with str(x)
.
for x in range(100):
print("Hello World!" +str(x))
In python, the x is start fom 0, and end with 99 in this example
To draw 4 circles like below
Below code will draw the 4 circles:
import turtle
t = turtle.Pen()
for x in range(4):
t.circle(100)
t.left(90)
- Please do it yourself, modify the code in 4.2.3 and change it to draw below 6 circles
Please practice below code, to see how to let user input the value.
import turtle, time
t = turtle.Pen()
t.speed(10)
# Ask the user for the number of circles in their rosette, default to 20
number_of_circles = int(turtle.numinput("Number of circles", "How many circles in your rosette?", 20))
for x in range(number_of_circles):
t.circle(100)
t.left(360/number_of_circles)
time.sleep(10)
A while loop statement is Python repeatedly executes a target statement as long as the given condition is true.
while expression:
statement(s)
Example:
i = 1
while i < 10 :
print(i)
i += 1
Please try below code yourself
The upper code will keep asking your name until you press enter without give any value.
Wile the break
statement , you could stop the loop event if the while condition is true.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
i = 1
while True:
print(i)
i += 1
if( i>10 ):
break
Use Continue statement will skip the remain lines of code and to next loop
The print "banana" will be skip in below code.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
The number 3 will not be print by below code.
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
If you never try put a loop inside a loop, you need try it.
import turtle,time
t = turtle.Pen()
t.speed(30)
for x in range(12):
for y in range(4):
t.circle(10)
t.left(90)
t.forward(50)
t.left(30)
time.sleep(10)