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 statements — Introduction to Programming with Python Conditional statements¶Introduction¶So far we have accomplished predefined tasks, but in all honesty we were accomplishing no better than old-time music boxes following one set of instructions to the end. What makes programming so much more powerful are conditional statements. This is the ability to test a variable against a value and act in one way if the condition is met by the variable or another way if not. They are also commonly called by programmers if statements. To know if a condition is True of False, we need a new type of data: the booleans. They allow logical operations. A logic statement or operation can be evaluated to be True or False. Our conditional statement can then be understood like this:
The condition can be anything that evaluates as True or
False. Comparisons always return True or False, for example
The else part is optional. If you leave it off, nothing will happen if the conditional evaluates to ‘False’. Examples¶Here are some examples. You may want to read them over line-by-line and see what you think they do, or run them to be certain: condition = True if condition: print("condition met") if not condition: print("condition not met") direction = -30 if direction > 0 : turtle.forward(direction) else: turtle.left(180) turtle.forward(-direction) Giving Directions¶Python turtles can be very good at following instructions. Let’s use
the Note Using Python 2? The It’s much easier to define this as a function, like so: def move(): direction = input("Go left or right? ") if direction == "left": turtle.left(60) turtle.forward(50) if direction == "right": turtle.right(60) turtle.forward(50) Now whenever you use “data munging”¶In this program, the turtle will only respond to exactly Here are some examples to print out the effects of my_variable = " I Am Capitalised" print(my_variable) my_stripped = my_variable.strip() print(my_stripped) my_lower = my_variable.lower() print(my_lower) Try adding Can you add some extra input choices to make the turtle draw other
things? How about |
| 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. |