Thursday 16 October 2014

9. Selection constructs and writing readable code: elif



Leaning Outcomes
You will learn to:
Use ELIF
Write readable code
Activity 8.1
Using elif
This program simulates a fortune cookie. A random number is used to decide your ‘fortune’.
Copy and run this program.
# a random number is given by the randint() function
import random
answer= random.randint(1,6)
if answer == 1:
print("You will make a new friend this week")
elif answer == 2:
print("You will do well in your GCSEs")
elif answer == 3:
print("You will find something you thought you’d lost")

The program is not yet complete. Include your own ‘fortunes’ for the numbers 4, 5 and 6.

Note: random.randint(1,6) is a function that returns a random number between 1 and 6. The ‘import random’ command allows the program to access the random.randint() function.
Activity 8.2
Writing readable code: a style guide
Program code is read more often that it is written. Here are some guidelines on how to write Python code so that it is easy to read.
A style guide for Python code
Indent by four spaces for each indentation level.
Use blank lines to separate different parts of the program.
Use two blank lines to separate functions.
Choose meaningful names for variables, using CamelCase or with words separated by underscores.
Put imports at the top of the file.
Include one space around each side of an assignment and other operators.
Use complete sentences with the first word capitalised for comments.
Write comments that add clarity and explain what the program does. Do not simplyrepeat what the code already says.
Write function names in lowercase, with words separated by underscores.
Use meaningful function names which describe the purpose of the function.
Write constants in CAPITAL_LETTERS.
Use meaningful constant names, which describe the purpose of the constant.

Note: Functions are subprograms which start with the “deffunction_name():. Constants are variables whose value never changes. You will be covering functions in later lessons.  
Apply the rules in the style guide above for this Python code.
def a(s):
if s<50:
print("You have lost")
else:
print("You have won")  
Activity 8.3
Select some of your programs and make them more readable using the rules in the style guide.Lesson 9 activities

No comments:

Post a Comment