Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week 1, Day 2 Programmatic mastery

Similar presentations


Presentation on theme: "Week 1, Day 2 Programmatic mastery"— Presentation transcript:

1 Week 1, Day 2 Programmatic mastery
28 June 2016

2 Day 1 Recap Python Basics: Installing What is programming?
Arithmetic Operations Functions Interpreter vs Script files The print and input functions Types Variables Day 1 Recap Recap ♻♻💡💡

3 Day 2 Plan Conditionals Loops Conditional Statements Boolean Logic
Boolean Expressions Loops Loop Statements While Loops Loop Patterns Day 2 Plan Today we’re going to look at more interesting control flow, and allow your programs to actually make decisions, instead of doing exactly the same thing every time. Boolean logic is a way of thinking about complex conditions, and we will look at how to understand and simplify boolean expressions to do that. Loops allow us to run the same block of code several times, without having to copy it out repeatedly. For example, it was a little tedious when we were writing the receipt program to have to write the code which asks for an item and a price repeatedly.

4 Conditional Statements
(AKA if statements AKA branches) 🌵 🔀

5

6 Python Comparison Operators
Python Symbol Meaning == != Equals, Not Equals > < Greater than, Less than >= <= Greater than or equals, Less than or equals Python Comparison Operators

7 Exercise 2.1 – Programmable Calculator
Write a short calculator program that the use can set into four different modes by answering a suitable prompt. This program should then prompt the user for two numbers, and depending upon the mode the calculator is in, print out the result If you haven’t yet, this is definitely a good time to mention `“...” % (...)`. We’re looking for them to use the “\n” special character, which they won’t be able to guess but they might be able to look up online. It’s worth reminding them that they can use the box! There’s a reasonable StackOverflow answer as the first result for “Python special character new line” currently.

8 Alternatives I personally think of program structure as a literal “flow” of control. It might be worth drawing up a kind of tree diagram with branches, each representing one if/else condition. Then show how different runs of the program will follow different paths through the tree depending on things like user input. Show how the paths might split, but ultimately rejoin at the end, having taken different routes to the end. You can augment this kind of diagram later with loops.

9 Exercise 2.1(b) – Programmable Calculator
Write a short calculator program that the use can set into four different modes by answering a suitable prompt. This program should then prompt the user for two numbers, and depending upon the mode the calculator is in, print out the result Use only one if, multiple elifs and an else If you haven’t yet, this is definitely a good time to mention `“...” % (...)`. We’re looking for them to use the “\n” special character, which they won’t be able to guess but they might be able to look up online. It’s worth reminding them that they can use the box! There’s a reasonable StackOverflow answer as the first result for “Python special character new line” currently.

10 Python Logical Operators
Python Symbol Meaning and Both expressions must be true or One expression must be true not The expression must not be true Python Logical Operators Demonstrate with examples. if (name==”Christopher” and age==22):    print(“It’s you!”) Try to explain that a condition like “3 < 5” is completely equivalent to the boolean value True, in the same way that “2 + 2” is completely equivalent to the number 4. You can then further simplify more complicated expressions involving `and` or `or`. For example `3<5 and 5!=10 or 10<4` -> `True and True or False` -> `True or False` -> `True`. This might need lots of examples to convey effectively. Perhaps draw up some truth tables collectively, and leave them on the board for reference.

11 Exercise 2.2 - PythonFunQuiz
Write a short program that asks the user five questions If the user gets the answer correct, print "Correct" and award them a point. If their final score is greater than 3 print out a suitable message of encouragement. Once again, a demonstration of a working quiz will be beneficial. It’s up to you if you want them to think about case-sensitivity. == is obviously case-sensitive. If they want to do a case-insensitive search, they’ll need to use “My String”.lower(). Watch out for quizzes which just do numeric answers to get around this problem… I like to (once again) encourage good style by factoring out a function “check” which takes the question and the expected answer, asks the user for their answer, does all the requisite printing, and finally returns 1 or 0 depending on whether the answer is correct. Then the quiz body is as simple as score = score + check(“What is the capital of England?”, “London”) score = score + check(“What is the capital of France?”, “Paris”) ...

12 Exercise 2.2(b) - PythonFunQuiz
Write a short program that asks the user five questions If the user gets the answer correct, print "Correct" and award them a point. If their final score is less than 2 points, print out a message of commiseration, between 3 and 4 points, print out a suitable message of encouragement. If it’s exactly 5, congratulate them! Getting them to think about non-redundant ranges is a valuable aim (if score<=2:... elif score<=4: … else: …). Alternatively, redundant checks offer the opportunity to practice combining conditions (if score<2:... elif score>=3 and score<=4: … elif score==5. Also note the ambiguity in “less than 2 points”. In our world, <2 is the same as ==1. So perhaps <=2 is more useful. Ditto with the second requirement - strictly speaking, there is nothing “between” 3 and 4 unless you’re inclusive.

13 Exercise 2.3 - Mark of Authority
Write a short program that prompts the user to enter the percentage marks of a hapless student for a series of subjects. Perform the necessary calculations to determine if the student has passed all subjects (their mark in each must be more than 50%)

14 Exercise 2.3(b) - Mark of Authority
Write a short program that prompts the user to enter the percentage marks of a hapless student for a series of subjects. Perform the necessary calculations to determine if the student has passed all subjects (their mark in each must be more than 50%) as well as determining if they've passed the whole year (average mark must be more than 50%). Some kids will try to do this by calculating the average mark and comparing that to 50. That’s probably the better approach, in fairness, but the exercise is looking for a bunch of boolean comparisons. I normally ask for both possible approaches.

15 Loops

16 Exercise 2.4 Look around the room.
Observe the people for a while, and try to spot someone who is performing the same set of actions repeatedly. Think about why they are repeating themselves, and make a prediction about what would make them stop Another exercise that is probably best carried out collaboratively on the board.

17 A circular railway shares many of the benefits of the same benefits as loops.

18 The While Loop Start by demonstrating a basic counter loop: x = 0
while x<10:    print(“I am on number “ + str(x))    x = x + 1 If you want to introduce shorthand update assignments (e.g. x += 1) then feel free to, but I have never found it worth the complication of explaining.

19 Exercise 2.5 - Starry Loops
Write a program that: Prompts a user to input a size. Print out as many *s as specified by the user, each on its own line

20 Exercise 2.5(b) - Starry Loops
Write a program that: Prompts a user to input a size. Print out a pyramid made up of *s that is as tall as specified by the user This is a fun one. Leading on from the previous exercise; you might like to start by printing out a right-angled triangle before moving onto the pyramid. I’ve had success getting students to work out the relationship between the number of stars on one line and the line number, and then doing the same with the number of spaces leading a line.

21 Loop Pattern: Counter Loops
This is a mechanical counter, if the picture isn’t quite clear. The pattern is a while loop with a variable that is incremented each iteration. This is the kind of loop they used for the previous exercise.

22 Loop Pattern: Infinite Loops
This is a surprisingly common pattern - used in many operating system processes. Also will be used when we come to using PyGame. When demonstrating, also demonstrate the use of Ctrl+C to interrupt In practice, an infinite loop will be more useful if it does eventually break, even if we don’t know in advance when that will be. Cue run-until....

23 Loop Pattern: Run-until
Especially useful for interfaces that run until the user specifies that they want to exit. This is a good time to introduce the break statement. Two forms which are useful in different scenarios: while True: # modifying the infinite loop userans = input("Do you want to continue?") if userans == "no": break cont = True while cont: cont = False

24 Ex 2.6 - Two Calculators walk in...
Write a program that: Asks a user how many calculations they would like to perform. Then, for however many calculations, prompt the user for the operation they would like to perform, as well as the two numbers involved. Make sure they’re using a counter loop for this

25 Ex 2.6(b) - Two Calculators walk in...
Modify your calculator so that rather than asking for the number of calculations, the program runs until the user indicates that they would like to exit

26 Day 2 Conditionals: Loops: Conditional Statements Alternatives
Boolean Logic Boolean Expressions Loops: Loop Statements While Loops Loop Patterns Day 2 Recap ♻♻💡💡 Go into detail if you can during the recap -- remind people of the specific problems that they encountered during the day, and how they managed to surmount them. It feels good to overcome obstacles, so remind them that what they’ve been doing is difficult, that they’ve come a long way, and that they’re doing a great job already!

27 Now for the Challenges! 💪🏆💪🏆

28 Ex 2.7 – Interactive Story Write a short choose-your-adventure story in programmatic form. Prompt the user for inputs, and the story progresses based upon their choices.

29 Ex 2.8 – Role-Playing Game Extend your interactive story by making it into a Role Playing Game. Keep track of attributes such as health, armour level, etc. Determine the outcome of scenarios based on the values of these attributes as well as player choices. If you’re running short of time, this can be tackled as a stand-alone challenge (and might be more valuable from a programming perspective than the story exercise). Start by defining some variables for e.g. health, stamina and gold. First try a monster fight - ask the user whether to run away or fight, and then select an attack to use. Different attacks might have different success rates (perhaps use random.randint() ), but cost different stamina. If your attack misses, you get hurt. If you defeat the monster, you get gold. With that done, factor the monter fight out into a function (may need to use globals or something clever for player variables. If you return to this on a later day, it might be worth introducing a player dictionary or class.)


Download ppt "Week 1, Day 2 Programmatic mastery"

Similar presentations


Ads by Google