Your SlideShare is downloading. ×
0
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Assmnt 1
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Assmnt 1

73

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
73
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
1
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)ITECH1000/5000 Programming 1Lecture 2: Some new concepts :Data types, For Loops andFunctions
  • 2. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)Assignment 1May 28, 20132Available on MoodleDue in week 7, Friday April 27th2012Start early – written component and programmingcomponent to complete
  • 3. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)PASSSessions with peersStart next week, airport loungeTimes on moodleMay 28, 20133
  • 4. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)Extension workAssignment Download sample programs from text(moodle), run the file roller.pyRead text book - graphicsWatch moodle for times for extensiondiscussion group(9.30am Friday morning?)May 28, 20134
  • 5. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 20135Last Week We Covered . . .• Programs provide instructions forcomputers• 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, 20136Last 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 inthe statement.• Variables have their values set if they appear on the leftside of an assignment statement• The values of variables are retrieved if they appear on theright side of an assignment statement or in a printstatement
  • 7. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 20137Last week: Activation stack• We have said that a computer storesvalues in its memory using variables.• The program uses a structure that lookslike a stack (we call it the activation stack)• When the program encounters a newvariable it makes space for its value ontop of the stack.
  • 8. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)Last week: Expressions• Made up of operators performingoperations on operands• Evaluate to a value• Used on right hand side ofassignment statements (and otherplaces)May 28, 20138
  • 9. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)Last week: Statements• Instructions are encoded instatements• 3 types of statements:• Assignment statements• Input statements• Output (print) statementsMay 28, 20139
  • 10. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201310Last week: Assignmentstatement• 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, 201311Last Week We Covered . . .• We saw how we could use PythonShell interactively• However, for programs that we use alot it’s best to make a permanentrecord• Make sure you save files with a .pysuffix
  • 12. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)Question• What is the ‘^’ operator?• It’s the bitwise exclusive or. Itmanipulates values at the level ofbits (0’s and 1’s)• Way beyond the scope of this courseMay 28, 201312
  • 13. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201313Last 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 theinstructions belonging to main• This will all make a lot more sense when we discussfunctions in detail
  • 14. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201314Program Execution• Now that we’ve written the instructions we needto 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 mainfunction• When the program has completed the actionsfrom one statement, it moves onto the next.
  • 15. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201315Activation stacknum1 6.4main()num1 = input (“Enter the first number “)num2 = input (“Enter the second number “)result = num1 + num2print resultAssume the user enters 6.4 and 3.6
  • 16. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201316Activation Stacknum2 3.6num1 6.4main ()num1 = input (“Enter the first number “)num2 = input (“Enter the second number “)result = num1 + num2print resultAssume the user enters 6.4 and 3.6
  • 17. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201317Activation Stackresult 10.0num2 3.6num1 6.4main ()num1 = input (“Enter the first number “)num2 = input (“Enter the second number “)result = num1 + num2print resultAssume the user enters 6.4 and 3.6
  • 18. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201318Activation stackresult 10.0num2 3.6num1 6.4main ()num1 = input (“Enter the first number “)num2 = input (“Enter the second number “)result = num1 + num2print resultAssume the user enters 6.4 and 3.6
  • 19. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201319Today• Data types• A looping construct• called the for loop• Some built-in functions• A function is code already written that we canuse to perform an action• Saves us writing the code ourselves
  • 20. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201320Data types• A data type reflect the sorts of datawe are currently working with• A data type determine the range ofdata and the operations that can beperformed on that data
  • 21. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201321Types 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 usesingle quotes for a single characterand double quotes for larger strings• E.g. ‘J’ and “John”
  • 22. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201322For example• 3 is an integer and so is 5.• Knowing this, the program will allow us to doarithmetic operations on them• eg ‘+’, ‘-’, ‘*’• That’s pretty straightforward when considering literalslike 3 and 5• It becomes a little trickier when working withvariables which can have different types and differentstages of program execution
  • 23. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201323Strings• Our third data type is called a string• A string is textual – not numeric• It consists of a group of characters contained inquotes (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, 201324Identifiers, Strings, Literals• Strings are surrounded by single or doublequotes (Python does not distinguish)• Identifiers (variable names) are notsurrounded 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, 201325Input with Strings• name = input(“Enter your name: “)• If “John” is entered that is fine• If the quotes are forgotten then Python interpretsthe response as an identifier or variable namethat is undefined – an error!• An alternative is to use raw_input
  • 26. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201326raw_input( )name = raw_input(“Enter your name: “)• Any input is treated as a string• Entering John or any other string without quotes is nolonger 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, 201327Concatenation• Refers to the combining of two or more strings• E.g. name = “John” + ‘ ‘ + “Smith”• The string expression on the right hand side isevaluated (concatenated) and assigned to name• ‘+’ here is the concatenation operator
  • 28. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201328Note• 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 toconcatenate two integers?
  • 29. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201329Joining/Splitting strings• String Concatenation operator ‘+’“John” + ‘ ‘ + “Smith”  John Smith• A library function which is the inverse ofconcatenationstring.split(“John Smith”) [“John”, “Smith”]The string has been separated at the space anda list of two strings results
  • 30. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201330String of characters• “John Smith” is stored as a list ofcharacters each of which can be accessedby its indexindex 0 1 2 3 4 5 6 7 8 9Character ‘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, 201331Substrings• “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, 201332Substrings• “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 lastcharacter
  • 33. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201333Converting 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, 201334Converting typeNote that:• float() adds .0 to an integer• float() removes the quotes from a numericalstring• int() cuts off any decimal part of the number• round() expresses the number to the nearestinteger
  • 35. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201335Mixed arithmetic• Any valid numerical expression thatcontains at least one float will evaluate asa float• Otherwise the result will be of type integer• It is not possible to do arithmetic withnumeric strings such as “2” + 7
  • 36. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201336Integer division• We spent a bit of time last week looking at code usingintegers and floats• One surprise with integers might be integer divisionnum1 = 11num2 = 4result = num1 / num2• Because num1 and num2 are both integers the resultof 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, 201337Integer division - modulus• 11 divided by 4 can be expressed2 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, 201338Floating point division• A floating point number has a decimal part as well asa 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 willbe 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, 201339Using our type conversions• Consider the codenum1 = 11num2 = 4result = num1 / num2 #Result assigned ‘2’• If we want 2.75 we can give one of the variables datatype floatresult = float (num1) / num2 #orresult = num1 / float (num2)
  • 40. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201340Concatenation• Refers to the combining of two or more strings• E.g. name = “John” + ‘ ‘ + “Smith”• The string expression on the right hand side isevaluated (concatenated) and assigned to name• ‘+’ here is the concatenation operator
  • 41. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201341Note• 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 toconcatenate two integers?
  • 42. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201342Consider . . .• 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 beoutput
  • 43. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201343Demo – sayHello.py• Note that with this program we repeat the samecode four times• What if we wanted to repeat it 10 times, 100times . . .?• This would become cumbersome very quickly• Python provides constructs which enable us torun the same code many times
  • 44. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201344Structured Programming• Consists of• Sequence• Iteration (looping)• Decision
  • 45. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)#Prompts for a persons name and says greets that person#Does this four timesdef main():name = input ("Enter a name: ") #prompt for nameresult = "Hello " + name + "!" #prepare greetingprint result #output greetingname = input ("Enter a name: ") #Do it againresult = "Hello " + name + "!"print resultname = input ("Enter a name: ") #And againresult = "Hello " + name + "!"print resultname = input ("Enter a name: ") #And a fourth timeresult = "Hello " + name + "!"print resultmain()#Notice how similar the four pieces of code are#Wouldnt it be better if we could simply use the same piece of code 4 times#Python provides looping structures which allow us to do thisMay 28, 2013
  • 46. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201346Definite loops• One of the great values of the computer isthat it can repeat actions indefinitely(without tiring)• The programming structure that allowsthis is the loop• A definite loop (called a for loop) repeatsloop code a fixed number of times
  • 47. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201347range• The number of times the for loop‘iterates’ is governed by the ‘range’function• ‘range(4)’ means 0,1,2,3, so that thefor loop iterates 4 times.
  • 48. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)#uses a for loop to repeat greetings four timesdef main():for index in range(4): #do 4 timesname = input ("Enter a name: ")# name = raw_input ("Enter a name: ")greeting = "Hello " + name + "!"print "Person number ", indexprint greetingmain()#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 itcontainsMay 28, 201348
  • 49. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201349range• range(4) takes the values 0, 1, 2, 3so index is assigned these values inturn• adding index to the print statementshows this
  • 50. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201350Some more looping examples(see sum10.py)• Consider a program that will sum allof the integers between 1 and 10• Extend this so that it prompts theuser for a start and finish number. Itthen sums the integers betweenthese values.• if the use enters 3 and 10 the outputwill 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 10def main():total = 0for index in range(10):total = total + index + 1 # add the number to the totalprint "Total: ", total # display the totalmain()May 28, 201351
  • 52. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)AlgorithmNeed range to start from num1 notzero HOW?Range to go up to num2Loopadd val to totalPrint totalMay 28, 201352
  • 53. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)Algorithm design (not worryingabout syntax)Need range to start from num1 notzero HOW?Range to go up to num2Input num1 and num2Initialise total =0 WHY?Loop from num1 to num2add val to totalPrint totalMay 28, 201353
  • 54. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)range functionNeed to find out if I can start atsomething other than zero… how?Range is a function that has beenpreviously written as part of thepython 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, 201358Consider(see sumNumbers.py)• A program that sums 4 numbers thatare 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 usedef main():# input how many numbers will be entered (numberOfValues)numberOfValues = input("How many numbers will be entered? ")for index in range(numberOfValues): # repeat ‘numberOfValues’ timesnum = input("Enter a number: ")runningTotal = runningTotal + num # add the number to the total# error at this lineprint runningTotal,print "Total: ", runningTotal # display the totalmain()
  • 60. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201360Note• The character “t” is a controlcharacter which prints out a tab• A control character is preceded by ‘’so be careful when using thebackslash in a string• Another control character is ‘n’which means new line
  • 61. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201361Note (2)• Notice that the print statement in theinner loop finishes with a comma (,)• This will tell the program not to printa new line• The next output will occur on the sameline
  • 62. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201362Python standard library• Can access the library from the Help menu ineither 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 importstatements
  • 63. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201363Some 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, 201364Import statements• These establish a link with the Python Standardlibrary• Any particular import statement is only requiredonce:• in any given program• in an open Python shell• A new Python shell requires new importstatements if library functions are required
  • 65. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)Built–in functions• A function is a small package ofPython code that performs a certaintask (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 useMay 28, 201365
  • 66. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)Built-in functions• We have already seen someexamples of a built-in function• We have used the input function toretrieve user input from the keyboard• We used the range function in a for loop• We will see more examples of built-infunctions todayMay 28, 201366
  • 67. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201367Functions• When we start writing programs to solve morecomplicated problems, we’ll find that we need towrite large amounts of code• Some programs have millions of lines of code• Putting all of this code into the main functionwould make it impossible to work with• Functions are a way to split code up into piecesthat can be dealt with individually
  • 68. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201368Functions• 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, 201369Advantages of Functions• Code can be written, tested and debuggedin smaller pieces• Allows a divide and conquer strategy fordealing with your code• Functions can be reused in differentsituations meaning you don’t have torewrite code• input ( ) – is a built-in function - think abouthow many times we’ve already used andreused that function
  • 70. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201370Splitting strings• An library function which is the inverse ofconcatenation“John” + ‘ ‘ + “Smith”  John Smithstring.split(“John Smith”) [“John”, “Smith”]• The string has been separated at the space and alist of two strings results
  • 71. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201371The typical function• Functions consist of code that carries out aspecific task (or ‘function’)• Many will require arguments• Many will return (output) data as theprime reason for their existence, otherswill produce what are sometimes calledside effects• Eg input function
  • 72. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201372Familiar 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, floatand 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, 201373Familiar functions• Library functions• math.sqrt(144)  12.0• string.split(“the end”)  [“the”, ”end”]• math.sqrt() - the argument can be of type int orfloat, a float is returned• string.split() – the argument is a string and a listof 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 sqrtimport math # library that holds the function sqrtdef main ( ):num = input ("Please enter a number: ")numRoot = math.sqrt (num); # Use the library namefollowed by .print "The root of ", num, " is ", numRootmain ( )Argument (input)to the functionmath.sqrt()
  • 75. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201375Arguments(see sqrtExample.py)• In the example on the previous slide,‘num’ is an argument of the function‘sqrt’• An argument is an expression whichmust be evaluated.• Eg. math.sqrt (num * 2)
  • 76. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201376Using 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 thiscase main ( )) is the calling function• The argument of the function call becomesessential input for the function• When a function is called, control of executionpasses to the function
  • 77. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201377Using functions• When a function has completed itsprocessing (terminates), controlreturns to the calling function• the calling function can make use ofthe value returned by the calledfunction
  • 78. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201378Reuse of Code• The functions that have been referred to(and many others) are used time and timeagain• This is a significant example of reuse ofcode, saving countless hours of work• Modifying existing programs for slightlydifferent purposes is another importantexample of reuse of code (see labs)
  • 79. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201379The black box• Note that when we use these built-inand library functions, we do not needto know how they work• We only need to know how to use them• We only need to know the inputs andoutputs. The processing is alreadydone.
  • 80. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)Functions• Often require arguments• Expressions or values which provideinput for the function• Normally provide a return value• A value, calculated by the function, thatwe can use in our codeMay 28, 201380
  • 81. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)Examplenum = input (“Enter a number”)“Enter a number” is an argumentThe value entered at the keyboard by theuser becomes the return value of thefunctionThe return value is used in the assignmentexpressionMay 28, 201381
  • 82. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)Today we have coveredMay 28, 201382• Data Types – strings, integers, floats• For loops• Functions
  • 83. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)ReviewMay 28, 201383• Data types – strings, integers, floats• Input() if you enter a string need toenclose in “ “• raw_input() no need for “ “• Functions take arguments as input
  • 84. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201384Review• Integer division gives an integer result (ignoringthe remainder)• Operator % gives the remainder• Built-in functions include: type(), float(), int(),round(), str(), len()• Library functions extend the range of functionssubstantially – they require one-off importstatements
  • 85. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201385Definite loops•A definite loop (called a for loop) repeatsloop code a fixed number of timesfor index in range(x)stmtstmt
  • 86. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)ReviewMay 28, 201386• Functions enable us to design good programs and to re-use code• Functions take input through arguments and return a result to thecalling code (usually)def main() : #define the function mainstmtstmtmain() # call the function main
  • 87. CRICOS Provider Number 00103D(Vic) 01266K (NSW) 02235J (SA)May 28, 201387Remember• Giving full attention to labs is essential –practice, experiment and have fun!• Ensure you have each lab completedbefore the next one• The theory test in week 5 is based onexperience gained from the first four labs(and lectures)

×