SlideShare a Scribd company logo
1 of 266
Introduction to Python
Damian Gordon
e: Damian.Gordon@dit.ie
t: @damiantgordon
Introduction
• This talk is aimed at people who are new to Python, to
teach them basic operations and algorithms in Python.
• We will look at SEQUENCE, SELECTION, and ITERATION.
• We will look at some COMMON ALGORITHMS.
Your Speaker is…
• Lecturer for 15 years in Dublin Institute of Technology
• Educational Advisor on a number of EU projects
• Research Interests
– Education, Assistive Technology, Creativity, Hacking
• previously Developer, Analyst, IT consultant
• Programming for over 30 years
• I absolutely love Python
http://www.damiantgordon.com/python/
Includes:
• Videos
• PowerPoints
• Over 100 code samples
• Exercises
• External links
The Python Programming Language
• Python was developed by
Guido van Rossum in the
Netherlands in 1989.
• Van Rossum is Python's
principal author, and his
continuing central role in
deciding the direction of
Python is reflected in the title
given to him by the Python
community, Benevolent Dictator
for Life (BDFL).
The Python Programming Language
• Python is named for the
British comedy group Monty
Python.
• The main members of the
group are Eric Idle, Terry
Jones, John Cleese, Michael
Palin, Graham Chapman, and
Terry Gilliam.
The Python Programming Language
• Python is named for the
British comedy group Monty
Python.
• The main members of the
group are Eric Idle, Terry
Jones, John Cleese, Michael
Palin, Graham Chapman, and
Terry Gilliam.
The Python Programming Language
2000
Ver 2
2008
Ver 3
1989
Ver 1
The Python Programming Language
• Python is a multi-paradigm programming language:
– structured programming
– object-oriented programming
– functional programming
– aspect-oriented programming
– design by contract
– logic programming
The Python Programming Language
• Python uses dynamic typing and a combination of reference
counting and a cycle-detecting garbage collector for memory
management. An important feature of Python is dynamic
name resolution (late binding), which binds method and
variable names during program execution.
The Python Programming Language
• Rather than requiring all desired functionality to be built into
the language's core, Python was designed to be highly
extensible. Python can also be embedded in existing
applications that need a programmable interface. This design
of a small core language with a large standard library and an
easily extensible interpreter was intended by Van Rossum from
the very start
The Python Programming Language
• Since 2003, Python has
consistently ranked in the top
ten most popular programming
languages as measured by the
TIOBE Programming
Community Index. As of
September 2015, it is in the
fifth position. It was ranked as
Programming Language of the
Year for the year 2007 and
2010.
What does Python look like?
# PROGRAM CheckPrime:
##################
# ERROR CHECKING #
##################
c = str(input("Do you want error checking on? (y/n)"))
if c == 'y':
# THEN
MyErrorCheck = True
else:
MyErrorCheck = False
# ENDIF;
##################
# PRIME CHECKING #
##################
a = int(input("Please input value:"))
b = a - 1
IsPrime = True
Part 1 of 3
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
if MyErrorCheck == True:
# THEN
print("*** Division with no remainder found, with ", b, "*****”)
# ENDIF;
# ENDIF;
if MyErrorCheck == True:
# THEN
print(">> a is ",a,">> b is ",b, ">> IsPrime is ",IsPrime)
# ENDIF;
b = b - 1
# ENDWHILE;
Part 2 of 3
if IsPrime:
# THEN
print(a, "is a prime number")
else:
print(a, "is not a prime number")
# ENDIF;
# END.
Part 3 of 3
The Python Programming Language
• Organizations that use Python include Google, Yahoo!, CERN, and
NASA.
• Python can serve as a scripting language for web applications
• Python has been embedded in a number of software products as a
scripting language, including in finite element method software
such as Abaqus, 3D parametric modeler like FreeCAD, 3D animation
packages such as 3ds Max, Blender, Cinema 4D, Lightwave, Houdini,
Maya, modo, MotionBuilder, Softimage, the visual effects
compositor Nuke, 2D imaging programs like GIMP, Inkscape, Scribus
and Paint Shop Pro, and musical notation program or scorewriter
capella.
IDLE
etc.
PEP 20 –
The Zen of Python
Tim Peters
Top-Down Design
Damian Gordon
Top-Down Design
• Top-Down Design (also known as stepwise design) is breaking
down a problem into steps.
• In Top-down Design an overview of the problem is described
first, specifying but not detailing any first-level sub-steps.
• Each sub-step is then refined in yet greater detail, sometimes
in many additional sub-steps, until the entire specification is
reduced to basic elements.
Example
• Making a Cup of Tea
Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
Example : Step-wise Refinement
Step-wise refinement of step 1 (Organise everything together)
1.1 Get a cup
1.2 Get tea bags
1.3 Get sugar
1.4 Get milk
1.5 Get spoon/fork.
Example : Step-wise Refinement
Step-wise refinement of step 2 (Plug in kettle)
2.1 Locate plug of kettle
2.2 Insert plug into electrical outlet
Example : Step-wise Refinement
Step-wise refinement of step 3 (Put teabag in cup)
3.1 Take teabag from box
3.2 Put it into cup
Example : Step-wise Refinement
Step-wise refinement of step 4 (Put water into kettle)
4.1 Bring kettle to tap
4.2 Put kettle under water
4.3 Turn on tap
4.4 Wait for kettle to be full
4.5 Turn off tap
Example : Step-wise Refinement
Step-wise refinement of step 5 (Turn on kettle)
5.1 Depress switch on kettle
Over to you…
etc.
Variables
Damian Gordon
Variables
• We know what a variable is from maths.
• We’ve all seen this sort of thing in algebra:
2x – 10 = 0
2x = 10
X = 5
Variables
• We know what a variable is from maths.
• We’ve all seen this sort of thing in algebra:
2x – 10 = 0
2x = 10
X = 5
Variables
• We know what a variable is from maths.
• We’ve all seen this sort of thing in algebra:
2x – 10 = 0
2x = 10
X = 5
Variables
• We know what a variable is from maths.
• We’ve all seen this sort of thing in algebra:
2x – 10 = 0
2x = 10
X = 5
Variables
• We know what a variable is from maths.
• We’ve all seen this sort of thing in algebra:
2x – 10 = 0
2x = 10
X = 5
Variables
• …and in another problem we might have:
3x + 12 = 0
3x = -12
X = -4
Variables
• So a variable contains a value, and that value changes over
time.
Variables
• …like your bank balance!
Variables
• In programming, we tell the computer the value of a variable
• So, for example,
x <- 5
means “X gets the value 5”
or “X is assigned 5”
Variables
• In programming, we tell the computer the value of a variable
• So, for example,
x = 5
means “X gets the value 5”
or “X is assigned 5”
Variables
• In programming, we tell the computer the value of a variable
• So, for example,
x = 5
means “X gets the value 5”
or “X is assigned 5”
X
Variables
• In programming, we tell the computer the value of a variable
• So, for example,
x = 5
means “X gets the value 5”
or “X is assigned 5”
X
5
Variables
• And later we can say something like:
x = 8
means “X gets the value 8”
or “X is assigned 8”
Variables
• If we want to add one to a variable:
x = x + 1
means “increment X”
or “X is incremented by 1”
X(new)
5
X(old)
4
+1
Variables
• We can create a new variable Y
y = x
means “Y gets the value of X”
or “Y is assigned the value of X”
Y
X
6
6
Variables
• We can also say:
y = x + 1
means “Y gets the value of x plus 1”
or “Y is assigned the value of x plus 1”
Y
X
6
7
+1
Variables
• All of these variables are integers
• They are all whole numbers
Variables
• Let’s look at numbers with decimal points:
P = 3.14159
means “p gets the value of 3.14159”
or “p is assigned the value of 3.14159”
Variables
• We should really give this a better name:
Pi = 3.14159
means “Pi gets the value of 3.14159”
or “Pi is assigned the value of 3.14159”
Variables
• We can also have single character variables:
Vitamin = ‘B’
means “Vitamin gets the value of B”
or “Vitamin is assigned the value of B”
Variables
• We can also have single character variables:
RoomNumber = ‘2’
means “RoomNumber gets the value of 2”
or “RoomNumber is assigned the value of 2”
Variables
• We can also have a string of characters:
Pet = “Dog”
means “Pet gets the value of Dog”
or “Pet is assigned the value of Dog”
Variables
• We also have a special type, called BOOLEAN
• It has only two values, TRUE or FALSE
IsWeekend = False
means “IsWeekend gets the value of FALSE”
or “IsWeekend is assigned the value of FALSE”
etc.
Python: Print
Damian Gordon
Your first Python program
• When learning a new computer programming language, the
first thing typically taught is how to write a message to the
screen saying “Hello, World”.
• Let’s see how to do that:
print(“Hello, World”)
# PROGRAM HelloWorldProgram:
print(“Hello, World”)
# END.
# HelloWorldProgram – Version 1
# A program to print out “Hello, World”
# Written by: Damian Gordon
# Date: 10/09/2015
# PROGRAM HelloWorldProgram:
print(“Hello, World”)
# END.
The PRINT statement
• If we want to add a blank line after our print statement:
# PROGRAM HelloWorldProgram:
print(“Hello, World”)
# END.
# PROGRAM HelloWorldProgram:
print(“Hello, World”)
# END.
# PROGRAM HelloWorldProgramNewLine:
print(“Hello, Worldn”)
# END.
The PRINT statement
• To print out two lines of text we do:
# PROGRAM HelloWorldProgramTwoLines:
print(“Hello, World”)
print(“I’m here”)
# END.
The PRINT statement
• To join two strings together:
# PROGRAM HelloWorldProgramJoined:
print(“Hello, World” + “ I’m here”)
# END.
The PRINT statement
• To print out the same message 10 times:
# PROGRAM HelloWorldProgram10Times:
print(“Hello, World” * 10)
# END.
The PRINT statement
• To print out the same message 10 times, each one on a new
line:
# PROGRAM HelloWorldProgramNewLine10Times:
print(“Hello, Worldn” * 10)
# END.
Code Description
 Print a backslash
’ Print a single quote
” Print a double quote
a Play a beep
n Print a new line
t Print a tab
Python: Maths
Damian Gordon
Some Simple Maths
• Let’s look at some simple maths first:
# PROGRAM AddingNumbers:
print(10 + 7)
# END.
Some Simple Maths
• Let’s make that a bit more fancy
# PROGRAM AddingNumbers:
print(“10 + 7 = “, 10 + 7)
# END.
Some Simple Maths
• Let’s try subtraction:
# PROGRAM SubtractingNumbers:
print(“10 - 7 = “, 10 - 7)
# END.
Some Simple Maths
• Let’s try multiplication:
# PROGRAM MultiplyingNumbers:
print(“10 * 7 = “, 10 * 7)
# END.
Some Simple Maths
• Division is a lot cooler, we can do three kinds of division,
– Regular Division
– Integer Division
– Division Remainder
# PROGRAM RegularDivision:
print(“10 / 7 = “, 10 / 7)
# END.
# PROGRAM RegularDivision:
print(“10 / 7 = “, 10 / 7)
# END.
This should give us:
1.428571
# PROGRAM IntegerDivision:
print(“10 // 7 = “, 10 // 7)
# END.
# PROGRAM IntegerDivision:
print(“10 // 7 = “, 10 // 7)
# END.
This should give us:
1
# PROGRAM IntegerDivision:
print(“10 // 7 = “, 10 // 7)
# END.
This should give us:
1
which is how many times
7 divides evenly into 10
# PROGRAM DivisionRemainder:
print(“10 % 7 = “, 10 % 7)
# END.
# PROGRAM DivisionRemainder:
print(“10 % 7 = “, 10 % 7)
# END.
This should give us:
3
# PROGRAM DivisionRemainder:
print(“10 % 7 = “, 10 % 7)
# END.
This should give us:
3
which is what is left over
when we divide 7 into 10
Some Simple Maths
• Can you work this one out?
# PROGRAM DivisionProblem:
print(((10 / 7 – 10 // 7) * 7) + 7)
# END.
Python: Variables
Damian Gordon
Using Variables
• Variables are easy to use in Python, there is no need to declare
the type of the variable.
• Python will work it out for you (mostly!).
# PROGRAM VariableAssignment:
x = 6
# END.
Using Variables
• And if we want to check the value of the variable:
# PROGRAM VariablePrint:
x = 6
print(x)
# END.
Using Variables
• Let’s add 1 to x:
# PROGRAM AddOneVariablePrint:
x = 6
print(x + 1)
# END.
Using Variables
• Let’s try two variables:
# PROGRAM TwoVariablePrint:
x = 6
y = 5
print(x + y)
# END.
Using Variables
• If we want to move from integers to real numbers
# PROGRAM RealVariablePrint:
x = 6.56
print(x)
# END.
# PROGRAM AnotherRealVariablePrint:
x = 6.0
print(x)
# END.
Using Variables
• If we want to create character variables
# PROGRAM CharacterVariablePrint:
x = ‘@’
print(x)
# END.
# PROGRAM AnotherCharacterVariablePrint:
x = ‘5’
print(x)
# END.
Using Variables
• Now we can see that we can’t do arithmetic with characters:
# PROGRAM ErrorProgram:
x = ‘5’
print(x + 1)
# END.
Using Variables
• If we want to create String variables
# PROGRAM StringVariablePrint:
x = “This is a string”
print(x)
# END.
Using Variables
• To get input from the screen, we can do the following:
# PROGRAM PrintMessage:
print(“Please input a message: ”)
NewMsg = input()
print(NewMsg)
# END.
Using Variables
• Let’s do the converting temperature program:
# PROGRAM ConvertFromCelsiusToFahrenheit:
print(“Please input your temperature in C:”)
InputVal = int(input());
print(“That temperature in F is:”)
print((InputVal *2) + 30)
# END.
Convert Description Result
int(x) Convert variable into an integer, e.g.
x = “10”
int(x)
10
float(x) Convert variable into a real e.g.
x = “10.5”
float(x)
10.5
str(x) Convert variable into an string, e.g.
x = 10
str(x)
“10”
Using Variables
• The following words cannot be used as variable names:
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
A Special Note On
Boolean Variables
Boolean Variables
• In the original version of Python (1989), there was no
Boolean type, in Version 2.2.1 (2002)
True and False constants were added to the built-ins
(they were simply set to integer values of 1 and 0 and
weren't a different type.
Boolean Variables
• Finally in Version 2.3 (2003) True and False were added
in as constants to the __builtin__ module, making
them a core part of Python.
# PROGRAM BooleanVar:
x = True
print(x)
# END.
# PROGRAM BooleanVar:
x = False
print(x)
# END.
etc.
Selection:
IF Statement
Damian Gordon
Do you wish to print a receipt?
< YES NO >
Do you wish to print a receipt?
< YES NO >
In the interests of preserving the
environment, we prefer not to print a
receipt, but if you want to be a jerk, go
ahead.
< PRINT RECEIPT CONTINUE >
Selection
• What if we want to make a choice, for example, do we want to
add sugar or not to the tea?
Selection
• What if we want to make a choice, for example, do we want to
add sugar or not to the tea?
• We call this SELECTION.
IF Statement
• So, we could state this as:
IF (sugar is required)
THEN add sugar;
ELSE don’t add sugar;
ENDIF;
IF Statement
• Adding a selection statement in the program:
PROGRAM MakeACupOfTea:
Organise everything together;
Plug in kettle;
Put teabag in cup;
Put water into kettle;
Wait for kettle to boil;
Add water to cup;
Remove teabag with spoon/fork;
Add milk;
IF (sugar is required)
THEN add sugar;
ELSE do nothing;
ENDIF;
Serve;
END.
IF Statement
• Adding a selection statement in the program:
PROGRAM MakeACupOfTea:
Organise everything together;
Plug in kettle;
Put teabag in cup;
Put water into kettle;
Wait for kettle to boil;
Add water to cup;
Remove teabag with spoon/fork;
Add milk;
IF (sugar is required)
THEN add sugar;
ELSE do nothing;
ENDIF;
Serve;
END.
etc.
Boolean Logic
Damian Gordon
Boolean Logic
• You may have seen Boolean logic in another module already,
for this module, we’ll look at three Boolean operations:
– AND
– OR
– NOT
Boolean Logic
• Boolean operators are used in the conditions of:
– IF Statements
– WHILE Loops
– FOR Loops
Boolean Logic
• AND Operation
– The AND operation means that both parts of the condition must be
true for the condition to be satisfied.
– A=TRUE, B=TRUE => A AND B = TRUE
– A=FALSE, B=TRUE => A AND B = FALSE
– A=TRUE, B=FALSE => A AND B = FALSE
– A=FALSE, B=FALSE => A AND B = FALSE
Boolean Logic
• OR Operation
– The OR operation means that either (or both) parts of the condition
must be true for the condition to be satisfied.
– A=TRUE, B=TRUE => A OR B = TRUE
– A=FALSE, B=TRUE => A OR B = TRUE
– A=TRUE, B=FALSE => A OR B = TRUE
– A=FALSE, B=FALSE => A OR B = FALSE
Boolean Logic
• NOT Operation
– The NOT operation means that the outcome of the condition is
inverted.
– A=TRUE => NOT(A) = FALSE
– A=FALSE => NOT(A) = TRUE
etc.
Python: Selection
Damian Gordon
Python: IF statement
Damian Gordon
Python: IF statement
• In Python the general form of the IF statement is as follows:
if CONDITION:
STATEMENT(S)
else:
STATEMENT(S)
Python: IF statement
• But we’ll do:
if CONDITION:
# THEN
STATEMENT(S)
else:
STATEMENT(S)
# ENDIF;
# PROGRAM SimpleIfStatement:
x = 6
y = 7
if x > y:
# THEN
print(“x is bigger”)
else:
print(“y is bigger”)
# ENDIF;
# END.
Python: IF statement
• Let’s get the user to input the values of x and y:
# PROGRAM AnotherSimpleIfStatement:
x = int(input())
y = int(input())
if x > y:
# THEN
print(x, “is bigger than”, y)
else:
print(y, “is bigger than”, x)
# ENDIF;
# END.
Python: IF statement
• Let’s add some PRINT statements to make this clearer:
# PROGRAM AnotherSimpleIfStatementPrints:
print(“Please input the first value”)
x = int(input())
print(“Please second the second value”)
y = int(input())
if x > y:
# THEN
print(x, “is bigger than”, y)
else:
print(y, “is bigger than”, x)
# ENDIF;
# END.
Python: IF statement
• We can make this shorter:
# PROGRAM AnotherSimpleIfStatementPrintsShorter:
x = int(input(“Please input the first valuen”))
y = int(input(“Please second the second valuen”))
if x > y:
# THEN
print(x, “is bigger than”, y)
else:
print(y, “is bigger than”, x)
# ENDIF;
# END.
Python: IF statement
• Lets try the Odd or Even program:
# PROGRAM IsOddOrEven:
x = int(input(“Please input the numbern”))
if (x % 2) != 0:
# THEN
print(x, “is odd”)
else:
print(x, “is even”)
# ENDIF;
# END.
Operator Description
!= is not equal to
== is equal to
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
Python: IF statement
• Let’s try the bigger of three numbers:
# PROGRAM BiggerOfThree:
a = int(input(“Please input the first valuen”))
b = int(input(“Please second the second valuen”))
c = int(input(“Please second the third valuen”))
if a > b:
# THEN
if a > c:
# THEN
print(a, “is bigger than”, b, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, c)
# ENDIF;
else:
if b > c:
# THEN
print(b, “is bigger than”, a, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, b)
# ENDIF;
# ENDIF;
# END.
Python: ELIF statement
Damian Gordon
# PROGRAM BiggerOfThree:
a = int(input(“Please input the first valuen”))
b = int(input(“Please second the second valuen”))
c = int(input(“Please second the third valuen”))
if a > b:
# THEN
if a > c:
# THEN
print(a, “is bigger than”, b, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, c)
# ENDIF;
else:
if b > c:
# THEN
print(b, “is bigger than”, a, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, b)
# ENDIF;
# ENDIF;
# END.
# PROGRAM BiggerOfThree:
a = int(input(“Please input the first valuen”))
b = int(input(“Please second the second valuen”))
c = int(input(“Please second the third valuen”))
if a > b:
# THEN
if a > c:
# THEN
print(a, “is bigger than”, b, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, c)
# ENDIF;
else:
if b > c:
# THEN
print(b, “is bigger than”, a, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, b)
# ENDIF;
# ENDIF;
# END.
# PROGRAM BiggerOfThreeElif:
a = int(input(“Please input the first valuen”))
b = int(input(“Please second the second valuen”))
c = int(input(“Please second the third valuen”))
if a > b:
# THEN
if a > c:
# THEN
print(a, “is bigger than”, b, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, c)
# ENDIF;
elif b > c:
# THEN
print(b, “is bigger than”, a, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, b)
# ENDIF;
# END.
Python: IF-ELIF statement
• In Python the general form of the IF-ESIF statement is as follows:
if CONDITION:
STATEMENT(S)
elif CONDITION:
STATEMENT(S)
elif CONDITION:
STATEMENT(S)
else:
STATEMENT(S)
Python: IF-ELIF statement
• But we’ll do:
if CONDITION:
# THEN
STATEMENT(S)
elif CONDITION:
# THEN
STATEMENT(S)
elif CONDITION:
# THEN
STATEMENT(S)
else:
STATEMENT(S)
# ENDIF;
Python: IF-ELIF statement
• Let’s look at doing a multi-choice question program:
# PROGRAM MultiChoiceQuestion:
InputValue = input("Please input your answer:n")
if InputValue == "a":
# THEN
print("Wrong Answer")
elif InputValue == "b":
# THEN
print("Wrong Answer")
elif InputValue == "c":
# THEN
print("Right Answer")
elif InputValue == "d":
# THEN
print("Wrong Answer")
else:
print("Bad Option")
# ENDIF;
# END.
Python: IF-ELIF statement
• Here’s how to calculate a grade:
# PROGRAM GetGrade:
InputValue = int(input("Please input the first valuen"))
if InputValue >= 70:
# THEN
print("It's a first")
elif InputValue >= 60:
# THEN
print("It's a 2.1")
elif InputValue >= 50:
# THEN
print("It's a 2.2")
elif InputValue >= 40:
# THEN
print("It's a third")
else:
print("Dude, sorry, it's a fail")
# ENDIF;
# END.
etc.
Iteration:
WHILE Loop
Damian Gordon
WHILE Loop
• Consider the problem of searching for an entry in a phone
book with only SELECTION:
WHILE Loop
Get first entry;
IF (this is the correct entry)
THEN write down phone number;
ELSE get next entry;
IF (this is the correct entry)
THEN write done entry;
ELSE get next entry;
IF (this is the correct entry)
……………
WHILE Loop
• We may rewrite this using a WHILE Loop:
WHILE Loop
Get first entry;
Call this entry N;
WHILE (N is NOT the required entry)
DO Get next entry;
Call this entry N;
ENDWHILE;
WHILE Loop
START
END
Is A==6?
No
A = 1
Yes
Print A
A = A + 1
etc.
Python: Iteration
Damian Gordon
Python: Iteration
• We’ll consider four ways to do iteration:
– The WHILE loop
– The FOR loop
Python: WHILE loop
Damian Gordon
Python: WHILE loop
• The WHILE loop works as follows:
while CONDITION:
STATEMENTS
Python: WHILE loop
• But we’ll do:
while CONDITION:
# DO
STATEMENTS
# ENDWHILE;
Python: WHILE loop
• Let’s print out the numbers 1 to 5:
# PROGRAM Print1To5:
a = 1
while a != 6:
# DO
print(a)
a = a + 1
# ENDWHILE;
# END.
Python: WHILE loop
• Let’s print the sum of the numbers 1 to 5:
# PROGRAM Sum1To5:
a = 1
total = 0
while a != 6:
# DO
total = total + a
a = a + 1
# ENDWHILE;
print(total)
# END.
Python: WHILE loop
• Let’s do factorial:
Python: WHILE loop
• Let’s do factorial:
– Remember:
– 5! = 5*4*3*2*1
– 7! = 7*6 *5*4*3*2*1
– N! = N*(N-1)*(N-2)*…*2*1
# PROGRAM Factorial:
value = int(input("Please input value:"))
total = 1
while value != 0:
# DO
total = total * value
value = value - 1
# ENDWHILE;
print(total)
# END.
Python: FOR loop
Damian Gordon
Python: WHILE loop
• The FOR loop works as follows:
for RANGE:
STATEMENTS
Python: WHILE loop
• But we’ll do:
for RANGE:
# DO
STATEMENTS
# ENDFOR;
Python: FOR loop
• Let’s remember the program to print out the numbers 1 to 5:
# PROGRAM Print1To5:
a = 1
while a != 6:
# DO
print(a)
a = a + 1
# ENDWHILE;
# END.
Python: FOR loop
• We can do it as follows as well:
# PROGRAM Print1To5For:
for a in range(1,6):
# DO
print(a)
# ENDFOR;
# END.
etc.
Prime Numbers
Damian Gordon
Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
– What’s a prime number?
Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
– What’s a prime number?
– A number that’s only divisible by itself and 1, e.g. 7.
Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
– What’s a prime number?
– A number that’s only divisible by itself and 1, e.g. 7.
– Or to put it another way, every number other than itself and 1 gives a remainder, e.g. For
7, if 6, 5, 4, 3, and 2 give a remainder then 7 is prime.
Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
– What’s a prime number?
– A number that’s only divisible by itself and 1, e.g. 7.
– Or to put it another way, every number other than itself and 1 gives a remainder, e.g. For
7, if 6, 5, 4, 3, and 2 give a remainder then 7 is prime.
– So all we need to do is divide 7 by all numbers less than it but greater than one, and if
any of them have no remainder, we know it’s not prime.
Prime Numbers
• So,
• If the number is 7, as long as 6, 5, 4, 3, and 2 give a
remainder, 7 is prime.
• If the number is 9, we know that 8, 7, 6, 5, and 4, all give
remainders, but 3 does not give a remainder, it goes
evenly into 9 so we can say 9 is not prime
Prime Numbers
• So remember,
– if the number is 7, as long as 6, 5, 4, 3, and 2 give a remainder,
7 is prime.
• So, in general,
– if the number is A, as long as A-1, A-2, A-3, A-4, ... 2 give a
remainder, A is prime.
etc.
Fibonacci Numbers
Damian Gordon
Fibonacci Numbers
Fibonacci Numbers
• As seen in the Da Vinci Code:
Fibonacci Numbers
• The Fibonacci numbers are
numbers where the next number
in the sequence is the sum of the
previous two.
• The sequence starts with 1, 1,
• And then it’s 2
• Then 3
• Then 5
• Then 8
• Then 13
Leonardo Bonacci (aka Fibonacci)
• Born 1170.
• Born in Pisa, Italy
• Died 1250.
• An Italian mathematician, considered
to be "the most talented Western
mathematician of the Middle Ages".
• Introduced the sequence of Fibonacci
numbers which he used as an example
in Liber Abaci.
etc.
Python: Algorithms
Damian Gordon
Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
– What’s a prime number?
– A number that’s only divisible by itself and 1, e.g. 7.
– Or to put it another way, every number other than itself and 1 gives a remainder, e.g. For 7, if 6, 5,
4, 3, and 2 give a remainder then 7 is prime.
– So all we need to do is divide 7 by all numbers less than it but greater than one, and if any of them
have no remainder, we know it’s not prime.
Prime Numbers
• So,
• If the number is 7, as long as 6, 5, 4, 3, and 2 give a remainder,
7 is prime.
• If the number is 9, we know that 8, 7, 6, 5, and 4, all give
remainders, but 3 does not give a remainder, it goes evenly
into 9 so we can say 9 is not prime
Prime Numbers
• So remember,
– if the number is 7, as long as 6, 5, 4, 3, and 2 give a remainder, 7 is
prime.
• So, in general,
– if the number is A, as long as A-1, A-2, A-3, A-4, ... 2 give a remainder,
A is prime.
# PROGRAM CheckPrime:
a = int(input("Please input value:"))
b = a - 1
IsPrime = True
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
# ENDIF;
b = b - 1
# ENDWHILE;
if IsPrime:
# THEN
print(a, "is a prime number")
else:
print(a, "is not a prime number")
# ENDIF;
# END.
Fibonacci Numbers
• The Fibonacci numbers are numbers where the next number in
the sequence is the sum of the previous two.
• The sequence starts with 1, 1,
• And then it’s 2
• Then 3
• Then 5
• Then 8
• Then 13
# PROGRAM FibonacciNumbers:
a = int(input("Please input value:"))
FirstNum = 1
SecondNum = 1
while a != 1:
# DO
total = SecondNum + FirstNum
FirstNum = SecondNum
SecondNum = total
a = a - 1
# ENDWHILE;
print(total)
# END.
etc.
Modularisation
Damian Gordon
Modularisation
• Let’s imagine we had code as follows:
Modularisation
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
Modularisation
• And some bits of the code are repeated a few times
Modularisation
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
Modularisation
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
Modularisation
• It would be good if there was some way we could wrap
up frequently used commands into a single package, and
instead of having to rewrite the same code over and over
again, we could just call the package name.
• We can call these packages methods or functions
• (or subroutines or procedures)
Modularisation
• Let’s revisit our prime number algorithm again:
etc.
Python: Modularisation
Damian Gordon
Modularisation
• Remember the prime checker program:
# PROGRAM CheckPrime:
a = int(input("Please input value:"))
b = a - 1
IsPrime = True
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
# ENDIF;
b = b - 1
# ENDWHILE;
if IsPrime:
# THEN
print(a, "is a prime number")
else:
print(a, "is not a prime number")
# ENDIF;
# END.
# PROGRAM CheckPrime:
a = int(input("Please input value:"))
b = a - 1
IsPrime = True
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
# ENDIF;
b = b - 1
# ENDWHILE;
if IsPrime:
# THEN
print(a, "is a prime number")
else:
print(a, "is not a prime number")
# ENDIF;
# END.
Modularisation
• Let’s break this program into modules (functions).
#########################
# Prime Checking Module #
#########################
def IsItPrime():
a = int(input("Please input value: "))
b = a - 1
IsPrime = True
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
# ENDIF;
b = b - 1
# ENDWHILE;
return IsPrime
# END IsItPrime.
#########################
# Prime Checking Module #
#########################
def IsItPrime():
a = int(input("Please input value: "))
b = a - 1
IsPrime = True
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
# ENDIF;
b = b - 1
# ENDWHILE;
return IsPrime
# END IsItPrime.
################
# Main Program #
################
# PROGRAM CheckPrime:
if IsItPrime() == True:
# THEN
print("Prime number")
else:
print("Not a prime number")
# ENDIF;
# END.
Thanks…
Please contact me:
e: Damian.Gordon@dit.ie
t: @damiantgordon

More Related Content

What's hot

Pseudocode flowcharts
Pseudocode flowchartsPseudocode flowcharts
Pseudocode flowchartsnicky_walters
 
Power BI Overview
Power BI OverviewPower BI Overview
Power BI OverviewJames Serra
 
SharePoint and Teams Integration Better Together Webinar
SharePoint and Teams Integration Better Together WebinarSharePoint and Teams Integration Better Together Webinar
SharePoint and Teams Integration Better Together WebinarJoel Oleson
 
Office 365 Sales Presentation
Office 365 Sales PresentationOffice 365 Sales Presentation
Office 365 Sales PresentationThomas Perdana
 
Ppt full stack developer
Ppt full stack developerPpt full stack developer
Ppt full stack developerSudhirVarpe1
 
Flowchart and algorithem
Flowchart and algorithemFlowchart and algorithem
Flowchart and algorithemehsanullah786
 
Algorithm and Programming (Introduction of Algorithms)
Algorithm and Programming (Introduction of Algorithms)Algorithm and Programming (Introduction of Algorithms)
Algorithm and Programming (Introduction of Algorithms)Adam Mukharil Bachtiar
 
Agiliza tus procesos de negocio con Microsoft Power Platform
Agiliza tus procesos de negocio con Microsoft Power PlatformAgiliza tus procesos de negocio con Microsoft Power Platform
Agiliza tus procesos de negocio con Microsoft Power PlatformDQSconsulting
 
Introduction to D3.js
Introduction to D3.jsIntroduction to D3.js
Introduction to D3.jsKnoldus Inc.
 
Web Design 101
Web Design 101Web Design 101
Web Design 101T.S. Lim
 
Lecture 1 intro to web designing
Lecture 1  intro to web designingLecture 1  intro to web designing
Lecture 1 intro to web designingpalhaftab
 
Visual Basic Programming
Visual Basic ProgrammingVisual Basic Programming
Visual Basic ProgrammingOsama Yaseen
 
HOW CAN POWERAPPS AND MICROSOFT FLOW ALLOWS YOUR POWER USERS TO QUICKLY BUILD...
HOW CAN POWERAPPS AND MICROSOFT FLOW ALLOWS YOUR POWER USERS TO QUICKLY BUILD...HOW CAN POWERAPPS AND MICROSOFT FLOW ALLOWS YOUR POWER USERS TO QUICKLY BUILD...
HOW CAN POWERAPPS AND MICROSOFT FLOW ALLOWS YOUR POWER USERS TO QUICKLY BUILD...Sandro Pereira
 

What's hot (20)

Pseudocode flowcharts
Pseudocode flowchartsPseudocode flowcharts
Pseudocode flowcharts
 
Flowchart
FlowchartFlowchart
Flowchart
 
Power BI Overview
Power BI OverviewPower BI Overview
Power BI Overview
 
SharePoint and Teams Integration Better Together Webinar
SharePoint and Teams Integration Better Together WebinarSharePoint and Teams Integration Better Together Webinar
SharePoint and Teams Integration Better Together Webinar
 
Office 365 Sales Presentation
Office 365 Sales PresentationOffice 365 Sales Presentation
Office 365 Sales Presentation
 
Ppt full stack developer
Ppt full stack developerPpt full stack developer
Ppt full stack developer
 
Flowchart and algorithem
Flowchart and algorithemFlowchart and algorithem
Flowchart and algorithem
 
Algorithm and Programming (Introduction of Algorithms)
Algorithm and Programming (Introduction of Algorithms)Algorithm and Programming (Introduction of Algorithms)
Algorithm and Programming (Introduction of Algorithms)
 
Introduction to Web development
Introduction to Web developmentIntroduction to Web development
Introduction to Web development
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
Agiliza tus procesos de negocio con Microsoft Power Platform
Agiliza tus procesos de negocio con Microsoft Power PlatformAgiliza tus procesos de negocio con Microsoft Power Platform
Agiliza tus procesos de negocio con Microsoft Power Platform
 
3 algorithm-and-flowchart
3 algorithm-and-flowchart3 algorithm-and-flowchart
3 algorithm-and-flowchart
 
Introduction to D3.js
Introduction to D3.jsIntroduction to D3.js
Introduction to D3.js
 
Web Design (Tools)
Web Design (Tools)Web Design (Tools)
Web Design (Tools)
 
Web Design 101
Web Design 101Web Design 101
Web Design 101
 
Joomla REST API
Joomla REST APIJoomla REST API
Joomla REST API
 
Lecture 1 intro to web designing
Lecture 1  intro to web designingLecture 1  intro to web designing
Lecture 1 intro to web designing
 
Visual Basic Programming
Visual Basic ProgrammingVisual Basic Programming
Visual Basic Programming
 
HOW CAN POWERAPPS AND MICROSOFT FLOW ALLOWS YOUR POWER USERS TO QUICKLY BUILD...
HOW CAN POWERAPPS AND MICROSOFT FLOW ALLOWS YOUR POWER USERS TO QUICKLY BUILD...HOW CAN POWERAPPS AND MICROSOFT FLOW ALLOWS YOUR POWER USERS TO QUICKLY BUILD...
HOW CAN POWERAPPS AND MICROSOFT FLOW ALLOWS YOUR POWER USERS TO QUICKLY BUILD...
 
Belajar Java dasar
Belajar Java dasarBelajar Java dasar
Belajar Java dasar
 

Viewers also liked

What does your experiment look like?
What does your experiment look like? What does your experiment look like?
What does your experiment look like? Damian T. Gordon
 
Creating a logo program
Creating a logo programCreating a logo program
Creating a logo programayaabdullahs
 
Retention Of Students Enrolled
Retention Of Students EnrolledRetention Of Students Enrolled
Retention Of Students EnrolledDamian T. Gordon
 
Diagrams of the 2009 Claremont Report
Diagrams of the 2009 Claremont ReportDiagrams of the 2009 Claremont Report
Diagrams of the 2009 Claremont ReportDamian T. Gordon
 
Evaluation Q4- Use of Technology
Evaluation Q4- Use of TechnologyEvaluation Q4- Use of Technology
Evaluation Q4- Use of Technologyabcdsmile
 
Hackers and Hollywood: Extended scene 1
Hackers and Hollywood: Extended scene 1Hackers and Hollywood: Extended scene 1
Hackers and Hollywood: Extended scene 1Damian T. Gordon
 
Operating Systems - Memory Management
Operating Systems - Memory ManagementOperating Systems - Memory Management
Operating Systems - Memory ManagementDamian T. Gordon
 
Narrative ppnt minus trailers
Narrative ppnt minus trailersNarrative ppnt minus trailers
Narrative ppnt minus trailersabcdsmile
 
Python: The Iterator Pattern (Comprehensions)
Python: The Iterator Pattern (Comprehensions)Python: The Iterator Pattern (Comprehensions)
Python: The Iterator Pattern (Comprehensions)Damian T. Gordon
 
Template Logos for "Team Project" Module
Template Logos for "Team Project" ModuleTemplate Logos for "Team Project" Module
Template Logos for "Team Project" ModuleDamian T. Gordon
 
Learning Styles for Virtual Learning Environments
Learning Styles for Virtual Learning EnvironmentsLearning Styles for Virtual Learning Environments
Learning Styles for Virtual Learning EnvironmentsDamian T. Gordon
 
Concepts from Random Words
Concepts from Random WordsConcepts from Random Words
Concepts from Random WordsDamian T. Gordon
 
Computer Vision: Reflectance Analysis for Image Understanding
Computer Vision: Reflectance Analysis for Image UnderstandingComputer Vision: Reflectance Analysis for Image Understanding
Computer Vision: Reflectance Analysis for Image UnderstandingDamian T. Gordon
 
A Compendium of Creativity Tools
A Compendium of Creativity ToolsA Compendium of Creativity Tools
A Compendium of Creativity ToolsDamian T. Gordon
 

Viewers also liked (20)

What does your experiment look like?
What does your experiment look like? What does your experiment look like?
What does your experiment look like?
 
Creating a logo program
Creating a logo programCreating a logo program
Creating a logo program
 
The 3M Way
The 3M WayThe 3M Way
The 3M Way
 
Retention Of Students Enrolled
Retention Of Students EnrolledRetention Of Students Enrolled
Retention Of Students Enrolled
 
Diagrams of the 2009 Claremont Report
Diagrams of the 2009 Claremont ReportDiagrams of the 2009 Claremont Report
Diagrams of the 2009 Claremont Report
 
Evaluation Q4- Use of Technology
Evaluation Q4- Use of TechnologyEvaluation Q4- Use of Technology
Evaluation Q4- Use of Technology
 
Hackers and Hollywood: Extended scene 1
Hackers and Hollywood: Extended scene 1Hackers and Hollywood: Extended scene 1
Hackers and Hollywood: Extended scene 1
 
Operating Systems - Memory Management
Operating Systems - Memory ManagementOperating Systems - Memory Management
Operating Systems - Memory Management
 
Narrative ppnt minus trailers
Narrative ppnt minus trailersNarrative ppnt minus trailers
Narrative ppnt minus trailers
 
Object-Orientated Design
Object-Orientated DesignObject-Orientated Design
Object-Orientated Design
 
Python: The Iterator Pattern (Comprehensions)
Python: The Iterator Pattern (Comprehensions)Python: The Iterator Pattern (Comprehensions)
Python: The Iterator Pattern (Comprehensions)
 
Template Logos for "Team Project" Module
Template Logos for "Team Project" ModuleTemplate Logos for "Team Project" Module
Template Logos for "Team Project" Module
 
Why do we teach?
Why do we teach?Why do we teach?
Why do we teach?
 
Learning Styles for Virtual Learning Environments
Learning Styles for Virtual Learning EnvironmentsLearning Styles for Virtual Learning Environments
Learning Styles for Virtual Learning Environments
 
Python: Manager Objects
Python: Manager ObjectsPython: Manager Objects
Python: Manager Objects
 
Concepts from Random Words
Concepts from Random WordsConcepts from Random Words
Concepts from Random Words
 
Computer Vision: Reflectance Analysis for Image Understanding
Computer Vision: Reflectance Analysis for Image UnderstandingComputer Vision: Reflectance Analysis for Image Understanding
Computer Vision: Reflectance Analysis for Image Understanding
 
Creative Commons Sites
Creative Commons SitesCreative Commons Sites
Creative Commons Sites
 
A Compendium of Creativity Tools
A Compendium of Creativity ToolsA Compendium of Creativity Tools
A Compendium of Creativity Tools
 
Case Study Questions
Case Study QuestionsCase Study Questions
Case Study Questions
 

Similar to Introduction to Python fundamentals

Learn to Code with MIT App Inventor ( PDFDrive ).pdf
Learn to Code with MIT App Inventor ( PDFDrive ).pdfLearn to Code with MIT App Inventor ( PDFDrive ).pdf
Learn to Code with MIT App Inventor ( PDFDrive ).pdfNemoPalleschi
 
Speaking 'Development Language' (Or, how to get your hands dirty with technic...
Speaking 'Development Language' (Or, how to get your hands dirty with technic...Speaking 'Development Language' (Or, how to get your hands dirty with technic...
Speaking 'Development Language' (Or, how to get your hands dirty with technic...Julie Meloni
 
iPads in the Early Years Classroom
iPads in the Early Years ClassroomiPads in the Early Years Classroom
iPads in the Early Years Classroomkarlaholt
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from DataMosky Liu
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchartdipti reya
 
200,000 Lines Later: Our Journey to Manageable Puppet Code
200,000 Lines Later: Our Journey to Manageable Puppet Code200,000 Lines Later: Our Journey to Manageable Puppet Code
200,000 Lines Later: Our Journey to Manageable Puppet CodeDavid Danzilio
 
Ambidextrous Python - Introduction Python Libraries
Ambidextrous Python - Introduction Python Libraries Ambidextrous Python - Introduction Python Libraries
Ambidextrous Python - Introduction Python Libraries Anoop Thomas Mathew
 
ProductsProduct IDProduct NameCategoryUnit PriceUnit CostSpokesper.docx
ProductsProduct IDProduct NameCategoryUnit PriceUnit CostSpokesper.docxProductsProduct IDProduct NameCategoryUnit PriceUnit CostSpokesper.docx
ProductsProduct IDProduct NameCategoryUnit PriceUnit CostSpokesper.docxbriancrawford30935
 
Test Driven Infrastructure
Test Driven InfrastructureTest Driven Infrastructure
Test Driven InfrastructureArthur Maltson
 
Python_Introduction&DataType.pptx
Python_Introduction&DataType.pptxPython_Introduction&DataType.pptx
Python_Introduction&DataType.pptxHaythamBarakeh1
 
2022 - Delivering Powerful Technical Presentations.pdf
2022 - Delivering Powerful Technical Presentations.pdf2022 - Delivering Powerful Technical Presentations.pdf
2022 - Delivering Powerful Technical Presentations.pdfWesley Reisz
 
Creating A Math Podcast
Creating A Math PodcastCreating A Math Podcast
Creating A Math PodcastHouston ISD
 
BASIC_INTRODUCTION_TO_PYTHON_PROGRAMMING.pdf
BASIC_INTRODUCTION_TO_PYTHON_PROGRAMMING.pdfBASIC_INTRODUCTION_TO_PYTHON_PROGRAMMING.pdf
BASIC_INTRODUCTION_TO_PYTHON_PROGRAMMING.pdfashaks17
 
Mastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loopsMastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loopsRuth Marvin
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptxArpittripathi45
 
Golang, Python or C/C++, who wins
Golang, Python or C/C++, who wins Golang, Python or C/C++, who wins
Golang, Python or C/C++, who wins Obed N Muñoz
 

Similar to Introduction to Python fundamentals (20)

Learn to Code with MIT App Inventor ( PDFDrive ).pdf
Learn to Code with MIT App Inventor ( PDFDrive ).pdfLearn to Code with MIT App Inventor ( PDFDrive ).pdf
Learn to Code with MIT App Inventor ( PDFDrive ).pdf
 
Speaking 'Development Language' (Or, how to get your hands dirty with technic...
Speaking 'Development Language' (Or, how to get your hands dirty with technic...Speaking 'Development Language' (Or, how to get your hands dirty with technic...
Speaking 'Development Language' (Or, how to get your hands dirty with technic...
 
iPads in the Early Years Classroom
iPads in the Early Years ClassroomiPads in the Early Years Classroom
iPads in the Early Years Classroom
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from Data
 
Python overview
Python overviewPython overview
Python overview
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
 
Lec 01 introduction
Lec 01   introductionLec 01   introduction
Lec 01 introduction
 
200,000 Lines Later: Our Journey to Manageable Puppet Code
200,000 Lines Later: Our Journey to Manageable Puppet Code200,000 Lines Later: Our Journey to Manageable Puppet Code
200,000 Lines Later: Our Journey to Manageable Puppet Code
 
Ambidextrous Python - Introduction Python Libraries
Ambidextrous Python - Introduction Python Libraries Ambidextrous Python - Introduction Python Libraries
Ambidextrous Python - Introduction Python Libraries
 
ProductsProduct IDProduct NameCategoryUnit PriceUnit CostSpokesper.docx
ProductsProduct IDProduct NameCategoryUnit PriceUnit CostSpokesper.docxProductsProduct IDProduct NameCategoryUnit PriceUnit CostSpokesper.docx
ProductsProduct IDProduct NameCategoryUnit PriceUnit CostSpokesper.docx
 
Test Driven Infrastructure
Test Driven InfrastructureTest Driven Infrastructure
Test Driven Infrastructure
 
Python_Introduction&DataType.pptx
Python_Introduction&DataType.pptxPython_Introduction&DataType.pptx
Python_Introduction&DataType.pptx
 
2022 - Delivering Powerful Technical Presentations.pdf
2022 - Delivering Powerful Technical Presentations.pdf2022 - Delivering Powerful Technical Presentations.pdf
2022 - Delivering Powerful Technical Presentations.pdf
 
Podcasting101
Podcasting101Podcasting101
Podcasting101
 
Creating A Math Podcast
Creating A Math PodcastCreating A Math Podcast
Creating A Math Podcast
 
BASIC_INTRODUCTION_TO_PYTHON_PROGRAMMING.pdf
BASIC_INTRODUCTION_TO_PYTHON_PROGRAMMING.pdfBASIC_INTRODUCTION_TO_PYTHON_PROGRAMMING.pdf
BASIC_INTRODUCTION_TO_PYTHON_PROGRAMMING.pdf
 
Mastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loopsMastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loops
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
Golang, Python or C/C++, who wins
Golang, Python or C/C++, who wins Golang, Python or C/C++, who wins
Golang, Python or C/C++, who wins
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
 

More from Damian T. Gordon

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Damian T. Gordon
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to MicroservicesDamian T. Gordon
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud ComputingDamian T. Gordon
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSDamian T. Gordon
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOTDamian T. Gordon
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricDamian T. Gordon
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDamian T. Gordon
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSUREDamian T. Gordon
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDamian T. Gordon
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDamian T. Gordon
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDamian T. Gordon
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsDamian T. Gordon
 

More from Damian T. Gordon (20)

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
REST and RESTful Services
REST and RESTful ServicesREST and RESTful Services
REST and RESTful Services
 
Serverless Computing
Serverless ComputingServerless Computing
Serverless Computing
 
Cloud Identity Management
Cloud Identity ManagementCloud Identity Management
Cloud Identity Management
 
Containers and Docker
Containers and DockerContainers and Docker
Containers and Docker
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud Computing
 
Introduction to ChatGPT
Introduction to ChatGPTIntroduction to ChatGPT
Introduction to ChatGPT
 
How to Argue Logically
How to Argue LogicallyHow to Argue Logically
How to Argue Logically
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONS
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOT
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson Rubric
 
Evaluating Teaching: LORI
Evaluating Teaching: LORIEvaluating Teaching: LORI
Evaluating Teaching: LORI
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause Procedure
 
Designing Teaching: ADDIE
Designing Teaching: ADDIEDesigning Teaching: ADDIE
Designing Teaching: ADDIE
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSURE
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning Types
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of Instruction
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration Theory
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some Considerations
 

Recently uploaded

Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Recently uploaded (20)

Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

Introduction to Python fundamentals

  • 1. Introduction to Python Damian Gordon e: Damian.Gordon@dit.ie t: @damiantgordon
  • 2. Introduction • This talk is aimed at people who are new to Python, to teach them basic operations and algorithms in Python. • We will look at SEQUENCE, SELECTION, and ITERATION. • We will look at some COMMON ALGORITHMS.
  • 3. Your Speaker is… • Lecturer for 15 years in Dublin Institute of Technology • Educational Advisor on a number of EU projects • Research Interests – Education, Assistive Technology, Creativity, Hacking • previously Developer, Analyst, IT consultant • Programming for over 30 years • I absolutely love Python
  • 4. http://www.damiantgordon.com/python/ Includes: • Videos • PowerPoints • Over 100 code samples • Exercises • External links
  • 5. The Python Programming Language • Python was developed by Guido van Rossum in the Netherlands in 1989. • Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, Benevolent Dictator for Life (BDFL).
  • 6. The Python Programming Language • Python is named for the British comedy group Monty Python. • The main members of the group are Eric Idle, Terry Jones, John Cleese, Michael Palin, Graham Chapman, and Terry Gilliam.
  • 7. The Python Programming Language • Python is named for the British comedy group Monty Python. • The main members of the group are Eric Idle, Terry Jones, John Cleese, Michael Palin, Graham Chapman, and Terry Gilliam.
  • 8. The Python Programming Language 2000 Ver 2 2008 Ver 3 1989 Ver 1
  • 9. The Python Programming Language • Python is a multi-paradigm programming language: – structured programming – object-oriented programming – functional programming – aspect-oriented programming – design by contract – logic programming
  • 10. The Python Programming Language • Python uses dynamic typing and a combination of reference counting and a cycle-detecting garbage collector for memory management. An important feature of Python is dynamic name resolution (late binding), which binds method and variable names during program execution.
  • 11. The Python Programming Language • Rather than requiring all desired functionality to be built into the language's core, Python was designed to be highly extensible. Python can also be embedded in existing applications that need a programmable interface. This design of a small core language with a large standard library and an easily extensible interpreter was intended by Van Rossum from the very start
  • 12. The Python Programming Language • Since 2003, Python has consistently ranked in the top ten most popular programming languages as measured by the TIOBE Programming Community Index. As of September 2015, it is in the fifth position. It was ranked as Programming Language of the Year for the year 2007 and 2010.
  • 13. What does Python look like?
  • 14. # PROGRAM CheckPrime: ################## # ERROR CHECKING # ################## c = str(input("Do you want error checking on? (y/n)")) if c == 'y': # THEN MyErrorCheck = True else: MyErrorCheck = False # ENDIF; ################## # PRIME CHECKING # ################## a = int(input("Please input value:")) b = a - 1 IsPrime = True Part 1 of 3
  • 15. while b != 1: # DO if a % b == 0: # THEN IsPrime = False if MyErrorCheck == True: # THEN print("*** Division with no remainder found, with ", b, "*****”) # ENDIF; # ENDIF; if MyErrorCheck == True: # THEN print(">> a is ",a,">> b is ",b, ">> IsPrime is ",IsPrime) # ENDIF; b = b - 1 # ENDWHILE; Part 2 of 3
  • 16. if IsPrime: # THEN print(a, "is a prime number") else: print(a, "is not a prime number") # ENDIF; # END. Part 3 of 3
  • 17. The Python Programming Language • Organizations that use Python include Google, Yahoo!, CERN, and NASA. • Python can serve as a scripting language for web applications • Python has been embedded in a number of software products as a scripting language, including in finite element method software such as Abaqus, 3D parametric modeler like FreeCAD, 3D animation packages such as 3ds Max, Blender, Cinema 4D, Lightwave, Houdini, Maya, modo, MotionBuilder, Softimage, the visual effects compositor Nuke, 2D imaging programs like GIMP, Inkscape, Scribus and Paint Shop Pro, and musical notation program or scorewriter capella.
  • 18. IDLE
  • 19. etc.
  • 20. PEP 20 – The Zen of Python Tim Peters
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 42. Top-Down Design • Top-Down Design (also known as stepwise design) is breaking down a problem into steps. • In Top-down Design an overview of the problem is described first, specifying but not detailing any first-level sub-steps. • Each sub-step is then refined in yet greater detail, sometimes in many additional sub-steps, until the entire specification is reduced to basic elements.
  • 43. Example • Making a Cup of Tea
  • 44. Example 1. Organise everything together 2. Plug in kettle 3. Put teabag in cup 4. Put water into kettle 5. Turn on kettle 6. Wait for kettle to boil 7. Add boiling water to cup 8. Remove teabag with spoon/fork 9. Add milk and/or sugar 10. Serve
  • 45. Example 1. Organise everything together 2. Plug in kettle 3. Put teabag in cup 4. Put water into kettle 5. Turn on kettle 6. Wait for kettle to boil 7. Add boiling water to cup 8. Remove teabag with spoon/fork 9. Add milk and/or sugar 10. Serve
  • 46. Example 1. Organise everything together 2. Plug in kettle 3. Put teabag in cup 4. Put water into kettle 5. Turn on kettle 6. Wait for kettle to boil 7. Add boiling water to cup 8. Remove teabag with spoon/fork 9. Add milk and/or sugar 10. Serve
  • 47. Example 1. Organise everything together 2. Plug in kettle 3. Put teabag in cup 4. Put water into kettle 5. Turn on kettle 6. Wait for kettle to boil 7. Add boiling water to cup 8. Remove teabag with spoon/fork 9. Add milk and/or sugar 10. Serve
  • 48. Example 1. Organise everything together 2. Plug in kettle 3. Put teabag in cup 4. Put water into kettle 5. Turn on kettle 6. Wait for kettle to boil 7. Add boiling water to cup 8. Remove teabag with spoon/fork 9. Add milk and/or sugar 10. Serve
  • 49. Example 1. Organise everything together 2. Plug in kettle 3. Put teabag in cup 4. Put water into kettle 5. Turn on kettle 6. Wait for kettle to boil 7. Add boiling water to cup 8. Remove teabag with spoon/fork 9. Add milk and/or sugar 10. Serve
  • 50. Example 1. Organise everything together 2. Plug in kettle 3. Put teabag in cup 4. Put water into kettle 5. Turn on kettle 6. Wait for kettle to boil 7. Add boiling water to cup 8. Remove teabag with spoon/fork 9. Add milk and/or sugar 10. Serve
  • 51. Example 1. Organise everything together 2. Plug in kettle 3. Put teabag in cup 4. Put water into kettle 5. Turn on kettle 6. Wait for kettle to boil 7. Add boiling water to cup 8. Remove teabag with spoon/fork 9. Add milk and/or sugar 10. Serve
  • 52. Example 1. Organise everything together 2. Plug in kettle 3. Put teabag in cup 4. Put water into kettle 5. Turn on kettle 6. Wait for kettle to boil 7. Add boiling water to cup 8. Remove teabag with spoon/fork 9. Add milk and/or sugar 10. Serve
  • 53. Example 1. Organise everything together 2. Plug in kettle 3. Put teabag in cup 4. Put water into kettle 5. Turn on kettle 6. Wait for kettle to boil 7. Add boiling water to cup 8. Remove teabag with spoon/fork 9. Add milk and/or sugar 10. Serve
  • 54. Example : Step-wise Refinement Step-wise refinement of step 1 (Organise everything together) 1.1 Get a cup 1.2 Get tea bags 1.3 Get sugar 1.4 Get milk 1.5 Get spoon/fork.
  • 55. Example : Step-wise Refinement Step-wise refinement of step 2 (Plug in kettle) 2.1 Locate plug of kettle 2.2 Insert plug into electrical outlet
  • 56. Example : Step-wise Refinement Step-wise refinement of step 3 (Put teabag in cup) 3.1 Take teabag from box 3.2 Put it into cup
  • 57. Example : Step-wise Refinement Step-wise refinement of step 4 (Put water into kettle) 4.1 Bring kettle to tap 4.2 Put kettle under water 4.3 Turn on tap 4.4 Wait for kettle to be full 4.5 Turn off tap
  • 58. Example : Step-wise Refinement Step-wise refinement of step 5 (Turn on kettle) 5.1 Depress switch on kettle
  • 60. etc.
  • 62. Variables • We know what a variable is from maths. • We’ve all seen this sort of thing in algebra: 2x – 10 = 0 2x = 10 X = 5
  • 63. Variables • We know what a variable is from maths. • We’ve all seen this sort of thing in algebra: 2x – 10 = 0 2x = 10 X = 5
  • 64. Variables • We know what a variable is from maths. • We’ve all seen this sort of thing in algebra: 2x – 10 = 0 2x = 10 X = 5
  • 65. Variables • We know what a variable is from maths. • We’ve all seen this sort of thing in algebra: 2x – 10 = 0 2x = 10 X = 5
  • 66. Variables • We know what a variable is from maths. • We’ve all seen this sort of thing in algebra: 2x – 10 = 0 2x = 10 X = 5
  • 67. Variables • …and in another problem we might have: 3x + 12 = 0 3x = -12 X = -4
  • 68. Variables • So a variable contains a value, and that value changes over time.
  • 69. Variables • …like your bank balance!
  • 70. Variables • In programming, we tell the computer the value of a variable • So, for example, x <- 5 means “X gets the value 5” or “X is assigned 5”
  • 71. Variables • In programming, we tell the computer the value of a variable • So, for example, x = 5 means “X gets the value 5” or “X is assigned 5”
  • 72. Variables • In programming, we tell the computer the value of a variable • So, for example, x = 5 means “X gets the value 5” or “X is assigned 5” X
  • 73. Variables • In programming, we tell the computer the value of a variable • So, for example, x = 5 means “X gets the value 5” or “X is assigned 5” X 5
  • 74. Variables • And later we can say something like: x = 8 means “X gets the value 8” or “X is assigned 8”
  • 75. Variables • If we want to add one to a variable: x = x + 1 means “increment X” or “X is incremented by 1” X(new) 5 X(old) 4 +1
  • 76. Variables • We can create a new variable Y y = x means “Y gets the value of X” or “Y is assigned the value of X” Y X 6 6
  • 77. Variables • We can also say: y = x + 1 means “Y gets the value of x plus 1” or “Y is assigned the value of x plus 1” Y X 6 7 +1
  • 78. Variables • All of these variables are integers • They are all whole numbers
  • 79. Variables • Let’s look at numbers with decimal points: P = 3.14159 means “p gets the value of 3.14159” or “p is assigned the value of 3.14159”
  • 80. Variables • We should really give this a better name: Pi = 3.14159 means “Pi gets the value of 3.14159” or “Pi is assigned the value of 3.14159”
  • 81. Variables • We can also have single character variables: Vitamin = ‘B’ means “Vitamin gets the value of B” or “Vitamin is assigned the value of B”
  • 82. Variables • We can also have single character variables: RoomNumber = ‘2’ means “RoomNumber gets the value of 2” or “RoomNumber is assigned the value of 2”
  • 83. Variables • We can also have a string of characters: Pet = “Dog” means “Pet gets the value of Dog” or “Pet is assigned the value of Dog”
  • 84. Variables • We also have a special type, called BOOLEAN • It has only two values, TRUE or FALSE IsWeekend = False means “IsWeekend gets the value of FALSE” or “IsWeekend is assigned the value of FALSE”
  • 85. etc.
  • 87. Your first Python program • When learning a new computer programming language, the first thing typically taught is how to write a message to the screen saying “Hello, World”. • Let’s see how to do that:
  • 90. # HelloWorldProgram – Version 1 # A program to print out “Hello, World” # Written by: Damian Gordon # Date: 10/09/2015 # PROGRAM HelloWorldProgram: print(“Hello, World”) # END.
  • 91. The PRINT statement • If we want to add a blank line after our print statement:
  • 93. # PROGRAM HelloWorldProgram: print(“Hello, World”) # END. # PROGRAM HelloWorldProgramNewLine: print(“Hello, Worldn”) # END.
  • 94. The PRINT statement • To print out two lines of text we do:
  • 95. # PROGRAM HelloWorldProgramTwoLines: print(“Hello, World”) print(“I’m here”) # END.
  • 96. The PRINT statement • To join two strings together:
  • 97. # PROGRAM HelloWorldProgramJoined: print(“Hello, World” + “ I’m here”) # END.
  • 98. The PRINT statement • To print out the same message 10 times:
  • 100. The PRINT statement • To print out the same message 10 times, each one on a new line:
  • 102. Code Description Print a backslash ’ Print a single quote ” Print a double quote a Play a beep n Print a new line t Print a tab
  • 104. Some Simple Maths • Let’s look at some simple maths first:
  • 106. Some Simple Maths • Let’s make that a bit more fancy
  • 107. # PROGRAM AddingNumbers: print(“10 + 7 = “, 10 + 7) # END.
  • 108. Some Simple Maths • Let’s try subtraction:
  • 109. # PROGRAM SubtractingNumbers: print(“10 - 7 = “, 10 - 7) # END.
  • 110. Some Simple Maths • Let’s try multiplication:
  • 111. # PROGRAM MultiplyingNumbers: print(“10 * 7 = “, 10 * 7) # END.
  • 112. Some Simple Maths • Division is a lot cooler, we can do three kinds of division, – Regular Division – Integer Division – Division Remainder
  • 113. # PROGRAM RegularDivision: print(“10 / 7 = “, 10 / 7) # END.
  • 114. # PROGRAM RegularDivision: print(“10 / 7 = “, 10 / 7) # END. This should give us: 1.428571
  • 115. # PROGRAM IntegerDivision: print(“10 // 7 = “, 10 // 7) # END.
  • 116. # PROGRAM IntegerDivision: print(“10 // 7 = “, 10 // 7) # END. This should give us: 1
  • 117. # PROGRAM IntegerDivision: print(“10 // 7 = “, 10 // 7) # END. This should give us: 1 which is how many times 7 divides evenly into 10
  • 118. # PROGRAM DivisionRemainder: print(“10 % 7 = “, 10 % 7) # END.
  • 119. # PROGRAM DivisionRemainder: print(“10 % 7 = “, 10 % 7) # END. This should give us: 3
  • 120. # PROGRAM DivisionRemainder: print(“10 % 7 = “, 10 % 7) # END. This should give us: 3 which is what is left over when we divide 7 into 10
  • 121. Some Simple Maths • Can you work this one out?
  • 122. # PROGRAM DivisionProblem: print(((10 / 7 – 10 // 7) * 7) + 7) # END.
  • 124. Using Variables • Variables are easy to use in Python, there is no need to declare the type of the variable. • Python will work it out for you (mostly!).
  • 126. Using Variables • And if we want to check the value of the variable:
  • 127. # PROGRAM VariablePrint: x = 6 print(x) # END.
  • 129. # PROGRAM AddOneVariablePrint: x = 6 print(x + 1) # END.
  • 130. Using Variables • Let’s try two variables:
  • 131. # PROGRAM TwoVariablePrint: x = 6 y = 5 print(x + y) # END.
  • 132. Using Variables • If we want to move from integers to real numbers
  • 133. # PROGRAM RealVariablePrint: x = 6.56 print(x) # END.
  • 134. # PROGRAM AnotherRealVariablePrint: x = 6.0 print(x) # END.
  • 135. Using Variables • If we want to create character variables
  • 136. # PROGRAM CharacterVariablePrint: x = ‘@’ print(x) # END.
  • 137. # PROGRAM AnotherCharacterVariablePrint: x = ‘5’ print(x) # END.
  • 138. Using Variables • Now we can see that we can’t do arithmetic with characters:
  • 139. # PROGRAM ErrorProgram: x = ‘5’ print(x + 1) # END.
  • 140. Using Variables • If we want to create String variables
  • 141. # PROGRAM StringVariablePrint: x = “This is a string” print(x) # END.
  • 142. Using Variables • To get input from the screen, we can do the following:
  • 143. # PROGRAM PrintMessage: print(“Please input a message: ”) NewMsg = input() print(NewMsg) # END.
  • 144. Using Variables • Let’s do the converting temperature program:
  • 145. # PROGRAM ConvertFromCelsiusToFahrenheit: print(“Please input your temperature in C:”) InputVal = int(input()); print(“That temperature in F is:”) print((InputVal *2) + 30) # END.
  • 146. Convert Description Result int(x) Convert variable into an integer, e.g. x = “10” int(x) 10 float(x) Convert variable into a real e.g. x = “10.5” float(x) 10.5 str(x) Convert variable into an string, e.g. x = 10 str(x) “10”
  • 147. Using Variables • The following words cannot be used as variable names: and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try
  • 148. A Special Note On Boolean Variables
  • 149. Boolean Variables • In the original version of Python (1989), there was no Boolean type, in Version 2.2.1 (2002) True and False constants were added to the built-ins (they were simply set to integer values of 1 and 0 and weren't a different type.
  • 150. Boolean Variables • Finally in Version 2.3 (2003) True and False were added in as constants to the __builtin__ module, making them a core part of Python.
  • 151. # PROGRAM BooleanVar: x = True print(x) # END.
  • 152. # PROGRAM BooleanVar: x = False print(x) # END.
  • 153. etc.
  • 155.
  • 156. Do you wish to print a receipt? < YES NO >
  • 157. Do you wish to print a receipt? < YES NO > In the interests of preserving the environment, we prefer not to print a receipt, but if you want to be a jerk, go ahead. < PRINT RECEIPT CONTINUE >
  • 158. Selection • What if we want to make a choice, for example, do we want to add sugar or not to the tea?
  • 159. Selection • What if we want to make a choice, for example, do we want to add sugar or not to the tea? • We call this SELECTION.
  • 160. IF Statement • So, we could state this as: IF (sugar is required) THEN add sugar; ELSE don’t add sugar; ENDIF;
  • 161. IF Statement • Adding a selection statement in the program: PROGRAM MakeACupOfTea: Organise everything together; Plug in kettle; Put teabag in cup; Put water into kettle; Wait for kettle to boil; Add water to cup; Remove teabag with spoon/fork; Add milk; IF (sugar is required) THEN add sugar; ELSE do nothing; ENDIF; Serve; END.
  • 162. IF Statement • Adding a selection statement in the program: PROGRAM MakeACupOfTea: Organise everything together; Plug in kettle; Put teabag in cup; Put water into kettle; Wait for kettle to boil; Add water to cup; Remove teabag with spoon/fork; Add milk; IF (sugar is required) THEN add sugar; ELSE do nothing; ENDIF; Serve; END.
  • 163. etc.
  • 165. Boolean Logic • You may have seen Boolean logic in another module already, for this module, we’ll look at three Boolean operations: – AND – OR – NOT
  • 166. Boolean Logic • Boolean operators are used in the conditions of: – IF Statements – WHILE Loops – FOR Loops
  • 167. Boolean Logic • AND Operation – The AND operation means that both parts of the condition must be true for the condition to be satisfied. – A=TRUE, B=TRUE => A AND B = TRUE – A=FALSE, B=TRUE => A AND B = FALSE – A=TRUE, B=FALSE => A AND B = FALSE – A=FALSE, B=FALSE => A AND B = FALSE
  • 168. Boolean Logic • OR Operation – The OR operation means that either (or both) parts of the condition must be true for the condition to be satisfied. – A=TRUE, B=TRUE => A OR B = TRUE – A=FALSE, B=TRUE => A OR B = TRUE – A=TRUE, B=FALSE => A OR B = TRUE – A=FALSE, B=FALSE => A OR B = FALSE
  • 169. Boolean Logic • NOT Operation – The NOT operation means that the outcome of the condition is inverted. – A=TRUE => NOT(A) = FALSE – A=FALSE => NOT(A) = TRUE
  • 170. etc.
  • 173. Python: IF statement • In Python the general form of the IF statement is as follows: if CONDITION: STATEMENT(S) else: STATEMENT(S)
  • 174. Python: IF statement • But we’ll do: if CONDITION: # THEN STATEMENT(S) else: STATEMENT(S) # ENDIF;
  • 175. # PROGRAM SimpleIfStatement: x = 6 y = 7 if x > y: # THEN print(“x is bigger”) else: print(“y is bigger”) # ENDIF; # END.
  • 176. Python: IF statement • Let’s get the user to input the values of x and y:
  • 177. # PROGRAM AnotherSimpleIfStatement: x = int(input()) y = int(input()) if x > y: # THEN print(x, “is bigger than”, y) else: print(y, “is bigger than”, x) # ENDIF; # END.
  • 178. Python: IF statement • Let’s add some PRINT statements to make this clearer:
  • 179. # PROGRAM AnotherSimpleIfStatementPrints: print(“Please input the first value”) x = int(input()) print(“Please second the second value”) y = int(input()) if x > y: # THEN print(x, “is bigger than”, y) else: print(y, “is bigger than”, x) # ENDIF; # END.
  • 180. Python: IF statement • We can make this shorter:
  • 181. # PROGRAM AnotherSimpleIfStatementPrintsShorter: x = int(input(“Please input the first valuen”)) y = int(input(“Please second the second valuen”)) if x > y: # THEN print(x, “is bigger than”, y) else: print(y, “is bigger than”, x) # ENDIF; # END.
  • 182. Python: IF statement • Lets try the Odd or Even program:
  • 183. # PROGRAM IsOddOrEven: x = int(input(“Please input the numbern”)) if (x % 2) != 0: # THEN print(x, “is odd”) else: print(x, “is even”) # ENDIF; # END.
  • 184. Operator Description != is not equal to == is equal to > is greater than < is less than >= is greater than or equal to <= is less than or equal to
  • 185. Python: IF statement • Let’s try the bigger of three numbers:
  • 186. # PROGRAM BiggerOfThree: a = int(input(“Please input the first valuen”)) b = int(input(“Please second the second valuen”)) c = int(input(“Please second the third valuen”)) if a > b: # THEN if a > c: # THEN print(a, “is bigger than”, b, “ and ”, c) else: print(c, “is bigger than”, a, “ and ”, c) # ENDIF; else: if b > c: # THEN print(b, “is bigger than”, a, “ and ”, c) else: print(c, “is bigger than”, a, “ and ”, b) # ENDIF; # ENDIF; # END.
  • 188. # PROGRAM BiggerOfThree: a = int(input(“Please input the first valuen”)) b = int(input(“Please second the second valuen”)) c = int(input(“Please second the third valuen”)) if a > b: # THEN if a > c: # THEN print(a, “is bigger than”, b, “ and ”, c) else: print(c, “is bigger than”, a, “ and ”, c) # ENDIF; else: if b > c: # THEN print(b, “is bigger than”, a, “ and ”, c) else: print(c, “is bigger than”, a, “ and ”, b) # ENDIF; # ENDIF; # END.
  • 189. # PROGRAM BiggerOfThree: a = int(input(“Please input the first valuen”)) b = int(input(“Please second the second valuen”)) c = int(input(“Please second the third valuen”)) if a > b: # THEN if a > c: # THEN print(a, “is bigger than”, b, “ and ”, c) else: print(c, “is bigger than”, a, “ and ”, c) # ENDIF; else: if b > c: # THEN print(b, “is bigger than”, a, “ and ”, c) else: print(c, “is bigger than”, a, “ and ”, b) # ENDIF; # ENDIF; # END.
  • 190. # PROGRAM BiggerOfThreeElif: a = int(input(“Please input the first valuen”)) b = int(input(“Please second the second valuen”)) c = int(input(“Please second the third valuen”)) if a > b: # THEN if a > c: # THEN print(a, “is bigger than”, b, “ and ”, c) else: print(c, “is bigger than”, a, “ and ”, c) # ENDIF; elif b > c: # THEN print(b, “is bigger than”, a, “ and ”, c) else: print(c, “is bigger than”, a, “ and ”, b) # ENDIF; # END.
  • 191. Python: IF-ELIF statement • In Python the general form of the IF-ESIF statement is as follows: if CONDITION: STATEMENT(S) elif CONDITION: STATEMENT(S) elif CONDITION: STATEMENT(S) else: STATEMENT(S)
  • 192. Python: IF-ELIF statement • But we’ll do: if CONDITION: # THEN STATEMENT(S) elif CONDITION: # THEN STATEMENT(S) elif CONDITION: # THEN STATEMENT(S) else: STATEMENT(S) # ENDIF;
  • 193. Python: IF-ELIF statement • Let’s look at doing a multi-choice question program:
  • 194. # PROGRAM MultiChoiceQuestion: InputValue = input("Please input your answer:n") if InputValue == "a": # THEN print("Wrong Answer") elif InputValue == "b": # THEN print("Wrong Answer") elif InputValue == "c": # THEN print("Right Answer") elif InputValue == "d": # THEN print("Wrong Answer") else: print("Bad Option") # ENDIF; # END.
  • 195. Python: IF-ELIF statement • Here’s how to calculate a grade:
  • 196. # PROGRAM GetGrade: InputValue = int(input("Please input the first valuen")) if InputValue >= 70: # THEN print("It's a first") elif InputValue >= 60: # THEN print("It's a 2.1") elif InputValue >= 50: # THEN print("It's a 2.2") elif InputValue >= 40: # THEN print("It's a third") else: print("Dude, sorry, it's a fail") # ENDIF; # END.
  • 197. etc.
  • 199. WHILE Loop • Consider the problem of searching for an entry in a phone book with only SELECTION:
  • 200. WHILE Loop Get first entry; IF (this is the correct entry) THEN write down phone number; ELSE get next entry; IF (this is the correct entry) THEN write done entry; ELSE get next entry; IF (this is the correct entry) ……………
  • 201. WHILE Loop • We may rewrite this using a WHILE Loop:
  • 202. WHILE Loop Get first entry; Call this entry N; WHILE (N is NOT the required entry) DO Get next entry; Call this entry N; ENDWHILE;
  • 203. WHILE Loop START END Is A==6? No A = 1 Yes Print A A = A + 1
  • 204. etc.
  • 206. Python: Iteration • We’ll consider four ways to do iteration: – The WHILE loop – The FOR loop
  • 208. Python: WHILE loop • The WHILE loop works as follows: while CONDITION: STATEMENTS
  • 209. Python: WHILE loop • But we’ll do: while CONDITION: # DO STATEMENTS # ENDWHILE;
  • 210. Python: WHILE loop • Let’s print out the numbers 1 to 5:
  • 211. # PROGRAM Print1To5: a = 1 while a != 6: # DO print(a) a = a + 1 # ENDWHILE; # END.
  • 212. Python: WHILE loop • Let’s print the sum of the numbers 1 to 5:
  • 213. # PROGRAM Sum1To5: a = 1 total = 0 while a != 6: # DO total = total + a a = a + 1 # ENDWHILE; print(total) # END.
  • 214. Python: WHILE loop • Let’s do factorial:
  • 215. Python: WHILE loop • Let’s do factorial: – Remember: – 5! = 5*4*3*2*1 – 7! = 7*6 *5*4*3*2*1 – N! = N*(N-1)*(N-2)*…*2*1
  • 216. # PROGRAM Factorial: value = int(input("Please input value:")) total = 1 while value != 0: # DO total = total * value value = value - 1 # ENDWHILE; print(total) # END.
  • 218. Python: WHILE loop • The FOR loop works as follows: for RANGE: STATEMENTS
  • 219. Python: WHILE loop • But we’ll do: for RANGE: # DO STATEMENTS # ENDFOR;
  • 220. Python: FOR loop • Let’s remember the program to print out the numbers 1 to 5:
  • 221. # PROGRAM Print1To5: a = 1 while a != 6: # DO print(a) a = a + 1 # ENDWHILE; # END.
  • 222. Python: FOR loop • We can do it as follows as well:
  • 223. # PROGRAM Print1To5For: for a in range(1,6): # DO print(a) # ENDFOR; # END.
  • 224. etc.
  • 226. Prime Numbers • So let’s say we want to express the following algorithm: – Read in a number and check if it’s a prime number.
  • 227. Prime Numbers • So let’s say we want to express the following algorithm: – Read in a number and check if it’s a prime number. – What’s a prime number?
  • 228. Prime Numbers • So let’s say we want to express the following algorithm: – Read in a number and check if it’s a prime number. – What’s a prime number? – A number that’s only divisible by itself and 1, e.g. 7.
  • 229. Prime Numbers • So let’s say we want to express the following algorithm: – Read in a number and check if it’s a prime number. – What’s a prime number? – A number that’s only divisible by itself and 1, e.g. 7. – Or to put it another way, every number other than itself and 1 gives a remainder, e.g. For 7, if 6, 5, 4, 3, and 2 give a remainder then 7 is prime.
  • 230. Prime Numbers • So let’s say we want to express the following algorithm: – Read in a number and check if it’s a prime number. – What’s a prime number? – A number that’s only divisible by itself and 1, e.g. 7. – Or to put it another way, every number other than itself and 1 gives a remainder, e.g. For 7, if 6, 5, 4, 3, and 2 give a remainder then 7 is prime. – So all we need to do is divide 7 by all numbers less than it but greater than one, and if any of them have no remainder, we know it’s not prime.
  • 231. Prime Numbers • So, • If the number is 7, as long as 6, 5, 4, 3, and 2 give a remainder, 7 is prime. • If the number is 9, we know that 8, 7, 6, 5, and 4, all give remainders, but 3 does not give a remainder, it goes evenly into 9 so we can say 9 is not prime
  • 232. Prime Numbers • So remember, – if the number is 7, as long as 6, 5, 4, 3, and 2 give a remainder, 7 is prime. • So, in general, – if the number is A, as long as A-1, A-2, A-3, A-4, ... 2 give a remainder, A is prime.
  • 233. etc.
  • 235.
  • 237. Fibonacci Numbers • As seen in the Da Vinci Code:
  • 238. Fibonacci Numbers • The Fibonacci numbers are numbers where the next number in the sequence is the sum of the previous two. • The sequence starts with 1, 1, • And then it’s 2 • Then 3 • Then 5 • Then 8 • Then 13
  • 239. Leonardo Bonacci (aka Fibonacci) • Born 1170. • Born in Pisa, Italy • Died 1250. • An Italian mathematician, considered to be "the most talented Western mathematician of the Middle Ages". • Introduced the sequence of Fibonacci numbers which he used as an example in Liber Abaci.
  • 240. etc.
  • 242. Prime Numbers • So let’s say we want to express the following algorithm: – Read in a number and check if it’s a prime number. – What’s a prime number? – A number that’s only divisible by itself and 1, e.g. 7. – Or to put it another way, every number other than itself and 1 gives a remainder, e.g. For 7, if 6, 5, 4, 3, and 2 give a remainder then 7 is prime. – So all we need to do is divide 7 by all numbers less than it but greater than one, and if any of them have no remainder, we know it’s not prime.
  • 243. Prime Numbers • So, • If the number is 7, as long as 6, 5, 4, 3, and 2 give a remainder, 7 is prime. • If the number is 9, we know that 8, 7, 6, 5, and 4, all give remainders, but 3 does not give a remainder, it goes evenly into 9 so we can say 9 is not prime
  • 244. Prime Numbers • So remember, – if the number is 7, as long as 6, 5, 4, 3, and 2 give a remainder, 7 is prime. • So, in general, – if the number is A, as long as A-1, A-2, A-3, A-4, ... 2 give a remainder, A is prime.
  • 245. # PROGRAM CheckPrime: a = int(input("Please input value:")) b = a - 1 IsPrime = True while b != 1: # DO if a % b == 0: # THEN IsPrime = False # ENDIF; b = b - 1 # ENDWHILE; if IsPrime: # THEN print(a, "is a prime number") else: print(a, "is not a prime number") # ENDIF; # END.
  • 246. Fibonacci Numbers • The Fibonacci numbers are numbers where the next number in the sequence is the sum of the previous two. • The sequence starts with 1, 1, • And then it’s 2 • Then 3 • Then 5 • Then 8 • Then 13
  • 247. # PROGRAM FibonacciNumbers: a = int(input("Please input value:")) FirstNum = 1 SecondNum = 1 while a != 1: # DO total = SecondNum + FirstNum FirstNum = SecondNum SecondNum = total a = a - 1 # ENDWHILE; print(total) # END.
  • 248. etc.
  • 250. Modularisation • Let’s imagine we had code as follows:
  • 251. Modularisation # Python program to mail merger # Names are in the file names.txt # Body of the mail is in body.txt # open names.txt for reading with open("names.txt",'r',encoding = 'utf-8') as names_file: # open body.txt for reading with open("body.txt",'r',encoding = 'utf-8') as body_file: # read entire content of the body body = body_file.read() # iterate over names for name in names_file: mail = "Hello "+name+body # write the mails to individual files with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file: mail_file.write(mail) # Python program to mail merger # Names are in the file names.txt # Body of the mail is in body.txt # open names.txt for reading with open("names.txt",'r',encoding = 'utf-8') as names_file: # open body.txt for reading with open("body.txt",'r',encoding = 'utf-8') as body_file: # read entire content of the body body = body_file.read() # iterate over names for name in names_file: mail = "Hello "+name+body # write the mails to individual files with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file: mail_file.write(mail)
  • 252. Modularisation • And some bits of the code are repeated a few times
  • 253. Modularisation # Python program to mail merger # Names are in the file names.txt # Body of the mail is in body.txt # open names.txt for reading with open("names.txt",'r',encoding = 'utf-8') as names_file: # open body.txt for reading with open("body.txt",'r',encoding = 'utf-8') as body_file: # read entire content of the body body = body_file.read() # iterate over names for name in names_file: mail = "Hello "+name+body # write the mails to individual files with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file: mail_file.write(mail) # Python program to mail merger # Names are in the file names.txt # Body of the mail is in body.txt # open names.txt for reading with open("names.txt",'r',encoding = 'utf-8') as names_file: # open body.txt for reading with open("body.txt",'r',encoding = 'utf-8') as body_file: # read entire content of the body body = body_file.read() # iterate over names for name in names_file: mail = "Hello "+name+body # write the mails to individual files with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file: mail_file.write(mail)
  • 254. Modularisation # Python program to mail merger # Names are in the file names.txt # Body of the mail is in body.txt # open names.txt for reading with open("names.txt",'r',encoding = 'utf-8') as names_file: # open body.txt for reading with open("body.txt",'r',encoding = 'utf-8') as body_file: # read entire content of the body body = body_file.read() # iterate over names for name in names_file: mail = "Hello "+name+body # write the mails to individual files with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file: mail_file.write(mail) # Python program to mail merger # Names are in the file names.txt # Body of the mail is in body.txt # open names.txt for reading with open("names.txt",'r',encoding = 'utf-8') as names_file: # open body.txt for reading with open("body.txt",'r',encoding = 'utf-8') as body_file: # read entire content of the body body = body_file.read() # iterate over names for name in names_file: mail = "Hello "+name+body # write the mails to individual files with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file: mail_file.write(mail)
  • 255. Modularisation • It would be good if there was some way we could wrap up frequently used commands into a single package, and instead of having to rewrite the same code over and over again, we could just call the package name. • We can call these packages methods or functions • (or subroutines or procedures)
  • 256. Modularisation • Let’s revisit our prime number algorithm again:
  • 257. etc.
  • 259. Modularisation • Remember the prime checker program:
  • 260. # PROGRAM CheckPrime: a = int(input("Please input value:")) b = a - 1 IsPrime = True while b != 1: # DO if a % b == 0: # THEN IsPrime = False # ENDIF; b = b - 1 # ENDWHILE; if IsPrime: # THEN print(a, "is a prime number") else: print(a, "is not a prime number") # ENDIF; # END.
  • 261. # PROGRAM CheckPrime: a = int(input("Please input value:")) b = a - 1 IsPrime = True while b != 1: # DO if a % b == 0: # THEN IsPrime = False # ENDIF; b = b - 1 # ENDWHILE; if IsPrime: # THEN print(a, "is a prime number") else: print(a, "is not a prime number") # ENDIF; # END.
  • 262. Modularisation • Let’s break this program into modules (functions).
  • 263. ######################### # Prime Checking Module # ######################### def IsItPrime(): a = int(input("Please input value: ")) b = a - 1 IsPrime = True while b != 1: # DO if a % b == 0: # THEN IsPrime = False # ENDIF; b = b - 1 # ENDWHILE; return IsPrime # END IsItPrime.
  • 264. ######################### # Prime Checking Module # ######################### def IsItPrime(): a = int(input("Please input value: ")) b = a - 1 IsPrime = True while b != 1: # DO if a % b == 0: # THEN IsPrime = False # ENDIF; b = b - 1 # ENDWHILE; return IsPrime # END IsItPrime.
  • 265. ################ # Main Program # ################ # PROGRAM CheckPrime: if IsItPrime() == True: # THEN print("Prime number") else: print("Not a prime number") # ENDIF; # END.
  • 266. Thanks… Please contact me: e: Damian.Gordon@dit.ie t: @damiantgordon