GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing opentechschool.github.io — Conditional Loops — Introduction to Programming with Python Conditional Loops¶Introduction¶Conditional loops are way to repeat something while a certain condition
is satisfied, or True. If the condition is always satisfied (never
becomes False), the loop can become infinite.
If the condition starts off false, the code in the loop will never run!
In Python conditional loops are defined with the word = '' sentence = '' print('Please enter some words.') print('Include a period (.) when you are finished.') while '.' not in word: word = input('next word: ') sentence = word + ' ' + sentence print() print('Aha! You said:') print(sentence) We call this part of the code the ‘conditional’: Whether the conditional return True or not determines whether the code inside
the Read the code above, and see if you can summarise in your head what it what it do (what its final output will be). Then copy it into a file, say Note If you are using Python 2, you will need to replace Turtle prison¶Exercise¶The turtle has been up to its usual tricks again, robbing liquor stores and building up huge gambling debts. It’s time for turtle to be put into a cell that it can’t get out of. Let’s make a new version of
You could try playing with a turtle in the interpreter and using these functions to check exactly what they do, if you like. Now you will need to implement the prison logic using these turtle
functions, perhaps a Solution¶def forward(distance): while distance > 0: if turtle.distance(0,0) > 100: angle = turtle.towards(0,0) turtle.setheading(angle) turtle.forward(1) distance = distance - 1 Draw a spiral¶Loops can be interrupted with the Exercise¶Write a To do this you will need the Note To draw a spiral, the turtle has to rotate by a constant value and move forward by an increasing value. Solution¶def draw_spiral(radius): original_xcor = turtle.xcor() original_ycor = turtle.ycor() speed = 1 while True: turtle.forward(speed) turtle.left(10) speed += 0.1 if turtle.distance(original_xcor, original_ycor) > radius: break Bonus¶Can you make a conditional for this loop, so you don’t need the
infinite loop |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |