Sie sind auf Seite 1von 27

Mastering Programming in Python

Lesson 2

100s of other resources are available from

www.teachingcomputing.com

Series Overview

Introduction to the language, SEQUENCE variables, create a Chat bot


SELECTION (if else statements)
ITERATION (While loops)
Introducing For Loops
Challenges and tasks for Mastering Iteration
Use of Functions/Modular Programming
Introducing Lists /Operations/List comprehension
Tuples, sets, lists, dictionaries
Use of Dictionaries
Doing things with strings
File Handling Reading, writing, appending text files
Working with CSV files
Practical Programming (plenty of engaging scenarios, challenges
and tasks to get you thinking)
Consolidation of all your skills useful resources
Includes Computer Science theory and Exciting themes for every
lesson including: Quantum Computing, History of Computing,
Future of storage, Brain Processing, Systems life Cycle, Testing
and more

Information/Theory/Discuss
Task (Code provided)
Challenge (DIY!)
Suggested Project/HW

*Please note that each lesson is not bound to a specific time (so it can be taken at your own pace)

In this lesson you will

Learn about conditional logic/control


flow/selection using IF ELSE statements
Look at the use of Selection in Game Design
Learn about Debugging/Error checking
Analyse a Flow Chart (which has Selection in it)
Discuss Video Gaming Addiction
Create a password checker
Create a username and password (login) app
Learn about the use of ELIF
Learn about Boolean Variables
Learn about Multiple Comparisons using and/or

Conditional Logic we use it all the time!


Some philosophers will argue that all love is conditional. Others
would say nothing is truly unconditional(except Gods love
known as Agape in Greek) By conditional we mean that an
outcome depends on certain conditions.
IF Mr X is kind and helpful, THEN, we
like him
ELSE we like him less!
IF we are full (after dinner) THEN we
go without dessert, ELSE, we eat the
apple pie!
In programming we can control the
flow of a program by using
In Python programming ELIF
SELECTION (IF ELSE/ ELIF statements,
statements are also used short
for ELSE AND IF
comparisons or Boolean variables)

Did you know?


A software bug is an error or flaw in a
computer program.
As a programmer, you are going to come
up a lot of these and it is important that
you are patient and persevere!
The first ever bug was an actual bug!
Operators traced an error in the Mark II to
a moth trapped in a relay, coining the
term bug. This bug was carefully removed
and taped to the log book
Stemming from this we now call glitches in
a computer a bug.

A page from the Harvard Mark IIelectromechanical computer's log,


featuring a dead moth that was removed from the device

Examples of IFELSE in game design.


It would be hard to think about creating a game without using
SELECTION (if else statements). You probably remember first
using these in SCRATCH (if else blocks)
What sort of if statements would
be needed in PONG?

Pong (marketed as PONG) is one of the


earliest arcade video games and the very first

An example of the use of Selection (IF)

If

the player has run out of lives, he..dies!


Speaking of
Video games,
the following
short
documentary on
Video Game
addition may be
of some
interest.
What do you
think?
https://youtu.be/GxL07giAC3M

Can you follow the logic of this flow chart?

You will often need to create flow charts to show the logic behind
your program.
Can you make any sense
the
following
chart? What is it
Readof
more
about
Flow chartsflow
here: https://en.wikipedia.org/wiki/Flowc
True
trying Ifto
x <say?
y

False

If y <
x
False

Output:
Done

Output x is
less than y

Input x 5

True

Output y is
less than x

Input y 7

A few things to keep in mind


Q1: If password !=moose then . (In this code, what do you
think != means?
Q2: Also, do you know the difference between a = 2
and
if a ==2 ?

Answer 1:

Answer 2:

!= is the

Use = when you are


assigning a value. (e.g. a =
2) and == is used when you
are CHECKING to see if two
values are equal.
(e.g. if a==2 then do x,y,z )

operator for
NOT equal to.

Its very important not to get


the two confused!

Task 1: Create a password checker


1. Open a Python
Module
2. Copy and paste
the code on the
right into the
module
3. Run the program
to see what it
does
4. See if you can fix
the errors to get it
to work.

#This doesn't quite work - lots of errors. Fix them (mostly


syntax and indentation errors) and get the program to work!
#This doesn't quite work - lots of errors. Fix them (mostly
syntax and indent error) and get the program to work!
password="open123"
print('Enter password:')
answer=input()
if answer==password:
print("yes")
else
print("no")

Task 1: Solution
password="open123"
print('Enter password:')
answer=input()
if answer==password:
print("yes")
else:
print("no")

Common errors to
look for.

Speech marks when referring to the data type


STRING
In Python 3, dont forget the brackets when
printing text
Its easy to forget to use the double equal signs
in Python
Identation is key in Python. Make sure the IF
and ELSE are on the same indent line.
Similarlty the PRINT (within the IF and ELSE
statements) need to be indented.

function. In Python a function is defined with


