SlideShare a Scribd company logo
www.teachingcomputing.com
Mastering Programming in Python
Lesson 2
• Introduction to the language, SEQUENCE variables, create a Chat bot
• Introduction SELECTION (if else statements)
• Introducing ITERATION (While loops)
• Introducing For Loops
• Use of Functions/Modular Programming
• Introducing Lists /Operations/List comprehension
• Use of Dictionaries
• String Manipulation
• File Handling – Reading and writing to CSV Files
• Importing and Exporting Files
• Transversing, Enumeration, Zip Merging
• Recursion
• Practical Programming
• 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, and more …
Series Overview
*Please note that each lesson is not bound to a specific time (so it can be taken at your own pace)
Information/Theory/Discuss
Task (Code provided)
Challenge (DIY!)
Suggested Project/HW
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!
IF Mr X is kind and helpful, THEN, we like him
ELSE we like him less!
Some philosophers will argue that all love is conditional. Others would say
nothing is truly unconditional(except God’s love – known as Agape in Greek) By
‘conditional’ we mean that an outcome depends on certain conditions.
In Python programming ELIF statements are
also used – short for ELSE AND IF
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 SELECTION (IF ELSE/ ELIF
statements, 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 IF…ELSE 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)
Pong (marketed as PONG) is one of the earliest arcade
video games and the very first sports arcade video game
What sort of if statements would be
needed in PONG?
An example of the use of Selection (IF)
Ifthe player has run out of lives, he…..dies!
https://youtu.be/GxL07giAC3M
Speaking of Video
games, the
following short
documentary on
Video Game
addition may be of
some interest.
What do you think?
Can Video Games
ruin people’s lives?
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 of the following flow chart? What is it trying to say?
If x < y
If y < x
Output: “Done”
Output “x is less
than y”
Output “y is less
than x”
Input x
Input y
5
7
Read more about Flow charts here: https://en.wikipedia.org/wiki/Flowchart
A few things to keep in mind …
Q1: If password !=“moose” then …. (In this code, what do you think “ != “ means?
!= is the
operator for
NOT equal to.
Q2: Also, do you know the difference between a = 2 and if a ==2 ?
Answer 1: Answer 2:
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 )
It’s 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, don’t forget the brackets when printing text
It’s 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.
Note: Sometimes we put bits of code in a 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 == password:
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.
Don’t 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 you’ve done the above, see if you can define more speficic
grade boundaries.
e.g. 0 – 20 = F
20 – 40 = E
40 –60 = D
60 – 70 = C
And so on …*You may need to do some research to complete this task!
Challenge 2: Solution(s)
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:
print("Pass")
elif num < 50:
print("Failed”)
Challenge 2 Solution Extension Solution
Using And / Or with IF statements
You can check multiple conditions by chaining together comparisons with and /or
#Example of AND
If x < y and x < z:
print (“x is less than y and z)
Example 1 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’ ?
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:')
print (computerfavnumber)
The official Python Site (very useful!)
Make a note of it and check out the tutorial! You can find what you’re looking for, in this
case, IF statements.
Use the glossary to reference something..
Useful Videos to watch on covered topics
https://www.youtube.com/watch?v=II5WTVvryvk
More on Robotics and AI today … Recommended video on Python Control Flow
https://www.youtube.com/watch?v=vMHfUWkELg0
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 today’s 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

More Related Content

What's hot (20)

DOCX
PYTHON NOTES
Ni
 
PPTX
Intro to Python Programming Language
Dipankar Achinta
 
PPT
Python - Introduction
stn_tkiller
 
PDF
Python made easy
Abhishek kumar
 
PPT
Python Programming Language
Dr.YNM
 
PPTX
Python Seminar PPT
Shivam Gupta
 
PPTX
Python Tutorial Part 1
Haitham El-Ghareeb
 
PDF
Python Workshop
Saket Choudhary
 
PDF
Python-01| Fundamentals
Mohd Sajjad
 
PPTX
Introduction to Python for Data Science and Machine Learning
ParrotAI
 
PDF
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 
PPTX
Python 3 Programming Language
Tahani Al-Manie
 
PDF
Python Tutorial
AkramWaseem
 
PPTX
Python introduction towards data science
deepak teja
 
PPTX
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Maulik Borsaniya
 
PPTX
Python ppt
Rachit Bhargava
 
PPT
Introduction to Python
Nowell Strite
 
PDF
Chapter 0 Python Overview (Python Programming Lecture)
IoT Code Lab
 
PPTX
Python second ppt
RaginiJain21
 
PYTHON NOTES
Ni
 
Intro to Python Programming Language
Dipankar Achinta
 
Python - Introduction
stn_tkiller
 
Python made easy
Abhishek kumar
 
Python Programming Language
Dr.YNM
 
Python Seminar PPT
Shivam Gupta
 
Python Tutorial Part 1
Haitham El-Ghareeb
 
Python Workshop
Saket Choudhary
 
Python-01| Fundamentals
Mohd Sajjad
 
Introduction to Python for Data Science and Machine Learning
ParrotAI
 
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 
Python 3 Programming Language
Tahani Al-Manie
 
Python Tutorial
AkramWaseem
 
Python introduction towards data science
deepak teja
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Maulik Borsaniya
 
Python ppt
Rachit Bhargava
 
Introduction to Python
Nowell Strite
 
Chapter 0 Python Overview (Python Programming Lecture)
IoT Code Lab
 
Python second ppt
RaginiJain21
 

Viewers also liked (20)

PDF
Workshop on Programming in Python - day II
Satyaki Sikdar
 
PPT
Primitive Data Types and Variables Lesson 02
A-Tech and Software Development
 
PPTX
CoderDojo: Intermediate Python programming course
Alexander Galkin
 
PPTX
SmartBoard Lesson Plans
georgekn
 
DOC
5 lesson 2 1 variables & expressions
mlabuski
 
PPTX
Lesson plan
Romà Mendoza
 
PPTX
Lesson 3: Variables and Expressions
"Filniño Edmar Ambos"
 
PPTX
Introduction to Advanced Javascript
Collaboration Technologies
 
PDF
Python - Lecture 1
Ravi Kiran Khareedi
 
PDF
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 
PDF
Learning notes of r for python programmer (Temp1)
Chia-Chi Chang
 
PDF
Java OOP Programming language (Part 1) - Introduction to Java
OUM SAOKOSAL
 
PDF
Meetup Python Nantes - les tests en python
Arthur Lutz
 
PDF
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 
PPT
Operator Overloading
Sardar Alam
 
PDF
Installing Python on Mac
Wei-Wen Hsu
 
PDF
Python for All
Pragya Goyal
 
PDF
Introduction to python
Yi-Fan Chu
 
PDF
Lesson1 python an introduction
Arulalan T
 
PDF
Python master class part 1
Chathuranga Bandara
 
Workshop on Programming in Python - day II
Satyaki Sikdar
 
Primitive Data Types and Variables Lesson 02
A-Tech and Software Development
 
CoderDojo: Intermediate Python programming course
Alexander Galkin
 
SmartBoard Lesson Plans
georgekn
 
5 lesson 2 1 variables & expressions
mlabuski
 
Lesson plan
Romà Mendoza
 
Lesson 3: Variables and Expressions
"Filniño Edmar Ambos"
 
Introduction to Advanced Javascript
Collaboration Technologies
 
Python - Lecture 1
Ravi Kiran Khareedi
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 
Learning notes of r for python programmer (Temp1)
Chia-Chi Chang
 
Java OOP Programming language (Part 1) - Introduction to Java
OUM SAOKOSAL
 
Meetup Python Nantes - les tests en python
Arthur Lutz
 
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 
Operator Overloading
Sardar Alam
 
Installing Python on Mac
Wei-Wen Hsu
 
Python for All
Pragya Goyal
 
Introduction to python
Yi-Fan Chu
 
Lesson1 python an introduction
Arulalan T
 
Python master class part 1
Chathuranga Bandara
 
Ad

Similar to Mastering python lesson2 (20)

PDF
Python Programming - III. Controlling the Flow
Ranel Padon
 
PPTX
ForLoops.pptx
RabiyaZhexembayeva
 
PPTX
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
PPTX
VKS-Python Basics for Beginners and advance.pptx
Vinod Srivastava
 
PPTX
Introduction To Python.pptx
Anum Zehra
 
PPTX
Application development with Python - Desktop application
Bao Long Nguyen Dang
 
PPT
Help with Pyhon Programming Homework
Helpmeinhomework
 
PDF
_PYTHON_CHAPTER_2.pdf
azha Affi11108
 
PPTX
Python Session - 6
AnirudhaGaikwad4
 
PDF
Intro-to-Python-Part-1-first-part-edition.pdf
ssuser543728
 
PDF
pyton Notes1
Amba Research
 
PDF
Introduction to python
mckennadglyn
 
PPT
AVB201.2 Microsoft Access VBA Module 2
Dan D'Urso
 
DOCX
INTERNSHIP REPORT.docx
21IT200KishorekumarI
 
DOCX
Python interview questions and answers
RojaPriya
 
PPT
Introduction to Python Lesson One-Python Easy Learning
johaneskurniawan2
 
PDF
Python for Physical Science.pdf
MarilouANDERSON
 
PDF
Python interview questions and answers
kavinilavuG
 
PPT
Learn python
mocninja
 
Python Programming - III. Controlling the Flow
Ranel Padon
 
ForLoops.pptx
RabiyaZhexembayeva
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
VKS-Python Basics for Beginners and advance.pptx
Vinod Srivastava
 
Introduction To Python.pptx
Anum Zehra
 
Application development with Python - Desktop application
Bao Long Nguyen Dang
 
Help with Pyhon Programming Homework
Helpmeinhomework
 
_PYTHON_CHAPTER_2.pdf
azha Affi11108
 
Python Session - 6
AnirudhaGaikwad4
 
Intro-to-Python-Part-1-first-part-edition.pdf
ssuser543728
 
pyton Notes1
Amba Research
 
Introduction to python
mckennadglyn
 
AVB201.2 Microsoft Access VBA Module 2
Dan D'Urso
 
INTERNSHIP REPORT.docx
21IT200KishorekumarI
 
Python interview questions and answers
RojaPriya
 
Introduction to Python Lesson One-Python Easy Learning
johaneskurniawan2
 
Python for Physical Science.pdf
MarilouANDERSON
 
Python interview questions and answers
kavinilavuG
 
Learn python
mocninja
 
Ad

Recently uploaded (20)

PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Introduction presentation of the patentbutler tool
MIPLM
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Difference between write and update in odoo 18
Celine George
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 

Mastering python lesson2

  • 2. • Introduction to the language, SEQUENCE variables, create a Chat bot • Introduction SELECTION (if else statements) • Introducing ITERATION (While loops) • Introducing For Loops • Use of Functions/Modular Programming • Introducing Lists /Operations/List comprehension • Use of Dictionaries • String Manipulation • File Handling – Reading and writing to CSV Files • Importing and Exporting Files • Transversing, Enumeration, Zip Merging • Recursion • Practical Programming • 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, and more … Series Overview *Please note that each lesson is not bound to a specific time (so it can be taken at your own pace) Information/Theory/Discuss Task (Code provided) Challenge (DIY!) Suggested Project/HW
  • 3. 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
  • 4. Conditional Logic – we use it all the time! IF Mr X is kind and helpful, THEN, we like him ELSE we like him less! Some philosophers will argue that all love is conditional. Others would say nothing is truly unconditional(except God’s love – known as Agape in Greek) By ‘conditional’ we mean that an outcome depends on certain conditions. In Python programming ELIF statements are also used – short for ELSE AND IF 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 SELECTION (IF ELSE/ ELIF statements, comparisons or Boolean variables)
  • 5. 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
  • 6. Examples of IF…ELSE 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) Pong (marketed as PONG) is one of the earliest arcade video games and the very first sports arcade video game What sort of if statements would be needed in PONG?
  • 7. An example of the use of Selection (IF) Ifthe player has run out of lives, he…..dies! https://youtu.be/GxL07giAC3M Speaking of Video games, the following short documentary on Video Game addition may be of some interest. What do you think? Can Video Games ruin people’s lives?
  • 8. 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 of the following flow chart? What is it trying to say? If x < y If y < x Output: “Done” Output “x is less than y” Output “y is less than x” Input x Input y 5 7 Read more about Flow charts here: https://en.wikipedia.org/wiki/Flowchart
  • 9. A few things to keep in mind … Q1: If password !=“moose” then …. (In this code, what do you think “ != “ means? != is the operator for NOT equal to. Q2: Also, do you know the difference between a = 2 and if a ==2 ? Answer 1: Answer 2: 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 ) It’s very important not to get the two confused!
  • 10. 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")
  • 11. 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, don’t forget the brackets when printing text It’s 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.
  • 12. Note: Sometimes we put bits of code in a 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")
  • 13. 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")
  • 14. Challenge 1: Solution def login(): username="username1" password="open123" print('Enter username') answer1=input() print('Enter password:') answer2=input() if answer1 == username and answer2 == password: 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. Don’t 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,
  • 15. 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")
  • 16. 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 you’ve done the above, see if you can define more speficic grade boundaries. e.g. 0 – 20 = F 20 – 40 = E 40 –60 = D 60 – 70 = C And so on …*You may need to do some research to complete this task!
  • 17. Challenge 2: Solution(s) 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: print("Pass") elif num < 50: print("Failed”) Challenge 2 Solution Extension Solution
  • 18. Using And / Or with IF statements You can check multiple conditions by chaining together comparisons with and /or #Example of AND If x < y and x < z: print (“x is less than y and z) Example 1 Example 2 #Non Exclusive Or If x < y or x < z: print(“x is less than either y or z”)
  • 19. 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’ ?
  • 20. ROBOTICS AND IF STATEMENTS As an extension, check out the following website on Robotics and IF statements http://arcbotics.com/lessons/if-statements/
  • 21. 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:') print (computerfavnumber)
  • 22. The official Python Site (very useful!) Make a note of it and check out the tutorial! You can find what you’re looking for, in this case, IF statements.
  • 23. Use the glossary to reference something..
  • 24. Useful Videos to watch on covered topics https://www.youtube.com/watch?v=II5WTVvryvk More on Robotics and AI today … Recommended video on Python Control Flow https://www.youtube.com/watch?v=vMHfUWkELg0
  • 25. 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 today’s 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?
  • 26. 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

Editor's Notes

  • #2: Associated Resource: Python GUI Programming: See www.teachingcomputing.com (resources overview) for more information
  • #3: Associated Resource: Python GUI Programming: See www.teachingcomputing.com (resources overview) for more information
  • #4: Image source: http://www.peardeck.com
  • #5: Image(s) source: Dreamstime.com (royalty free images)
  • #6: Image(s) source: wikipedia
  • #7: Image(s) source: Dreamstime.com (royalty free images)
  • #8: Image Source: https://s-media-cache-ak0.pinimg.com
  • #9: Image(s) source: Dreamstime.com (royalty free images)
  • #10: Image(s) source: Dreamstime.com (royalty free images)
  • #15: Teachers: You may want to delete this slide if you are giving the power point to your students!
  • #19: Image(s) source: Dreamstime.com (royalty free images)
  • #20: Image(s) source: Dreamstime.com (royalty free images)
  • #21: Source: taken from BBC news article that can be read here: http://www.bbc.co.uk/news/35501537
  • #26: Image(s) source: Wikipedia
  • #27: Image(s) source: Wikipedia