MrSchmid.com

Branching, while Loops, and If - then

Posted On: Wed, 2008-03-26 14:52 by mrschmid

Branching, while Loops, and If - then

 Indentation:

Python is unique in that it requires blocks of code under a branching operator to be indented. Any line of code that is indented under an IF statement is code that will be executed if that IF statement is true. It doesn’t matter how you indent, but you must be consistent with your indentation. You can use 1 tab, or 2 spaces, or 4 spaces, but using 2 when you have been using 3 spaces will create problems.


Operator

Meaning

Sample Condition

Evaluates To

==

equal to

5 == 5

True

!=

not equal to

8 != 5

True

>

greater than

3 > 10

False

<

less than

5 < 8

True

>=

greater than or equal to

5 >= 10

False

<=

less than or equal to

5 <= 5

True


Hacker program

Computer Club

Loops – WHILE

Loops are blocks of code that will repeat until a condition is met. That condition is called a sentry value. Before creating a loop, we ignitialize the sentry value before it’s used in the loop.

Caution – beware of the infinite loop. Infinite loops never end and will crash the program. Always check that your loop has a condition that is possible to meet (or likely).

Three year old simulator

- Hi-Lo program

Psuedocode and Flow Charts

It’s a good idea to map out how your program will work before you start to code. The two most popular ways to map out a plan is with psuedocode or flow charts. Psuedocode is writing the steps in the process of the program, while flow charts visually show the flow of the program.

 

EXERCISES

 

- Modify Computer Club Program so it returns the user’s security level and a clever line about the user’s security level.

Magic 6 ball program
Write a program that follows this flow chart .

Coin Flipper

Write a program that flips a coin 100 times and then tells you the number of heads and tails. – use the random function to generate a 1 or a 2, then use a if statement to add a count for either heads or tails.

Modified Hi-Lo

Modify the Hi-Lo game so that the player has a limited number of guesses. If the player fails to guess in time, the program should display an appropriately chastising message.

Salary Doubled
You’ve started a new job with a strange salary schedule. You will make a penny on the first day, with your salary doubling on the 2nd day, then your salary doubling again. So for day 1 you would make $0.01, on day two: $0.02 and on day 3 $0.04. Write a program that will display the day, the day’s wages and the total wages earned to date. Stop the program after a month (30 days) and see how rich you’d be in just a month!

Practices: Hacker, Computer Club, 3-yr old, Hi-Lo
Exercises: Modified Computer Club, Magic 6 Ball, Coin Flipper, Modified HiLo, Salary Doubled

AttachmentSize
hacker.gif6.36 KB
computerclub.gif13.65 KB
threeyearold.gif6.54 KB
hilo.gif12.45 KB
magic6_flow.JPG37.3 KB
branch.jpg32.19 KB
( categories: | )