the word: def (see below to call a function
and run the code)
def login():
username="username1"
print('Enter username')
answer1=input()
print('Enter password:')
if answer1 == username and
answer2 = password:
print("Access Granted")
else:
print("Sorry, Access
Denied")

Challenge 1: Username and psswd check.


1. Open a Python
Module
2. Copy and paste
the code on the
right into the
module
3. Here we use a
function so in the
shell type login()
to RUN the
program
4. Get it to work!

#Task - create a program which asks the user for their


username AND password.
#only if BOTH are correct, access is granted, else any other
combination
results in access denied
def login():
username="username1"
print('Enter username')
answer1=input()
print('Enter password:')
if answer1 == username and answer2 = password:
print("Access Granted")
else:
print("Sorry, Access Denied")

Challenge 1: Solution
def login():
username="username1"
password="open123"
print('Enter username')
answer1=input()
print('Enter password:')
answer2=input()
if answer1 == username and answer2
print("Access Granted")
else:
print("Sorry, Access Denied")

Declare a password variable and assign it


a value!
Declare answer2 as a variable for user
input.

== password:

Dont forget the double equals sign here.


Remember when you are checking
equivalence a == is used, but when it
is a simple assignment operator, a single
equals sign = will suffice,

Task 2: Check number using ELIF


1. Open a Python
Module
2. Copy and paste
the code on the
right into the
module
3. Here we use a
function so in the
shell type
checknum() to
RUN the program
4. Analyse the code

def checknumber():
#
#
#
#

In this program, we input a number


check if the number is positive or
negative or zero and display
an appropriate message
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Challenge 2: Create a grade checker app


1. Open a Python
Module
2. Using the previous
code in Task 2,
see if you can
create a function
called
gradechecker
3. The pseudo code
for the program is
on the right.
4. Can you do it!?

1. Ask the user for their grade (which must be between 0


and 100)
2. Allow the user to input their response (an integer
response between 0 and 100)
3. If the user enters anything under 50 (<50) then print
Fail
4. If the user enters anything above 50 (>50) then print
Pass
Extension: If youve done the above, see if you can define
more speficic grade boundaries.
e.g. 0 20 = F
20 40 = E

Challenge 2: Solution(s)
Challenge 2 Solution

def
gradechecker():
# In this
program, we
input a number
# check if the
number is
positive or
# negative or
zero and display
# an appropriate
message
num =
float(input("Enter
a number: "))
if num > 50:

Extension Solution

Using And / Or with IF statements


You can check multiple conditions by chaining together
comparisons with and /or

Example 1
#Example of
AND
If x < y and x < z:
print (x is less than
y and z)

Example 2
#Non Exclusive
Or
If x < y or x < z:
print(x is less than
either y or z)

Boolean Variables with IF statements


Python supports Boolean variables. They are basically variables
that can either store the value True or False. When using an IF
statement, the expression needs to evaluate to either True or
False
In the following
example, the
variable
seat_booked is
set to True.
What would
happen if it was
changed to
False ?

Constants
It is worth noting that many of the programs you write will have
CONSTANTS as well as variables. The difference is that constants remain
constant that is they dont change! Examples shown below:
Black and White on the right are in
UPPER CASE and we put them in
like this to signify they are constants.
If you expect a colour to change
during the program execution, then it
should be set, not to a constant, but
to a variable! An example would be
Backgroundcolour!

Variable:
off black)

backgroundcolor = (0,0,0) (starts

Well get into what these colours actually mean


and how they are created in Series 3 (game
design and object orientated programming).
You can of course, always skip ahead and find
out for yourself!

ROBOTICS AND IF STATEMENTS


As an extension, check out the following website on Robotics and
IF statements

http://arcbotics.com/lessons/if-statements/

Challenge: Extend your Chabot from Lesson


1 using Selection and Functions.
Here are some
suggestions, but get
creative and implement
your own ideas!
**********Get the computer to
ask the user for an age. IF the
age is above 16, take them to
another function where the
program continues, ELSE, quit
the program and inform the user
that they are too young.

#This is a chatbot and this is a comment, not executed by


the program
#Extend it to make the computer ask for your favourite
movie and respond accordingly!
print('Hello this is your computer...what is your favourite
number?')
#Declaring our first variable below called
'computerfavnumber' and storing the value 33
computerfavnumber=33
#We now declare a variable but set the variable to hold
whatever the *user* inputs into the program
favnumber=input()
print(favnumber + '...is a very nice number indeed.
So...what is your name?')
name=input()
print('what a lovely name: ' + name + '...now, I will reveal
what my favourite number is:')

The official Python Site (very useful!)


Make a note of it and check out the tutorial! You can find what youre looking for, in this
case, IF statements.

Use the glossary to reference something..

Useful Videos to watch on covered topics


More on Robotics and AI today

https://www.youtube.com/watch?v=vMHfUWkELg0

Recommended video on Python Control Flow

https://www.youtube.com/watch?v=II5WTVvryvk

Suggested Project / HW / Research


Create a research information point on the history and future of AI
Create a timeline of Artificial Intelligence
What are the applications of Artificial Intelligence in todays society?
What are the advancements in Robotics today?
What is the future of AI and Robotics?
What countries are currently at the forefront in these crucial fields?
Compare and contrast the use of SELECTION in four different high level
languages (suggested: Python, VB.Net, C++, Java)
Give examples of the syntax of if statements in each language
Look up Case statements in VB.Net what is the equivalent in Python
Contrast and compare the advantages of Python and VB.Net as languages? Which
do YOU think is better and why?

Useful links and additional reading


http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/index.html
http://www.python-course.eu/variables.php
http://www.programiz.com/python-programming/variables-datatypes
http://www.tutorialspoint.com/python/python_variable_types.htm
https://en.wikibooks.org/wiki/Python_Programming/Variables_and_Strings

Das könnte Ihnen auch gefallen