Skip to content

Latest commit

 

History

History
249 lines (169 loc) · 5.43 KB

File metadata and controls

249 lines (169 loc) · 5.43 KB

4 Loop

4.1 What is Loop

when you coding, many times you need repeat to do same or similar things again and again. copypatest You could use copy and paste to repeat the code. repeat

But that's bad code example, because you could you loop and tell computer how many time you need repeat.

4.2 For Loop

4.2.1 Print "Hello World" 100 times

Below is the example to print "Hello World" 100 time.

for x in range(100):
    print("Hello World!")

4.2.2 Use the variable in for loop

The variable x could be print with str(x).

for x in range(100):
    print("Hello World!" +str(x))

X In python, the x is start fom 0, and end with 99 in this example

x

4.2.3 Example: Draw 4 Circles

To draw 4 circles like below

draw circles

Below code will draw the 4 circles:

import turtle

t = turtle.Pen()

for x in range(4):
    t.circle(100)
    t.left(90)

4.2.4 Practice, draw 6 circles

  • Please do it yourself, modify the code in 4.2.3 and change it to draw below 6 circles

draw circles

  • Please try to use the x variable to draw 6 circle like below draw circles with variable

4.2.5 Advance, change variable with User input

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)

turtleinput

result

4.3 While Loop

4.3.1 While loop syntax

A while loop statement is Python repeatedly executes a target statement as long as the given condition is true.

while expression:
    statement(s)

Flow Diagram: diagram

Example:

i = 1
while i < 10 :
    print(i)
    i += 1

4.3.2 Try it: Ues While loop to Repeat Asking and Print your name

Please try below code yourself

04.3.2

The upper code will keep asking your name until you press enter without give any value.

4.4 Break statement of loop

Wile the break statement , you could stop the loop event if the while condition is true.

4.4.1 Break statement For loop example:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

4.4.2 Break statement While loop example:

i = 1
while True:
    print(i)
    i += 1
    if( i>10 ):
        break

4.5 Continue Statement

Use Continue statement will skip the remain lines of code and to next loop

4.5.1 Continue statement For loop example:

The print "banana" will be skip in below code.

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)

4.5.2 Continue statement While loop example:

The number 3 will not be print by below code.

i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

4.6 Double loop

If you never try put a loop inside a loop, you need try it.

doubleloop

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)

4.7 Loop practice

4.7.1 Use while and for loop , input and turtle together

# SpiralFamily.py - prints a colorful spiral of names
import turtle     # Set up turtle graphics
t = turtle.Pen()  
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green", "orange",  "purple", "white", "brown", "gray", "pink" ]
family = []       # Set up an empty list for family names

# Ask for the first name
name = turtle.textinput("My family","Enter a name, or just hit [ENTER] to end:")

# Keep asking for names
while name != "":
    # Add their name to the family list
    family.append(name)
    # Ask for another name, or end
    name = turtle.textinput("My family","Enter a name, or just hit [ENTER] to end:")

# Draw a spiral of the names on the screen
for x in range(100):
    t.pencolor(colors[x%len(family)]) # Rotate through the colors
    t.penup()                         # Don't draw the regular spiral lines
    t.forward(x*4)                    # Just move the turtle on the screen
    t.pendown()                       # Draw the next family member's name
    t.write(family[x%len(family)], font = ("Arial", int((x+4)/4), "bold") )
    t.left(360/len(family) + 2)         # Turn left for our spiral

You will got a image like below 04.7.1

4.7.2 Challenge

Could you modify the upper code to make a picture like below? 04.7.1

hint:

  • Change the previous script to change user input value to draw circle
  • Modify your script to change color
  • Modify your script to draw spiral of circles
  • No need exactly same just need get similar pattern

4.7.3 More Python Loop practices

For loop exercises online: https://holypython.com/intermediate-python-exercises/exercise-8-python-for-loop/

Go to Prev go to Next