SlideShare ist ein Scribd-Unternehmen logo
1 von 87
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
ITECH1000/5000 Programming 1
Lecture 2: Some new concepts :
Data types, For Loops and
Functions
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Assignment 1
May 28, 20132
Available on Moodle
Due in week 7, Friday April 27th
2012
Start early – written component and programming
component to complete
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
PASS
Sessions with peers
Start next week, airport lounge
Times on moodle
May 28, 20133
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Extension work
Assignment 
Download sample programs from text
(moodle), run the file roller.py
Read text book - graphics
Watch moodle for times for extension
discussion group
(9.30am Friday morning?)
May 28, 20134
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 20135
Last Week We Covered . . .
• Programs provide instructions for
computers
• Follow a strict syntax
• All (or most) programs
• Receive input (eg from keyboard)
• Process that data
• Provide output
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 20136
Last Week We Covered . . .
• Data is stored in variables
• Variables enable access to values on the activation stack
• The use of variables depends upon where they appear in
the statement.
• Variables have their values set if they appear on the left
side of an assignment statement
• The values of variables are retrieved if they appear on the
right side of an assignment statement or in a print
statement
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 20137
Last week: Activation stack
• We have said that a computer stores
values in its memory using variables.
• The program uses a structure that looks
like a stack (we call it the activation stack)
• When the program encounters a new
variable it makes space for its value on
top of the stack.
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Last week: Expressions
• Made up of operators performing
operations on operands
• Evaluate to a value
• Used on right hand side of
assignment statements (and other
places)
May 28, 20138
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Last week: Statements
• Instructions are encoded in
statements
• 3 types of statements:
• Assignment statements
• Input statements
• Output (print) statements
May 28, 20139
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201310
Last week: Assignment
statement
• Made up of three parts
• A variable on the left side of ‘=‘
• The operator ‘=‘
• An expression on the right side of ‘=‘
• If a variable appears on the right side of
‘=‘ its value is retrieved and used
• num1 = num1 + 3
• Answer is stored in assigned variable
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201311
Last Week We Covered . . .
• We saw how we could use Python
Shell interactively
• However, for programs that we use a
lot it’s best to make a permanent
record
• Make sure you save files with a .py
suffix
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Question
• What is the ‘^’ operator?
• It’s the bitwise exclusive or. It
manipulates values at the level of
bits (0’s and 1’s)
• Way beyond the scope of this course
May 28, 201312
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201313
Last week: Main function
• All of our Python programs should start with a function
(yep – more on functions later) called ‘main’
• We define this function with the line
‘def main ( ):’ #don’t forget the ‘:’
• The instructions that belong to main are indented (one tab)
• The line ‘main ( )’ tells the program to execute the
instructions belonging to main
• This will all make a lot more sense when we discuss
functions in detail
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201314
Program Execution
• Now that we’ve written the instructions we need
to get the computer to perform the actions
• This is called running or executing the program
• The code is executed, one statement at a time,
starting with the statement at the top of the main
function
• When the program has completed the actions
from one statement, it moves onto the next.
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201315
Activation stack
num1 6.4
main()
num1 = input (“Enter the first number “)
num2 = input (“Enter the second number “)
result = num1 + num2
print result
Assume the user enters 6.4 and 3.6
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201316
Activation Stack
num2 3.6
num1 6.4
main ()
num1 = input (“Enter the first number “)
num2 = input (“Enter the second number “)
result = num1 + num2
print result
Assume the user enters 6.4 and 3.6
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201317
Activation Stack
result 10.0
num2 3.6
num1 6.4
main ()
num1 = input (“Enter the first number “)
num2 = input (“Enter the second number “)
result = num1 + num2
print result
Assume the user enters 6.4 and 3.6
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201318
Activation stack
result 10.0
num2 3.6
num1 6.4
main ()
num1 = input (“Enter the first number “)
num2 = input (“Enter the second number “)
result = num1 + num2
print result
Assume the user enters 6.4 and 3.6
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201319
Today
• Data types
• A looping construct
• called the for loop
• Some built-in functions
• A function is code already written that we can
use to perform an action
• Saves us writing the code ourselves
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201320
Data types
• A data type reflect the sorts of data
we are currently working with
• A data type determine the range of
data and the operations that can be
performed on that data
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201321
Types of data
• Fundamental data types include:
• Integers (whole numbers) e.g. 5
• Floats (decimal numbers) e.g. 3.8
• Strings (of characters) using quotes
• Many programming languages use
single quotes for a single character
and double quotes for larger strings
• E.g. ‘J’ and “John”
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201322
For example
• 3 is an integer and so is 5.
• Knowing this, the program will allow us to do
arithmetic operations on them
• eg ‘+’, ‘-’, ‘*’
• That’s pretty straightforward when considering literals
like 3 and 5
• It becomes a little trickier when working with
variables which can have different types and different
stages of program execution
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201323
Strings
• Our third data type is called a string
• A string is textual – not numeric
• It consists of a group of characters contained in
quotes (either single or double)
• Example
• “John”, ‘John’, ‘3’, “4”, “Please enter a number:”
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201324
Identifiers, Strings, Literals
• Strings are surrounded by single or double
quotes (Python does not distinguish)
• Identifiers (variable names) are not
surrounded by quotes
• Literals are specific values such as “John”,
5, 3.8 (compare with variables)
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201325
Input with Strings
• name = input(“Enter your name: “)
• If “John” is entered that is fine
• If the quotes are forgotten then Python interprets
the response as an identifier or variable name
that is undefined – an error!
• An alternative is to use raw_input
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201326
raw_input( )
name = raw_input(“Enter your name: “)
• Any input is treated as a string
• Entering John or any other string without quotes is no
longer a problem
• However if raw_input() is used to enter a number:
• The number will be of type string
• Arithmetic is not possible without conversion using float()
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201327
Concatenation
• Refers to the combining of two or more strings
• E.g. name = “John” + ‘ ‘ + “Smith”
• The string expression on the right hand side is
evaluated (concatenated) and assigned to name
• ‘+’ here is the concatenation operator
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201328
Note
• We can only concatenate strings
• We cannot concatenate a string with an integer.
For example
“Jane: Age “ + 35
• Will give an error message
• Trivial question – what will happen if we try to
concatenate two integers?
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201329
Joining/Splitting strings
• String Concatenation operator ‘+’
“John” + ‘ ‘ + “Smith”  John Smith
• A library function which is the inverse of
concatenation
string.split(“John Smith”) [“John”, “Smith”]
The string has been separated at the space and
a list of two strings results
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201330
String of characters
• “John Smith” is stored as a list of
characters each of which can be accessed
by its index
index 0 1 2 3 4 5 6 7 8 9
Character ‘J’ ‘o’ ‘h’ ‘n’ ‘ ’ ‘S’ ‘m’ ‘i’ ‘t’ ‘h’
• E.g. “John Smith”[0]  ‘J’
• “John Smith”[8]  ‘t’
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201331
Substrings
• “John Smith”[0:3]  “Joh”
• The second index is NOT included
•
• “John Smith”[:3]  “Joh”
• If the first index is 0 it can be left out
• “John Smith”[2:6]  “hn S”
• Indexes 2,3,4,5 (6-2=4 characters)
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201332
Substrings
• “John Smith”[-1]  ‘h’
• Negative sign means start from the end
(-0 is the same as 0)
• “John Smith”[:-1]  ‘John Smit’
• Select up to but excluding the last
character
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201333
Converting type
• Functions: float(), int(), round
• Examples:
• float(3) # gives 3.0
• float(“3.8”) # gives 3.8
• int(3.8) # gives 3
• round(3.8) # gives 4
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201334
Converting type
Note that:
• float() adds .0 to an integer
• float() removes the quotes from a numerical
string
• int() cuts off any decimal part of the number
• round() expresses the number to the nearest
integer
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201335
Mixed arithmetic
• Any valid numerical expression that
contains at least one float will evaluate as
a float
• Otherwise the result will be of type integer
• It is not possible to do arithmetic with
numeric strings such as “2” + 7
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201336
Integer division
• We spent a bit of time last week looking at code using
integers and floats
• One surprise with integers might be integer division
num1 = 11
num2 = 4
result = num1 / num2
• Because num1 and num2 are both integers the result
of the division is also an integer
• Thus result will have the value 2 – not 2.75
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201337
Integer division - modulus
• 11 divided by 4 can be expressed
2 remainder 3
• Integer division gives us the whole number (2)
• The modulus operator ‘%’ gives us the remainder (3).
result = 11 % 4
• Will put the value 3 into the variable result
• The modulus operator cannot be used with floats
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201338
Floating point division
• A floating point number has a decimal part as well as
a whole number
• Eg 11.4, 454.83737 etc
• The decimal part might be 0. So
• 11 has data type int
• 11.0 has data type float
• If a division has at least one float then the result will
be a float
• result = 11.0 / 4
• Puts the value 2.75 into the variable result
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201339
Using our type conversions
• Consider the code
num1 = 11
num2 = 4
result = num1 / num2 #Result assigned ‘2’
• If we want 2.75 we can give one of the variables data
type float
result = float (num1) / num2 #or
result = num1 / float (num2)
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201340
Concatenation
• Refers to the combining of two or more strings
• E.g. name = “John” + ‘ ‘ + “Smith”
• The string expression on the right hand side is
evaluated (concatenated) and assigned to name
• ‘+’ here is the concatenation operator
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201341
Note
• We can only concatenate strings
• We cannot concatenate a string with an integer.
For example
“Jane: Age “ + 35
• Will give an error message
• Trivial question – what will happen if we try to
concatenate two integers?
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201342
Consider . . .
• A program that
• Prompts the user for a person’s name
• Creates a string greets that person
• Outputs that string
• Does this four times
• For example, if the user enters
“Jane” then “Hello Jane!” should be
output
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201343
Demo – sayHello.py
• Note that with this program we repeat the same
code four times
• What if we wanted to repeat it 10 times, 100
times . . .?
• This would become cumbersome very quickly
• Python provides constructs which enable us to
run the same code many times
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201344
Structured Programming
• Consists of
• Sequence
• Iteration (looping)
• Decision
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
#Prompts for a person's name and says greets that person
#Does this four times
def main():
name = input ("Enter a name: ") #prompt for name
result = "Hello " + name + "!" #prepare greeting
print result #output greeting
name = input ("Enter a name: ") #Do it again
result = "Hello " + name + "!"
print result
name = input ("Enter a name: ") #And again
result = "Hello " + name + "!"
print result
name = input ("Enter a name: ") #And a fourth time
result = "Hello " + name + "!"
print result
main()
#Notice how similar the four pieces of code are
#Wouldn't it be better if we could simply use the same piece of code 4 times
#Python provides looping structures which allow us to do this
May 28, 2013
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201346
Definite loops
• One of the great values of the computer is
that it can repeat actions indefinitely
(without tiring)
• The programming structure that allows
this is the loop
• A definite loop (called a for loop) repeats
loop code a fixed number of times
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201347
range
• The number of times the for loop
‘iterates’ is governed by the ‘range’
function
• ‘range(4)’ means 0,1,2,3, so that the
for loop iterates 4 times.
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
#uses a for loop to repeat greetings four times
def main():
for index in range(4): #do 4 times
name = input ("Enter a name: ")
# name = raw_input ("Enter a name: ")
greeting = "Hello " + name + "!"
print "Person number ", index
print greeting
main()
#The 'for loop' iterates 4 times
#The statements which are part of the loop are defined by the indenting
#Try taking the indenting away and see what happens
#We will also have a look at the variable 'index' to see what values it
contains
May 28, 201348
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201349
range
• range(4) takes the values 0, 1, 2, 3
so index is assigned these values in
turn
• adding index to the print statement
shows this
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201350
Some more looping examples
(see sum10.py)
• Consider a program that will sum all
of the integers between 1 and 10
• Extend this so that it prompts the
user for a start and finish number. It
then sums the integers between
these values.
• if the use enters 3 and 10 the output
will be 52
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Sum10.py
# program to find the total of the integers between 1 and 10
def main():
total = 0
for index in range(10):
total = total + index + 1 # add the number to the total
print "Total: ", total # display the total
main()
May 28, 201351
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Algorithm
Need range to start from num1 not
zero HOW?
Range to go up to num2
Loop
add val to total
Print total
May 28, 201352
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Algorithm design (not worrying
about syntax)
Need range to start from num1 not
zero HOW?
Range to go up to num2
Input num1 and num2
Initialise total =0 WHY?
Loop from num1 to num2
add val to total
Print total
May 28, 201353
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
range function
Need to find out if I can start at
something other than zero… how?
Range is a function that has been
previously written as part of the
python library.
Google it: “python range function”
May 28, 201354
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201355
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201356
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201357
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201358
Consider
(see sumNumbers.py)
• A program that sums 4 numbers that
are entered by the user.
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201359
# program to find the total of all numbers entered by the user
# will cause an error because runningTotal not initialised before use
def main():
# input how many numbers will be entered (numberOfValues)
numberOfValues = input("How many numbers will be entered? ")
for index in range(numberOfValues): # repeat ‘numberOfValues’ times
num = input("Enter a number: ")
runningTotal = runningTotal + num # add the number to the total
# error at this line
print runningTotal,
print "Total: ", runningTotal # display the total
main()
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201360
Note
• The character “t” is a control
character which prints out a tab
• A control character is preceded by ‘’
so be careful when using the
backslash in a string
• Another control character is ‘n’
which means new line
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201361
Note (2)
• Notice that the print statement in the
inner loop finishes with a comma (,)
• This will tell the program not to print
a new line
• The next output will occur on the same
line
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201362
Python standard library
• Can access the library from the Help menu in
either the shell or the editor
• Provides functions additional to the built-in ones
• Has a math section and a string section
• Library functions are accessed via import
statements
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201363
Some library functions
>>> import math
>>> math.sqrt(36) displays 6
>>> import string
>>> string.lower(“UPPERCASE”)
>>> string.upper(“lowercase”)
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201364
Import statements
• These establish a link with the Python Standard
library
• Any particular import statement is only required
once:
• in any given program
• in an open Python shell
• A new Python shell requires new import
statements if library functions are required
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Built–in functions
• A function is a small package of
Python code that performs a certain
task (function)
• Functions can be user-defined
• Coded by the programmer (see week 4)
• Functions can be built-in or library
• Written by someone else for our use
May 28, 201365
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Built-in functions
• We have already seen some
examples of a built-in function
• We have used the input function to
retrieve user input from the keyboard
• We used the range function in a for loop
• We will see more examples of built-in
functions today
May 28, 201366
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201367
Functions
• When we start writing programs to solve more
complicated problems, we’ll find that we need to
write large amounts of code
• Some programs have millions of lines of code
• Putting all of this code into the main function
would make it impossible to work with
• Functions are a way to split code up into pieces
that can be dealt with individually
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201368
Functions
• Can be built-in
• Examples are float (), input () etc
• Included in an external library
• string and math libraries for example
• Can be user-defined
• The programmer writes them
• We will be covering built-in functions today
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201369
Advantages of Functions
• Code can be written, tested and debugged
in smaller pieces
• Allows a divide and conquer strategy for
dealing with your code
• Functions can be reused in different
situations meaning you don’t have to
rewrite code
• input ( ) – is a built-in function - think about
how many times we’ve already used and
reused that function
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201370
Splitting strings
• An library function which is the inverse of
concatenation
“John” + ‘ ‘ + “Smith”  John Smith
string.split(“John Smith”) [“John”, “Smith”]
• The string has been separated at the space and a
list of two strings results
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201371
The typical function
• Functions consist of code that carries out a
specific task (or ‘function’)
• Many will require arguments
• Many will return (output) data as the
prime reason for their existence, others
will produce what are sometimes called
side effects
• Eg input function
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201372
Familiar functions
• Built-in functions
• float(7)  7.0
• float(“7.8”)  7.8
• int(7.8)  7
• round(7.8)  8.0
• len(“a string”)  8
• Argument types are int, str, float, float
and str respectively
• Return types for these functions are
• float – two occasions
• int – three occasions
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201373
Familiar functions
• Library functions
• math.sqrt(144)  12.0
• string.split(“the end”)  [“the”, ”end”]
• math.sqrt() - the argument can be of type int or
float, a float is returned
• string.split() – the argument is a string and a list
of strings is returned
• Remember these libraries need to be imported
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201374
# sqrtExample.py
# a program to demonstrate the library function 'sqrt'
import math # library that holds the function 'sqrt'
def main ( ):
num = input ("Please enter a number: ")
numRoot = math.sqrt (num); # Use the library name
followed by '.'
print "The root of ", num, " is ", numRoot
main ( )
Argument (input)
to the function
math.sqrt()
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201375
Arguments
(see sqrtExample.py)
• In the example on the previous slide,
‘num’ is an argument of the function
‘sqrt’
• An argument is an expression which
must be evaluated.
• Eg. math.sqrt (num * 2)
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201376
Using functions
• When a function is used with a program, e.g.
math.sqrt(), we say the function is called
• The function from which the call is made (in this
case main ( )) is the calling function
• The argument of the function call becomes
essential input for the function
• When a function is called, control of execution
passes to the function
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201377
Using functions
• When a function has completed its
processing (terminates), control
returns to the calling function
• the calling function can make use of
the value returned by the called
function
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201378
Reuse of Code
• The functions that have been referred to
(and many others) are used time and time
again
• This is a significant example of reuse of
code, saving countless hours of work
• Modifying existing programs for slightly
different purposes is another important
example of reuse of code (see labs)
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201379
The black box
• Note that when we use these built-in
and library functions, we do not need
to know how they work
• We only need to know how to use them
• We only need to know the inputs and
outputs. The processing is already
done.
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Functions
• Often require arguments
• Expressions or values which provide
input for the function
• Normally provide a return value
• A value, calculated by the function, that
we can use in our code
May 28, 201380
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Example
num = input (“Enter a number”)
“Enter a number” is an argument
The value entered at the keyboard by the
user becomes the return value of the
function
The return value is used in the assignment
expression
May 28, 201381
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Today we have covered
May 28, 201382
• Data Types – strings, integers, floats
• For loops
• Functions
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Review
May 28, 201383
• Data types – strings, integers, floats
• Input() if you enter a string need to
enclose in “ “
• raw_input() no need for “ “
• Functions take arguments as input
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201384
Review
• Integer division gives an integer result (ignoring
the remainder)
• Operator % gives the remainder
• Built-in functions include: type(), float(), int(),
round(), str(), len()
• Library functions extend the range of functions
substantially – they require one-off import
statements
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201385
Definite loops
•A definite loop (called a for loop) repeats
loop code a fixed number of times
for index in range(x)
stmt
stmt
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)
Review
May 28, 201386
• Functions enable us to design good programs and to re-use code
• Functions take input through arguments and return a result to the
calling code (usually)
def main() : #define the function main
stmt
stmt
main() # call the function main
CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201387
Remember
• Giving full attention to labs is essential –
practice, experiment and have fun!
• Ensure you have each lab completed
before the next one
• The theory test in week 5 is based on
experience gained from the first four labs
(and lectures)

Weitere ähnliche Inhalte

Ähnlich wie Assmnt 1

Stream-based Data Synchronization
Stream-based Data SynchronizationStream-based Data Synchronization
Stream-based Data SynchronizationKlemen Verdnik
 
With big data comes big responsibility
With big data comes big responsibilityWith big data comes big responsibility
With big data comes big responsibilityERPScan
 
AWS December 2015 Webinar Series - Design Patterns using Amazon DynamoDB
AWS December 2015 Webinar Series - Design Patterns using Amazon DynamoDBAWS December 2015 Webinar Series - Design Patterns using Amazon DynamoDB
AWS December 2015 Webinar Series - Design Patterns using Amazon DynamoDBAmazon Web Services
 
Uncovering SQL Server query problems with execution plans - Tony Davis
Uncovering SQL Server query problems with execution plans - Tony DavisUncovering SQL Server query problems with execution plans - Tony Davis
Uncovering SQL Server query problems with execution plans - Tony DavisRed Gate Software
 
MongoDB World 2018: Overnight to 60 Seconds: An IOT ETL Performance Case Study
MongoDB World 2018: Overnight to 60 Seconds: An IOT ETL Performance Case StudyMongoDB World 2018: Overnight to 60 Seconds: An IOT ETL Performance Case Study
MongoDB World 2018: Overnight to 60 Seconds: An IOT ETL Performance Case StudyMongoDB
 
ASE2023_SCPatcher_Presentation_V5.pptx
ASE2023_SCPatcher_Presentation_V5.pptxASE2023_SCPatcher_Presentation_V5.pptx
ASE2023_SCPatcher_Presentation_V5.pptxjzyNick
 
06 impq introduction_to_mysql
06 impq introduction_to_mysql06 impq introduction_to_mysql
06 impq introduction_to_mysqlShahil Mk
 
Kaizen cso002 l1
Kaizen cso002 l1Kaizen cso002 l1
Kaizen cso002 l1asslang
 
Microservices and Azure App Services
Microservices and Azure App ServicesMicroservices and Azure App Services
Microservices and Azure App ServicesDamir Dobric
 
Public Training SQL Implementation & Embedded Programming in IBM i (05-09 Jun...
Public Training SQL Implementation & Embedded Programming in IBM i (05-09 Jun...Public Training SQL Implementation & Embedded Programming in IBM i (05-09 Jun...
Public Training SQL Implementation & Embedded Programming in IBM i (05-09 Jun...Hany Paulina
 
Public Training SQL Implementation & Embedded Programming in IBM i
Public Training SQL Implementation & Embedded Programming in IBM iPublic Training SQL Implementation & Embedded Programming in IBM i
Public Training SQL Implementation & Embedded Programming in IBM iHany Paulina
 
Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithmK Hari Shankar
 
Chapter 16-spreadsheet1 questions and answer
Chapter 16-spreadsheet1  questions and answerChapter 16-spreadsheet1  questions and answer
Chapter 16-spreadsheet1 questions and answerRaajTech
 
SESSION 2.ppt
SESSION 2.pptSESSION 2.ppt
SESSION 2.pptSaranya S
 
18.02.05_IAAI2018_Mobille Network Failure Event Detection and Forecasting wit...
18.02.05_IAAI2018_Mobille Network Failure Event Detection and Forecasting wit...18.02.05_IAAI2018_Mobille Network Failure Event Detection and Forecasting wit...
18.02.05_IAAI2018_Mobille Network Failure Event Detection and Forecasting wit...LINE Corp.
 
IRJET - Predicting the Maximum Computational Power of Microprocessors using M...
IRJET - Predicting the Maximum Computational Power of Microprocessors using M...IRJET - Predicting the Maximum Computational Power of Microprocessors using M...
IRJET - Predicting the Maximum Computational Power of Microprocessors using M...IRJET Journal
 

Ähnlich wie Assmnt 1 (20)

Stream-based Data Synchronization
Stream-based Data SynchronizationStream-based Data Synchronization
Stream-based Data Synchronization
 
With big data comes big responsibility
With big data comes big responsibilityWith big data comes big responsibility
With big data comes big responsibility
 
AWS December 2015 Webinar Series - Design Patterns using Amazon DynamoDB
AWS December 2015 Webinar Series - Design Patterns using Amazon DynamoDBAWS December 2015 Webinar Series - Design Patterns using Amazon DynamoDB
AWS December 2015 Webinar Series - Design Patterns using Amazon DynamoDB
 
Uncovering SQL Server query problems with execution plans - Tony Davis
Uncovering SQL Server query problems with execution plans - Tony DavisUncovering SQL Server query problems with execution plans - Tony Davis
Uncovering SQL Server query problems with execution plans - Tony Davis
 
MongoDB World 2018: Overnight to 60 Seconds: An IOT ETL Performance Case Study
MongoDB World 2018: Overnight to 60 Seconds: An IOT ETL Performance Case StudyMongoDB World 2018: Overnight to 60 Seconds: An IOT ETL Performance Case Study
MongoDB World 2018: Overnight to 60 Seconds: An IOT ETL Performance Case Study
 
ASE2023_SCPatcher_Presentation_V5.pptx
ASE2023_SCPatcher_Presentation_V5.pptxASE2023_SCPatcher_Presentation_V5.pptx
ASE2023_SCPatcher_Presentation_V5.pptx
 
cryptography
cryptographycryptography
cryptography
 
06 impq introduction_to_mysql
06 impq introduction_to_mysql06 impq introduction_to_mysql
06 impq introduction_to_mysql
 
Kaizen cso002 l1
Kaizen cso002 l1Kaizen cso002 l1
Kaizen cso002 l1
 
Microservices and Azure App Services
Microservices and Azure App ServicesMicroservices and Azure App Services
Microservices and Azure App Services
 
Public Training SQL Implementation & Embedded Programming in IBM i (05-09 Jun...
Public Training SQL Implementation & Embedded Programming in IBM i (05-09 Jun...Public Training SQL Implementation & Embedded Programming in IBM i (05-09 Jun...
Public Training SQL Implementation & Embedded Programming in IBM i (05-09 Jun...
 
Public Training SQL Implementation & Embedded Programming in IBM i
Public Training SQL Implementation & Embedded Programming in IBM iPublic Training SQL Implementation & Embedded Programming in IBM i
Public Training SQL Implementation & Embedded Programming in IBM i
 
Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithm
 
Chapter 16-spreadsheet1 questions and answer
Chapter 16-spreadsheet1  questions and answerChapter 16-spreadsheet1  questions and answer
Chapter 16-spreadsheet1 questions and answer
 
SESSION 2.ppt
SESSION 2.pptSESSION 2.ppt
SESSION 2.ppt
 
Amit vish
Amit vishAmit vish
Amit vish
 
L02.pdf
L02.pdfL02.pdf
L02.pdf
 
18.02.05_IAAI2018_Mobille Network Failure Event Detection and Forecasting wit...
18.02.05_IAAI2018_Mobille Network Failure Event Detection and Forecasting wit...18.02.05_IAAI2018_Mobille Network Failure Event Detection and Forecasting wit...
18.02.05_IAAI2018_Mobille Network Failure Event Detection and Forecasting wit...
 
IRJET - Predicting the Maximum Computational Power of Microprocessors using M...
IRJET - Predicting the Maximum Computational Power of Microprocessors using M...IRJET - Predicting the Maximum Computational Power of Microprocessors using M...
IRJET - Predicting the Maximum Computational Power of Microprocessors using M...
 
Relational algebra
Relational algebraRelational algebra
Relational algebra
 

Kürzlich hochgeladen

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Kürzlich hochgeladen (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

Assmnt 1

  • 1. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) ITECH1000/5000 Programming 1 Lecture 2: Some new concepts : Data types, For Loops and Functions
  • 2. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Assignment 1 May 28, 20132 Available on Moodle Due in week 7, Friday April 27th 2012 Start early – written component and programming component to complete
  • 3. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) PASS Sessions with peers Start next week, airport lounge Times on moodle May 28, 20133
  • 4. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Extension work Assignment  Download sample programs from text (moodle), run the file roller.py Read text book - graphics Watch moodle for times for extension discussion group (9.30am Friday morning?) May 28, 20134
  • 5. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 20135 Last Week We Covered . . . • Programs provide instructions for computers • Follow a strict syntax • All (or most) programs • Receive input (eg from keyboard) • Process that data • Provide output
  • 6. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 20136 Last Week We Covered . . . • Data is stored in variables • Variables enable access to values on the activation stack • The use of variables depends upon where they appear in the statement. • Variables have their values set if they appear on the left side of an assignment statement • The values of variables are retrieved if they appear on the right side of an assignment statement or in a print statement
  • 7. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 20137 Last week: Activation stack • We have said that a computer stores values in its memory using variables. • The program uses a structure that looks like a stack (we call it the activation stack) • When the program encounters a new variable it makes space for its value on top of the stack.
  • 8. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Last week: Expressions • Made up of operators performing operations on operands • Evaluate to a value • Used on right hand side of assignment statements (and other places) May 28, 20138
  • 9. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Last week: Statements • Instructions are encoded in statements • 3 types of statements: • Assignment statements • Input statements • Output (print) statements May 28, 20139
  • 10. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201310 Last week: Assignment statement • Made up of three parts • A variable on the left side of ‘=‘ • The operator ‘=‘ • An expression on the right side of ‘=‘ • If a variable appears on the right side of ‘=‘ its value is retrieved and used • num1 = num1 + 3 • Answer is stored in assigned variable
  • 11. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201311 Last Week We Covered . . . • We saw how we could use Python Shell interactively • However, for programs that we use a lot it’s best to make a permanent record • Make sure you save files with a .py suffix
  • 12. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Question • What is the ‘^’ operator? • It’s the bitwise exclusive or. It manipulates values at the level of bits (0’s and 1’s) • Way beyond the scope of this course May 28, 201312
  • 13. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201313 Last week: Main function • All of our Python programs should start with a function (yep – more on functions later) called ‘main’ • We define this function with the line ‘def main ( ):’ #don’t forget the ‘:’ • The instructions that belong to main are indented (one tab) • The line ‘main ( )’ tells the program to execute the instructions belonging to main • This will all make a lot more sense when we discuss functions in detail
  • 14. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201314 Program Execution • Now that we’ve written the instructions we need to get the computer to perform the actions • This is called running or executing the program • The code is executed, one statement at a time, starting with the statement at the top of the main function • When the program has completed the actions from one statement, it moves onto the next.
  • 15. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201315 Activation stack num1 6.4 main() num1 = input (“Enter the first number “) num2 = input (“Enter the second number “) result = num1 + num2 print result Assume the user enters 6.4 and 3.6
  • 16. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201316 Activation Stack num2 3.6 num1 6.4 main () num1 = input (“Enter the first number “) num2 = input (“Enter the second number “) result = num1 + num2 print result Assume the user enters 6.4 and 3.6
  • 17. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201317 Activation Stack result 10.0 num2 3.6 num1 6.4 main () num1 = input (“Enter the first number “) num2 = input (“Enter the second number “) result = num1 + num2 print result Assume the user enters 6.4 and 3.6
  • 18. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201318 Activation stack result 10.0 num2 3.6 num1 6.4 main () num1 = input (“Enter the first number “) num2 = input (“Enter the second number “) result = num1 + num2 print result Assume the user enters 6.4 and 3.6
  • 19. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201319 Today • Data types • A looping construct • called the for loop • Some built-in functions • A function is code already written that we can use to perform an action • Saves us writing the code ourselves
  • 20. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201320 Data types • A data type reflect the sorts of data we are currently working with • A data type determine the range of data and the operations that can be performed on that data
  • 21. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201321 Types of data • Fundamental data types include: • Integers (whole numbers) e.g. 5 • Floats (decimal numbers) e.g. 3.8 • Strings (of characters) using quotes • Many programming languages use single quotes for a single character and double quotes for larger strings • E.g. ‘J’ and “John”
  • 22. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201322 For example • 3 is an integer and so is 5. • Knowing this, the program will allow us to do arithmetic operations on them • eg ‘+’, ‘-’, ‘*’ • That’s pretty straightforward when considering literals like 3 and 5 • It becomes a little trickier when working with variables which can have different types and different stages of program execution
  • 23. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201323 Strings • Our third data type is called a string • A string is textual – not numeric • It consists of a group of characters contained in quotes (either single or double) • Example • “John”, ‘John’, ‘3’, “4”, “Please enter a number:”
  • 24. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201324 Identifiers, Strings, Literals • Strings are surrounded by single or double quotes (Python does not distinguish) • Identifiers (variable names) are not surrounded by quotes • Literals are specific values such as “John”, 5, 3.8 (compare with variables)
  • 25. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201325 Input with Strings • name = input(“Enter your name: “) • If “John” is entered that is fine • If the quotes are forgotten then Python interprets the response as an identifier or variable name that is undefined – an error! • An alternative is to use raw_input
  • 26. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201326 raw_input( ) name = raw_input(“Enter your name: “) • Any input is treated as a string • Entering John or any other string without quotes is no longer a problem • However if raw_input() is used to enter a number: • The number will be of type string • Arithmetic is not possible without conversion using float()
  • 27. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201327 Concatenation • Refers to the combining of two or more strings • E.g. name = “John” + ‘ ‘ + “Smith” • The string expression on the right hand side is evaluated (concatenated) and assigned to name • ‘+’ here is the concatenation operator
  • 28. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201328 Note • We can only concatenate strings • We cannot concatenate a string with an integer. For example “Jane: Age “ + 35 • Will give an error message • Trivial question – what will happen if we try to concatenate two integers?
  • 29. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201329 Joining/Splitting strings • String Concatenation operator ‘+’ “John” + ‘ ‘ + “Smith”  John Smith • A library function which is the inverse of concatenation string.split(“John Smith”) [“John”, “Smith”] The string has been separated at the space and a list of two strings results
  • 30. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201330 String of characters • “John Smith” is stored as a list of characters each of which can be accessed by its index index 0 1 2 3 4 5 6 7 8 9 Character ‘J’ ‘o’ ‘h’ ‘n’ ‘ ’ ‘S’ ‘m’ ‘i’ ‘t’ ‘h’ • E.g. “John Smith”[0]  ‘J’ • “John Smith”[8]  ‘t’
  • 31. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201331 Substrings • “John Smith”[0:3]  “Joh” • The second index is NOT included • • “John Smith”[:3]  “Joh” • If the first index is 0 it can be left out • “John Smith”[2:6]  “hn S” • Indexes 2,3,4,5 (6-2=4 characters)
  • 32. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201332 Substrings • “John Smith”[-1]  ‘h’ • Negative sign means start from the end (-0 is the same as 0) • “John Smith”[:-1]  ‘John Smit’ • Select up to but excluding the last character
  • 33. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201333 Converting type • Functions: float(), int(), round • Examples: • float(3) # gives 3.0 • float(“3.8”) # gives 3.8 • int(3.8) # gives 3 • round(3.8) # gives 4
  • 34. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201334 Converting type Note that: • float() adds .0 to an integer • float() removes the quotes from a numerical string • int() cuts off any decimal part of the number • round() expresses the number to the nearest integer
  • 35. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201335 Mixed arithmetic • Any valid numerical expression that contains at least one float will evaluate as a float • Otherwise the result will be of type integer • It is not possible to do arithmetic with numeric strings such as “2” + 7
  • 36. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201336 Integer division • We spent a bit of time last week looking at code using integers and floats • One surprise with integers might be integer division num1 = 11 num2 = 4 result = num1 / num2 • Because num1 and num2 are both integers the result of the division is also an integer • Thus result will have the value 2 – not 2.75
  • 37. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201337 Integer division - modulus • 11 divided by 4 can be expressed 2 remainder 3 • Integer division gives us the whole number (2) • The modulus operator ‘%’ gives us the remainder (3). result = 11 % 4 • Will put the value 3 into the variable result • The modulus operator cannot be used with floats
  • 38. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201338 Floating point division • A floating point number has a decimal part as well as a whole number • Eg 11.4, 454.83737 etc • The decimal part might be 0. So • 11 has data type int • 11.0 has data type float • If a division has at least one float then the result will be a float • result = 11.0 / 4 • Puts the value 2.75 into the variable result
  • 39. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201339 Using our type conversions • Consider the code num1 = 11 num2 = 4 result = num1 / num2 #Result assigned ‘2’ • If we want 2.75 we can give one of the variables data type float result = float (num1) / num2 #or result = num1 / float (num2)
  • 40. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201340 Concatenation • Refers to the combining of two or more strings • E.g. name = “John” + ‘ ‘ + “Smith” • The string expression on the right hand side is evaluated (concatenated) and assigned to name • ‘+’ here is the concatenation operator
  • 41. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201341 Note • We can only concatenate strings • We cannot concatenate a string with an integer. For example “Jane: Age “ + 35 • Will give an error message • Trivial question – what will happen if we try to concatenate two integers?
  • 42. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201342 Consider . . . • A program that • Prompts the user for a person’s name • Creates a string greets that person • Outputs that string • Does this four times • For example, if the user enters “Jane” then “Hello Jane!” should be output
  • 43. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201343 Demo – sayHello.py • Note that with this program we repeat the same code four times • What if we wanted to repeat it 10 times, 100 times . . .? • This would become cumbersome very quickly • Python provides constructs which enable us to run the same code many times
  • 44. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201344 Structured Programming • Consists of • Sequence • Iteration (looping) • Decision
  • 45. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) #Prompts for a person's name and says greets that person #Does this four times def main(): name = input ("Enter a name: ") #prompt for name result = "Hello " + name + "!" #prepare greeting print result #output greeting name = input ("Enter a name: ") #Do it again result = "Hello " + name + "!" print result name = input ("Enter a name: ") #And again result = "Hello " + name + "!" print result name = input ("Enter a name: ") #And a fourth time result = "Hello " + name + "!" print result main() #Notice how similar the four pieces of code are #Wouldn't it be better if we could simply use the same piece of code 4 times #Python provides looping structures which allow us to do this May 28, 2013
  • 46. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201346 Definite loops • One of the great values of the computer is that it can repeat actions indefinitely (without tiring) • The programming structure that allows this is the loop • A definite loop (called a for loop) repeats loop code a fixed number of times
  • 47. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201347 range • The number of times the for loop ‘iterates’ is governed by the ‘range’ function • ‘range(4)’ means 0,1,2,3, so that the for loop iterates 4 times.
  • 48. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) #uses a for loop to repeat greetings four times def main(): for index in range(4): #do 4 times name = input ("Enter a name: ") # name = raw_input ("Enter a name: ") greeting = "Hello " + name + "!" print "Person number ", index print greeting main() #The 'for loop' iterates 4 times #The statements which are part of the loop are defined by the indenting #Try taking the indenting away and see what happens #We will also have a look at the variable 'index' to see what values it contains May 28, 201348
  • 49. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201349 range • range(4) takes the values 0, 1, 2, 3 so index is assigned these values in turn • adding index to the print statement shows this
  • 50. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201350 Some more looping examples (see sum10.py) • Consider a program that will sum all of the integers between 1 and 10 • Extend this so that it prompts the user for a start and finish number. It then sums the integers between these values. • if the use enters 3 and 10 the output will be 52
  • 51. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Sum10.py # program to find the total of the integers between 1 and 10 def main(): total = 0 for index in range(10): total = total + index + 1 # add the number to the total print "Total: ", total # display the total main() May 28, 201351
  • 52. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Algorithm Need range to start from num1 not zero HOW? Range to go up to num2 Loop add val to total Print total May 28, 201352
  • 53. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Algorithm design (not worrying about syntax) Need range to start from num1 not zero HOW? Range to go up to num2 Input num1 and num2 Initialise total =0 WHY? Loop from num1 to num2 add val to total Print total May 28, 201353
  • 54. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) range function Need to find out if I can start at something other than zero… how? Range is a function that has been previously written as part of the python library. Google it: “python range function” May 28, 201354
  • 55. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201355
  • 56. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201356
  • 57. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201357
  • 58. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201358 Consider (see sumNumbers.py) • A program that sums 4 numbers that are entered by the user.
  • 59. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201359 # program to find the total of all numbers entered by the user # will cause an error because runningTotal not initialised before use def main(): # input how many numbers will be entered (numberOfValues) numberOfValues = input("How many numbers will be entered? ") for index in range(numberOfValues): # repeat ‘numberOfValues’ times num = input("Enter a number: ") runningTotal = runningTotal + num # add the number to the total # error at this line print runningTotal, print "Total: ", runningTotal # display the total main()
  • 60. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201360 Note • The character “t” is a control character which prints out a tab • A control character is preceded by ‘’ so be careful when using the backslash in a string • Another control character is ‘n’ which means new line
  • 61. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201361 Note (2) • Notice that the print statement in the inner loop finishes with a comma (,) • This will tell the program not to print a new line • The next output will occur on the same line
  • 62. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201362 Python standard library • Can access the library from the Help menu in either the shell or the editor • Provides functions additional to the built-in ones • Has a math section and a string section • Library functions are accessed via import statements
  • 63. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201363 Some library functions >>> import math >>> math.sqrt(36) displays 6 >>> import string >>> string.lower(“UPPERCASE”) >>> string.upper(“lowercase”)
  • 64. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201364 Import statements • These establish a link with the Python Standard library • Any particular import statement is only required once: • in any given program • in an open Python shell • A new Python shell requires new import statements if library functions are required
  • 65. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Built–in functions • A function is a small package of Python code that performs a certain task (function) • Functions can be user-defined • Coded by the programmer (see week 4) • Functions can be built-in or library • Written by someone else for our use May 28, 201365
  • 66. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Built-in functions • We have already seen some examples of a built-in function • We have used the input function to retrieve user input from the keyboard • We used the range function in a for loop • We will see more examples of built-in functions today May 28, 201366
  • 67. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201367 Functions • When we start writing programs to solve more complicated problems, we’ll find that we need to write large amounts of code • Some programs have millions of lines of code • Putting all of this code into the main function would make it impossible to work with • Functions are a way to split code up into pieces that can be dealt with individually
  • 68. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201368 Functions • Can be built-in • Examples are float (), input () etc • Included in an external library • string and math libraries for example • Can be user-defined • The programmer writes them • We will be covering built-in functions today
  • 69. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201369 Advantages of Functions • Code can be written, tested and debugged in smaller pieces • Allows a divide and conquer strategy for dealing with your code • Functions can be reused in different situations meaning you don’t have to rewrite code • input ( ) – is a built-in function - think about how many times we’ve already used and reused that function
  • 70. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201370 Splitting strings • An library function which is the inverse of concatenation “John” + ‘ ‘ + “Smith”  John Smith string.split(“John Smith”) [“John”, “Smith”] • The string has been separated at the space and a list of two strings results
  • 71. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201371 The typical function • Functions consist of code that carries out a specific task (or ‘function’) • Many will require arguments • Many will return (output) data as the prime reason for their existence, others will produce what are sometimes called side effects • Eg input function
  • 72. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201372 Familiar functions • Built-in functions • float(7)  7.0 • float(“7.8”)  7.8 • int(7.8)  7 • round(7.8)  8.0 • len(“a string”)  8 • Argument types are int, str, float, float and str respectively • Return types for these functions are • float – two occasions • int – three occasions
  • 73. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201373 Familiar functions • Library functions • math.sqrt(144)  12.0 • string.split(“the end”)  [“the”, ”end”] • math.sqrt() - the argument can be of type int or float, a float is returned • string.split() – the argument is a string and a list of strings is returned • Remember these libraries need to be imported
  • 74. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201374 # sqrtExample.py # a program to demonstrate the library function 'sqrt' import math # library that holds the function 'sqrt' def main ( ): num = input ("Please enter a number: ") numRoot = math.sqrt (num); # Use the library name followed by '.' print "The root of ", num, " is ", numRoot main ( ) Argument (input) to the function math.sqrt()
  • 75. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201375 Arguments (see sqrtExample.py) • In the example on the previous slide, ‘num’ is an argument of the function ‘sqrt’ • An argument is an expression which must be evaluated. • Eg. math.sqrt (num * 2)
  • 76. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201376 Using functions • When a function is used with a program, e.g. math.sqrt(), we say the function is called • The function from which the call is made (in this case main ( )) is the calling function • The argument of the function call becomes essential input for the function • When a function is called, control of execution passes to the function
  • 77. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201377 Using functions • When a function has completed its processing (terminates), control returns to the calling function • the calling function can make use of the value returned by the called function
  • 78. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201378 Reuse of Code • The functions that have been referred to (and many others) are used time and time again • This is a significant example of reuse of code, saving countless hours of work • Modifying existing programs for slightly different purposes is another important example of reuse of code (see labs)
  • 79. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201379 The black box • Note that when we use these built-in and library functions, we do not need to know how they work • We only need to know how to use them • We only need to know the inputs and outputs. The processing is already done.
  • 80. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Functions • Often require arguments • Expressions or values which provide input for the function • Normally provide a return value • A value, calculated by the function, that we can use in our code May 28, 201380
  • 81. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Example num = input (“Enter a number”) “Enter a number” is an argument The value entered at the keyboard by the user becomes the return value of the function The return value is used in the assignment expression May 28, 201381
  • 82. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Today we have covered May 28, 201382 • Data Types – strings, integers, floats • For loops • Functions
  • 83. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Review May 28, 201383 • Data types – strings, integers, floats • Input() if you enter a string need to enclose in “ “ • raw_input() no need for “ “ • Functions take arguments as input
  • 84. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201384 Review • Integer division gives an integer result (ignoring the remainder) • Operator % gives the remainder • Built-in functions include: type(), float(), int(), round(), str(), len() • Library functions extend the range of functions substantially – they require one-off import statements
  • 85. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201385 Definite loops •A definite loop (called a for loop) repeats loop code a fixed number of times for index in range(x) stmt stmt
  • 86. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA) Review May 28, 201386 • Functions enable us to design good programs and to re-use code • Functions take input through arguments and return a result to the calling code (usually) def main() : #define the function main stmt stmt main() # call the function main
  • 87. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201387 Remember • Giving full attention to labs is essential – practice, experiment and have fun! • Ensure you have each lab completed before the next one • The theory test in week 5 is based on experience gained from the first four labs (and lectures)