Document Details
Uploaded by GenerousChrysoprase
La Trobe University
Tags
Full Transcript
Lecture 5.2 Objects Introduction ◎ So far the types of data we have worked with have been defined for us. ○ i.e. floats, integers, strings, etc. ◎ However, we might want to define our own types. ○ e.g. a "student" type that holds a name and ID. ◎ In this lecture we will learn about objects and ho...
Lecture 5.2 Objects Introduction ◎ So far the types of data we have worked with have been defined for us. ○ i.e. floats, integers, strings, etc. ◎ However, we might want to define our own types. ○ e.g. a "student" type that holds a name and ID. ◎ In this lecture we will learn about objects and how to create our own types using classes. 2 Lecture Overview 1. Objects 2. Creating Classes 3. References and Mutability 3 1. Objects 4 Objects Everywhere! ◎ An object consists of: ○ Related pieces of data (its value), and ○ Functions which use or manipulate that data (its methods). ◎ That is, an object knows stuff and can do stuff. ◎ In Python almost everything is an object. ○ Integers, strings, floats, and booleans are all objects. ○ If a variable can hold it, it's an object! 5 Date Objects ◎ We are going to use dates as an example to explore objects further. ◎ In Python, dates are part of the datetime module. ◎ The following line of code enables the creation of new date objects: ○ from datetime import date ◎ We'll learn more about importing modules in a future lecture. 6 Creating a Date Object ◎ A date has three key pieces of ◎ You could picture the date data: the year, the month, and object representing 21/7/2012 the day. like this: ○ It's a bit like three variables in one. ◎ The action of creating a new object is called instantiation. 7 Creating a Date Object ◎ The code for instantiating a new object is similar to a function call. ◎ The instantiated returned. object is >>> from datetime import date >>> my_date = date(2012, 7, 21) ◎ Here we are instantiating an object to represent the date 21/7/2012. ◎ For a date object, the arguments are the year, month, and day (respectively). 8 Creating a Date Object ◎ If we ask Python about the type of my_date, we'll see something interesting. >>> type(my_date) <class 'datetime.date'> ◎ my_date is not an int, str, or float---it's something else entirely! ◎ We say that my_date is an instance of the date class. 9 Accessing Object Data ◎ We can access the three pieces of data stored in my_date by name. >>> my_date.year 2012 >>> my_date.month 7 >>> my_date.day 21 ◎ We say that year, month, and day are attributes of my_date. ◎ Different types of objects have different attributes. 10 Calling Methods ◎ A method is a function attached to an object that has access to the object's value (data). ◎ The methods on my_date are accessed in a similar way to attributes. >>> my_date.isoweekday() 6 ◎ The isoweekday method determines which day of the week the date falls on. ○ Apparently 21/7/2012 was the sixth day of the week (Saturday). 11 What's The Point? ◎ Grouping related data (value) and behaviour (methods) makes code more manageable. ◎ Instead of keeping track of multiple different variables (year, month, day), we can bundle them together. ◎ We also have easy access to related behaviour (e.g. isoweekday). 12 2. Creating Classes 13 What is a Class? ◎ A class is a template from which objects are instantiated (created). ○ A date class describes what a date is (i.e. that it is a year, a month, and a day). ○ A date object describes a particular date, like 21/7/2012. ◎ One class is typically used to create many objects. 14 Class Vs Object 15 Example: Class - Object 16 Example: Class - Object 17 Creating a Custom Class 18 Creating a Custom Class ◎ By creating a class, we have a custom template which we can use to instantiate objects. ◎ Let's create an Ellipse class that has a width and a height. height width 19 Creating an Ellipse Class ◎ __init__ is a special function called a constructor. class Ellipse: def __init__(self): self.width = 2 self.height = 1 ◎ The code in this constructor will be run every time an Ellipse object is instantiated. ◎ Behind the scenes, Python will provide the object instance as the first parameter (self). 20 Creating an Ellipse Class ◎ When instantiating an Ellipse object, two variables called width and height will be attached to it. class Ellipse: def __init__(self): self.width = 2 self.height = 1 ◎ We call width and height instance variables. ◎ width and height will initially be 2 and 1, respectively. 21 Using Our Ellipse Class >>> ell = Ellipse() >>> type(ell) <class '__main__.Ellipse'> >>> ell.width 2 >>> ell.width = 3 >>> ell.width 3 ◎ Notice that we can assign to instance variables, just like regular variables. ◎ Here we change the width of the ellipse from 2 to 3. 22 Constructor Arguments ◎ Currently, if we want to create an ellipse with a particular width and height, we must: 1. Instantiate an Ellipse. ell = Ellipse() 2. Set the width. ell.width = 5 3. Set the height. ell.height = 7 ◎ To make things simpler, we can rewrite the constructor so that the width and height can be passed in as arguments when instantiating the object. 23 Constructor Arguments class Ellipse: def __init__(self, w, h): self.width = w self.height = h >>> ell = Ellipse(5, 7) >>> ell.width 5 >>> ell.height 7 ◎ Now 2 arguments are expected when instantiating an Ellipse. ◎ These arguments are used to set the initial values of the width and height instance variables. 24 What is a Method? ◎ A method is a function which is attached to an object. ◎ Behind the scenes, Python itself will provide the object instance as the first parameter (self). ○ Sound familiar? This is because the constructor, __init__, is a method! 25 Creating a Method class Ellipse: def __init__(self, w, h): self.width = w self.height = h def calculate_area(self): return 3.14159 * self.width * self.height ◎ Here we have defined a calculate_area method which returns the area of the ellipse. 26 Using a Method >>> ell = Ellipse(5, 7) >>> ell.calculate_area() 109.95565 ◎ Notice that we don't pass an argument for self, Python does that automatically. 27 Method Arguments ◎ A method can accept additional argument after self. ◎ A method can also modify instance variables. ◎ Let's add another method to the Ellipse class for scaling its size. 28 Method Arguments class Ellipse: def __init__(self, w, h): self.width = w self.height = h def calculate_area(self): return 3.14159 * self.width * self.height def scale(self, s): self.width = self.width * s self.height = self.height * s ◎ The argument, s, determines the scale factor. 29 Method Arguments >>> ell = Ellipse(3, 4) >>> ell.calculate_area() 37.699079999999995 >>> ell.scale(2) >>> ell.width 6 >>> ell.height 8 >>> ell.calculate_area() ◎ Notice that calling the scale method changes the width and height of our ellipse object. ○ This changes the value returned by calculate_area. 150.79631999999998 30 Check Your Understanding Q. What are the instance variables of the Box class? class Box: def __init__(self, width, height): self.area = width * height self.full = False 31 Check Your Understanding Q. What are the instance variables of the Box class? A. area and full. ◎ width and height are constructor parameters, not instance variables. ◎ The instance variables are attached to the object instance. class Box: def __init__(self, width, height): self.area = width * height self.full = False 32 3. References and Mutability 33 Memory ◎ Every computer has memory. ○ RAM = random access memory. ◎ Memory provides a temporary storage area for programs to store objects. ○ When the program finishes, the objects in memory are no longer accessible. 34 References ◎ So far we have considered variables to be like boxes which hold objects, but this is not strictly true. ◎ In reality, the objects are stored in memory and variables reference those objects. ◎ A variable can only reference one object. ◎ The same object can be referenced by many variables. ◎ Assigning an object to a variable causes the variable to reference that object. ○ It does not copy the object. 35 Example: References 1 2 3 4 a = 5 b = a c = 7 Objects (in memory) a = c References 36 Example: References 1 2 3 4 a = 5 b = a c = 7 Objects (in memory) 5 a = c a References ◎ The integer 5 is assigned to variable a. ○ a now references the integer 5 in memory. 37 Example: References 1 2 3 4 a = 5 b = a c = 7 Objects (in memory) 5 a = c a b References ◎ The object referenced by a (which is the integer 5) is assigned to variable b. ○ Now both b and a reference the integer 5. 38 Example: References 1 2 3 4 a = 5 b = a c = 7 Objects (in memory) 5 7 a = c a b c References ◎ The integer 7 is assigned to variable c. ○ c now references the integer 7 in memory. 39 Example: References 1 2 3 4 a = 5 b = a c = 7 Objects (in memory) 5 7 a = c a b c References ◎ The integer 7 is assigned to variable c. ○ c now references the integer 7 in memory. 40 Objects Without References ◎ An object can only be accessed if there is a reference to it. ○ That is, when there are no references to an object, that object is no longer accessible by the program. ◎ Python will automatically remove objects without references from memory. ○ This helps to free up space in memory. 41 Example: Objects Without References 1 b = 0 Objects (in memory) 5 a 7 b c References 42 Example: Objects Without References 1 b = 0 Objects (in memory) 5 a 7 b 0 c References ◎ b now references the integer 0 in memory. ◎ There are no references left to the integer 5. ○ That object can be automatically removed by Python. 43 Summary of References ◎ Objects are stored in memory. ◎ Variables reference objects. ○ A variable can only reference one object. ○ The same object can be referenced by many variables. ◎ Assignment can be used to change which object a variable references. ◎ Objects with no references are inaccessible. 44 Immutable Objects ◎ An immutable object cannot have its value changed. ◎ Before this lecture, all of the types we've dealt with have been mutable (int, float, etc.). ◎ When using immutable objects in a computation, a new object is created to represent the result. ○ The original objects do not change. 45 Example: Immutable Objects 1 2 3 a = 0 b = a Objects (in memory) b = b + 1 References 46 Example: Immutable Objects 1 2 3 a = 0 b = a Objects (in memory) 0 b = b + 1 a References ◎ The integer 0 is assigned to variable a. ○ a now references the integer 0 in memory. 47 Example: Immutable Objects 1 2 3 a = 0 b = a Objects (in memory) 0 b = b + 1 a b References ◎ The object reference by a (the integer 0) is assigned to variable b. ○ Now both b and a reference the integer 0. 48 Example: Immutable Objects 1 2 3 a = 0 b = a Objects (in memory) 0 b = b + 1 a 1 b References ◎ The new integer 1 (result of b + 1) is assigned to variable b. ○ b now references the integer 1 in memory. ○ a continues to reference the integer 0. ◉ i.e. the original object still has its original value, 0. 49 Mutable Objects ◎ Mutable objects can be changed. ○ We saw this earlier when we changed the width and height of our Ellipse object. ◎ Object instances created from custom classes are mutable. ◎ If multiple variables refer to the same object, mutating the object will affect all of them. 50 Example: Mutable Objects >>> >>> >>> >>> 6 >>> 6 a = Ellipse(3, 4) b = a a.scale(2) a.width ◎ a and b reference the same Ellipse object. b.width ◎ As long as they hold the same reference, a and b can be used interchangeably. 51 Example: Mutable Objects 1 2 3 a = Ellipse(3, 4) b = a a.scale(2) Objects (in memory) width=3 height=4 a References ◎ The Ellipse object is assigned to variable a. ○ a now references the ellipse object in memory. 52 Example: Mutable Objects 1 2 3 a = Ellipse(3, 4) b = a a.scale(2) Objects (in memory) width=3 height=4 a b References ◎ The object referenced by b is assigned to variable a. ○ Now both b and a reference the same Ellipse object. 53 Example: Mutable Objects 1 2 3 a = Ellipse(3, 4) b = a a.scale(2) Objects (in memory) width=6 height=8 a b References ◎ The scale method mutates the Ellipse object. ◎ The effect will be seen by both a and b. 54 Comparing References ◎ In Python, the is keyword can be used to check whether two variables reference the same object. ◎ This is equivalent to checking whether two arrows point to the same object in our diagrams. 55 Example: Comparing References >>> a >>> b >>> c >>> a True >>> a = Ellipse(3, 4) = a = Ellipse(7, 5) is b Objects (in memory) width=3 height=4 width=7 height=5 is c False a b c References 56 Multiple Instances ◎ Using a class to instantiate multiple objects will result in different object instances. ◎ They are different objects even if they have the same value. ○ That is, they will occupy different locations in memory. ○ Mutating one will not affect the other (in general). 57 Example: Multiple Instances >>> >>> >>> >>> 6 >>> 3 >>> a = Ellipse(3, 4) b = Ellipse(3, 4) a.scale(2) a.width ◎ a and b reference different Ellipse objects. b.width ◎ Mutating a does not affect b. a is b False 58 Example: Multiple Instances 1 2 3 a = Ellipse(3, 4) b = Ellipse(3, 4) Objects (in memory) a.scale(2) References 59 Example: Multiple Instances 1 2 3 a = Ellipse(3, 4) b = Ellipse(3, 4) a.scale(2) Objects (in memory) width=3 height=4 a References ◎ The Ellipse object is assigned to variable a. ○ a now references the ellipse object in memory. 60 Example: Multiple Instances 1 2 3 a = Ellipse(3, 4) b = Ellipse(3, 4) a.scale(2) Objects (in memory) width=3 height=4 a width=3 height=4 b References ◎ A different Ellipse object is instantiated and assigned to variable b. ○ b now references the second Ellipse object in memory. 61 Example: Multiple Instances 1 2 3 a = Ellipse(3, 4) b = Ellipse(3, 4) a.scale(2) Objects (in memory) width=6 height=8 a width=3 height=4 b References ◎ The scale method mutates the first Ellipse object. ◎ The effect will be seen by a only. 62 Check Your Understanding Q. Assuming that the Ellipse class has been defined, what will be the outputs of the shown program? 1 2 3 4 5 6 var1 = Ellipse(2, 2) var2 = Ellipse(3, 4) var1 = var2 var1.height = 5 print(var1.width) print(var1.height) 63 Check Your Understanding Q. Assuming that the Ellipse class has been defined, what will be the outputs of the shown program? A. 3 and 5. 1 2 3 4 5 6 var1 = Ellipse(2, 2) var2 = Ellipse(3, 4) var1 = var2 var1.height = 5 print(var1.width) print(var1.height) 64 Check Your Understanding 1 2 3 4 var1 = Ellipse(2, 2) var2 = Ellipse(3, 4) var1 = var2 var1.height = 5 Objects (in memory) References 65 Check Your Understanding 1 2 3 4 var1 = Ellipse(2, 2) var2 = Ellipse(3, 4) var1 = var2 var1.height = 5 Objects (in memory) width=2 height=2 var1 References 66 Check Your Understanding 1 2 3 4 var1 = Ellipse(2, 2) var2 = Ellipse(3, 4) var1 = var2 var1.height = 5 Objects (in memory) width=2 height=2 var1 width=3 height=4 var2 References 67 Check Your Understanding 1 2 3 4 var1 = Ellipse(2, 2) var2 = Ellipse(3, 4) var1 = var2 var1.height = 5 Objects (in memory) width=2 height=2 var1 width=3 height=4 var2 References 68 Check Your Understanding 1 2 3 4 var1 = Ellipse(2, 2) var2 = Ellipse(3, 4) var1 = var2 var1.height = 5 Objects (in memory) width=2 height=2 var1 width=3 height=5 var2 References ◎ So var1.width is 3 and var1.height is 5. 69 Example Summary 71 In This Lecture We... ◎ Learnt that objects combine data and behaviour. ◎ Defined our own types of objects using classes. ◎ Discovered how references work and the difference between mutable and immutable objects. 72 Next Lecture We Will... ◎ Take a closer look at how strings can be created and manipulated. 73 Thanks for your attention! The slides and lecture recording will be made available on LMS. The “Cordelia” presentation template by Jimena Catalina is licensed under CC BY 4.0. PPT Acknowledgement: Dr Aiden Nibali, CS&IT LTU. 74 Lecture 6.1 Strings Topic 6 Intended Learning Outcomes ◎ By the end of week 6 you should be able to: ○ Express text in Python using different kinds of string literals and escape sequences, ○ Build strings in a neater and more flexible way using fstrings, ○ Read and write data from text files, and ○ Perform various file system operations. 2 Lecture Overview 1. More String Literals 2. Manipulating Strings 3. f-strings and Formatting 3 1. More String Literals 4 What The Literal... ◎ Up until this point, we've been using single quotes around text to create string literals. ○ e.g. 'Programming’ ◎ But if a single quote indicates the end of the string, how do we include a single quote inside the string? ○ 'This doesn't work’ ◎ And what about other special characters, like newlines and tabs? 5 Escape Character ◎ In Python the backslash, \, is an escape character which changes how the character after it is interpreted inside a string. >>> print('Quotes aren\'t a problem') Quotes aren't a problem ◎ \' is an example of an escape sequence. ◎ Placing a backslash before a single quote tells Python "this isn't the end of the string, it's just a single quotation mark". 6 Common Escape Sequences OPERATOR NAME \\ One backslash (\) \' Single quote (') \" Double quote (") \n Newline \t Horizontal tab 7 Example: Escape Sequences >>> print('First line\nSecond line') First line Second line >>> print('\\\'o\'/') \'o’/ >>> print('"Free"') "Free“ >>> print('\"Free\"') "Free" 8 Alternative String Literal Syntax ◎ Although you can use escape sequences to express any string you can think of, it can start to look a bit ugly. ○ e.g. '\'\'\'\n\'\'\‘’ ◎ Python provides alternative ways of expressing string literals which you can choose between. 9 Double Quote Strings ◎ You can use double quotes instead of single quotes. ○ Changes which type of quotes need to be escaped. ◎ Useful when you need to include apostrophes. ○ e.g. "I don't need to escape" ◎ The trade-off is that double quotes now need to be escaped. ○ e.g. "It isn't the \"real\" you" 10 Multiline Strings ◎ You can write a string that spans multiple lines by using three single/double quotes. ◎ This avoids the need to use \n to separate lines. ○ You can still use \n inside multiline strings if you want, though. 11 Example: Multiline Strings >>> ... One Two >>> ... "1" "2" print("""One Two""") print('''"1"\n"2" "3"''') "3" 12 Indentation with Multiline Strings ◎ Note that the space included in the string matters, so things can look a bit weird when code is indented. ring = True if ring: print('''ding dong''') Output: ding dong 13 Indentation with Multiline Strings ◎ Python allows you to break the usual indentation rules inside multiline strings to work around this problem. ring = True if ring: print('''ding dong''') Output: ding dong 14 Check Your Understanding Q. Use a double-quoted, singleline string literal to express the following text: Is it cheap, Or "cheap"? 15 Check Your Understanding Q. Use a double-quoted, single- A. "Is it cheap,\nOr \"cheap\"?" line string literal to express the ◎ \n represents the newline. following text: ◎ \" represents double quotes. Is it cheap, Or "cheap"? 16 2. Manipulating Strings 17 Character Sequences ◎ A string is a sequence of characters. ◎ The length of a string is the number of characters in the string. ○ You can use the len built-in function to get this value. ○ e.g. len('Avocado') returns 7. ◎ An escape sequence counts as 1 character. ○ e.g. len('A\nB') returns 3. 18 Character Sequences ◎ The index of a character indicates its position in the string. ◎ Indices start at 0 (so the first character is at index 0). ◎ The last index is the length of the string minus 1. 19 Character Sequences 'Star Wars' S t a r 0 1 2 3 4 W a r s 5 6 7 8 ◎ The character at index 1 is t. ◎ The character at index 4 is the space character, . 20 Negative Indices 'Star Wars' S t a r -9 -8 -7 -6 -5 W a r s -4 -3 -2 -1 ◎ In Python, you can use negative indices to count backwards from the end of the string. ◎ The character at index -1 is the last character of the string (in this case, s). 21 Indexing a String ◎ You can use square brackets [] to retrieve a character by its index. ◎ This is called indexing a string. ◎ You can use normal or negative indices. >>> movie = 'Star Wars' >>> movie[0] 'S' >>> movie[-2] 'r' 22 Slicing a String ◎ You can also use square brackets to retrieve a segment of a string (a substring). >>> movie = 'Star Wars' >>> movie[0:3] 'Sta' >>> movie[-4:-1] ◎ This is called slicing a string. ◎ Notice that the character at the first index is included but the character at the last index is excluded. 'War' 23 Slicing a String ◎ If you omit the first index, all characters from the start of the string are returned. >>> movie = 'Star Wars' >>> movie[:4] 'Star' >>> movie[-4:] 'Wars' ◎ If you omit the second index while slicing, all characters to the end of the string are returned. 24 Looping Over Characters ◎ Since a string is a sequence of characters, it can be used in a for loop to iterate over each character. ◎ Each item is a string of length 1 containing a single character, starting with the first character. 25 Example: Looping Over Characters dna = 'GATTACA' for nucleotide in dna: if nucleotide == 'G' or nucleotide == 'A': print(nucleotide) Output: G A A A 26 Searching ◎ The find string method returns the position of the first occurrence of a smaller substring within a larger string. >>> s = "Where's Wally?" >>> s.find('W') 0 >>> s.find('Wally') 8 ◎ The position returned is the index of the first character of the matching part of the string. 27 Failing to Find ◎ If the string does not contain the substring, -1 is returned. >>> s = "Where's Wally?" >>> s.find('Odlaw') -1 >>> s.find('w') -1 28 Searching Backwards ◎ You can find the last instance of the substring (instead of the first) but using the rfind string method. >>> s = "Where's Wally?" >>> s.find('e') 2 >>> s.rfind('e') 4 29 Case and String Comparison ◎ It is important to keep in mind that the case of letters matters when comparing strings. >>> 'earth' == 'Earth' False >>> 'grand canyon'.find('canyon') 6 >>> 'Grand Canyon'.find('canyon') -1 ◎ An uppercase letter (e.g. 'A') is different to a lowercase letter (e.g. 'a'). 30 Case and String Comparison ◎ To ignore case, you can convert all of the letters to either lowercase or uppercase before comparing. ○ lower converts all letters to lowercase. ○ upper converts all letters to UPPERCASE. >>> 'earTH'.lower() == 'Earth'.lower() True >>> 'grand canyon'.upper().find('CANYON') 6 >>> 'grand canyon'.upper().find('canyon') -1 31 String Replacement ◎ The replace method can be used to replace parts of a string. It takes 2 arguments: ○ First: The substring to replace. ○ Second: The replacement. >>> s = "Where's Wally?" >>> s.replace('ly', 'do') "Where's Waldo?“ >>> s.replace('W', 'R') "Rhere's Rally?“ >>> s "Where's Wally?" ◎ A new string is returned (the original string is not modified). 32 String Replacement ◎ If the substring isn't found, the string is returned unchanged. ◎ The second argument (the replacement) can be an empty string. ○ Using an empty string will result in the found substrings being replaced with nothing (i.e. removed). 33 Example: Removing Vowels # File: remove_vowels.py vowels = 'aeiouAEIOU' s = input('Enter some text: ') for vowel in vowels: s = s.replace(vowel, '') print(s) Example run: $ python remove_vowels.py Enter some text: A fox is orange. fx s rng. 34 Check Your Understanding Q. What is the result of the following Python expression? 'No worries, Oliver'.rfind('o') 35 Check Your Understanding Q. What is the result of the following Python expression? 'No worries, Oliver'.rfind('o') A. 4. ◎ There are two instances of the substring 'o'. ○ Capital 'O' is different to lowercase 'o’. ◎ rfind searches backwards, so it finds the last 'o’. ◎ The index of the last 'o' is 4. 36 3. f-strings and Formatting 37 String Concatenation Can Be Ugly (and it's not even beautiful on the inside) ◎ So far we have built strings using the + operator. ◎ We used str() to convert other types of data into strings prior to concatenation. ◎ The code from this can become messy. acc = 1 bal = 23.0 print('Account ' + str(acc) + ' balance is $' + str(bal)) 38 f-strings ◎ Python provides f-strings as a convenient way of building strings. ◎ An f-string is a string literal prefixed with an f. ◎ When writing an f-string, you can include Python expressions by using curly brackets. ○ This part of an f-string is called a replacement field. ◎ f-strings reduce the need for + and str(). 39 f-strings # With string concatenation acc = 1 bal = 23.0 print('Account ' + str(acc) + ' balance is $' + str(bal)) # With an f-string acc = 1 bal = 23.0 print(f'Account {acc} balance is ${bal}') ◎ Note that the f-string has an f before the first quote. ◎ {acc} and {bal} are replacement fields. 40 Formatting Values ◎ There are multiple ways of expressing a number. ○ e.g. the number 5 can be written as 5, 5.0, 5.00, etc. ◎ A programmer should be able to choose how a number is displayed depending on the application. ○ For example, dollar amounts are usually expressed using two decimal places (e.g. $1.99). ○ Precise distance measurements might be expressed using many decimal places. 41 Format Specifiers ◎ You can specify how values are to be formatted in an fstring. ◎ This is achieved by including a format specifier in a replacement field. ◎ Format specifiers are actually quite in-depth and allow for lots of customisation. ◎ We will now cover some common kinds of format specifiers. 42 Format Specifiers ◎ A format specifier can be added to a replacement field. ◎ The format specifier is separated from the expression using a colon, :. 43 Number of Decimal Places ◎ You can specify the number of decimal places shown. ◎ Appropriate rounding will be applied. >>> x = 0.6666 >>> f'{x:.3f}' '0.667' >>> f'{x:.0f}' '1' >>> f'{x:.6f}' '0.666600' ◎ Trailing zeros will be added if necessary. 44 Number of Decimal Places ◎ The letter "f" in the format specifier indicates that the value should be presented as a number with a fixedlength fractional part. ◎ This is called the presentation type or format code. >>> x = 0.6666 >>> f'{x:.3f}' '0.667' >>> f'{x:.0f}' '1' >>> f'{x:.6f}' '0.666600' 45 Number of Decimal Places ◎ The ".#" in the format specifier indicates the number of decimal places. >>> x = 0.6666 >>> f'{x:.3f}' '0.667' >>> f'{x:.0f}' '1' >>> f'{x:.6f}' '0.666600' 46 Width ◎ The minimum space that the formatted value will occupy can be specified. ○ The "width" in terms of number of characters. >>> f'{123:6d}' ' 123' >>> f'{123:2d}' '123' >>> f'{0.11:6.2f}' ' 0.11' ◎ The extra room is filled with space characters. ◎ Useful for output. aligning program 47 Width ◎ Notice that spaces are added to the start to ensure that the minimum width is met. >>> f'{123:6d}' ' 123' >>> f'{123:2d}' '123' >>> f'{0.11:6.2f}' ' 0.11' ◎ Strings that are too long are not affected. 48 Width ◎ Using the "d" presentation type indicates that the value should be presented as a whole number without a fractional part. >>> f'{123:6d}' ' 123' >>> f'{123:2d}' '123' >>> f'{0.11:6.2f}' ◎ You can only use "d" when the value is an integer. >>> f'{12.3:6d}' ' 0.11' Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Unknown format code 'd' for object of type 'float' 49 Width ◎ Here’s a times table program that produces nicely aligned output using format specifiers. ◎ Can you see how the spaces automatically added to smaller numbers result in visually pleasing formatting? a = int(input('Times table: ')) for b in range(1, 13): print(f'{a:2d} x {b:2d} = {a * b:3d}') Times table: 11 11 x 1 = 11 11 x 2 = 22 11 x 3 = 33 11 x 4 = 44 11 x 5 = 55 11 x 6 = 66 11 x 7 = 77 11 x 8 = 88 11 x 9 = 99 11 x 10 = 110 11 x 11 = 121 11 x 12 = 132 50 Width for String Values ◎ String values can also be formatted with a minimum width. >>> f'{"hello":8s}' 'hello ‘ >>> f'{96:8s}' Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Unknown format code 's' for object of type 'int' ◎ In order to format a string, you should use the "s" presentation type instead of "d" or "f". ◎ You can only use "s" when the value is a string. 51 Alignment ◎ Notice that, unlike numbers, strings are left-aligned by default rather than right-aligned. ○ Spaces are added to the end, not the start. ◎ You can force a particular alignment using < for left alignment and > for right alignment. >>> f'{"hello":8s}' 'hello ' >>> f'{"hello":>8s}' ' hello' >>> f'{42:6d}' ' 42' >>> f'{42:<6d}' '42 ' 52 Check Your Understanding Q. What will the output of the shown program be? speed_kph = 40.0 time_h = 0.5 print(f'|{time_h * speed_kph:<6.2f}|') 53 Check Your Understanding Q. What will the output of the shown program be? speed_kph = 40.0 time_h = 0.5 A. |20.00 | (note the space between the 0 and the |). print(f'|{time_h * speed_kph:<6.2f}|') 54 Check Your Understanding Q. What will the output of the shown program be? speed_kph = 40.0 time_h = 0.5 print(f'|{time_h * speed_kph:<6.2f}|') A. |20.00 | (note the space between the 0 and the |). ◎ The result of the expression is 20.0. 55 Check Your Understanding Q. What will the output of the shown program be? speed_kph = 40.0 time_h = 0.5 print(f'|{time_h * speed_kph:<6.2f}|') A. |20.00 | (note the space between the 0 and the |). ◎ The .2f part of the format specifier specifies presentation with 2 decimal places (i.e. 20.00). 56 Check Your Understanding Q. What will the output of the shown program be? speed_kph = 40.0 time_h = 0.5 print(f'|{time_h * speed_kph:<6.2f}|') A. |20.00 | (note the space between the 0 and the |). ◎ The 6 part of the format specifier specifies that anything less than 6 characters wide will have spaces added to make it 6 characters wide. 57 Check Your Understanding Q. What will the output of the shown program be? speed_kph = 40.0 time_h = 0.5 print(f'|{time_h * speed_kph:<6.2f}|') A. |20.00 | (note the space between the 0 and the |). ◎ The < part specifies that the spaces should be added to the end (left-aligned). ◎ Since 20.00 is 5 characters wide, the result of <6 is that one space character will be added to the end. 58 Check Your Understanding Q. What will the output of the shown program be? speed_kph = 40.0 time_h = 0.5 print(f'|{time_h * speed_kph:<6.2f}|') A. |20.00 | (note the space between the 0 and the |). ◎ The pipe characters (|) don't have any special meaning, they are just part of the string. 59 Summary 60 In This Lecture We... ◎ Used escape sequences to include characters in strings that can't be written in a straightforward way. ◎ Explored different ways of writing string literals in Python. ◎ Manipulates strings in various ways. ◎ Used f-strings to build strings in a neater and more flexible way. 61 Next Lecture We Will... ◎ Learn how to read and write data in text files. 62 Thanks for your attention! The slides and lecture recording will be made available on LMS. The “Cordelia” presentation template by Jimena Catalina is licensed under CC BY 4.0. PPT Acknowledgement: Dr Aiden Nibali, CS&IT LTU. 63 Lecture 6.2 Files Introduction 2 Introduction ◎ Up until this point, the ways in which our programs handled input and output have been limited. ○ Input was always entered by the user. ○ Output was always displayed to the user. ◎ If the user want to save the output, they would need to copy it or write it down. ◎ This is quite frankly lame, and I wouldn't want to be friends with a program that made me copy hundreds of lines of output manually. 3 Introduction ◎ We also had no way of saving data for future runs of the program. ○ i.e. the program had no way of remembering anything about previous runs. ◎ In this lecture, we will learn about reading and writing text files as an alternative form of input and output. ◎ This will also allow us to write programs which process existing data stored in text files. 4 Lecture Overview 1. Reading Text Files 2. Writing Text Files 3. File System Operations 5 1. Reading Text Files 6 Text Files ◎ A text file is like a string saved on a computer's storage drive (hard drive or solid state drive). ◎ It's very likely that you have come across text files before. ◎ Some examples of files which are text files include .txt files, CSV files, HTML pages, and Python source code. ◎ As a general rule of thumb, if you can edit a file in Notepad, it’s a text file. 7 Binary Files ◎ Files which are not text files are called binary files. ◎ Binary files do not fundamentally represent their data using human-readable characters. ◎ Some examples of files which are binary files (and not text files) are JPEG images, MP3 songs, ZIP archives, and Word documents. 8 Opening Files ◎ In order to read from or write to a file, it must be opened. ○ Python's open built-in function opens a file. ◎ In Python, opening a file successfully will result in a file object which represents that file. 9 Opening Files >>> f = open('colours.txt') >>> f <_io.TextIOWrapper name='colours.txt' mode='r' encoding='UTF-8'> red green blue colours.txt 10 File Objects ◎ A file object has the information Python requires to access the contents of a file. ○ It also contains the name of the file. ◎ A file object does not represent the data contained within the file. ○ Data is accessed using methods on the file object for reading and writing data. 11 Failing to Open ◎ A call to open can fail, which will result in an error being raised. ○ e.g. if the file doesn't exist. ◎ For now, we will simply assume that the files we are opening are accessible. >>> open('404.txt') Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: '404.txt' ◎ FileNotFoundError means exactly what you think it means. ◎ In a future lecture, we will discuss how to handle errors. 12 Reading Everything At Once ◎ The read method of a file object returns the entire content of the file as a string. ◎ Here you can see the lines are separated using the newline character, \n. >>> f = open('colours.txt') >>> s = f.read() >>> s 'red\ngreen\nblue\n' red green blue colours.txt 13 Reading Line-By-Line ◎ Sometimes it is not a good idea to read all of a file at once. ○ For large files this could be extremely slow. ○ Very, very large files might not fit in memory. ○ In other situations, it might not be convenient to work with the entire file all at once. ◎ The readline method can be used to read one line at a time. 14 Reading Line-By-Line >>> f = open('colours.txt') >>> f.readline() 'red\n’ >>> f.readline() 'green\n’ >>> f.readline() 'blue\n’ ◎ Reading a line will "advance" the cursor position in the file. ◎ Each line includes the newline character at the end. >>> f.readline() '' red green blue colours.txt ◎ Once the end of the file is reached, calls to readline return the empty string, ''. 15 Reading Line-By-Line ◎ The newline character can be removed from lines using string slicing or string replacement. >>> f = open('colours.txt') >>> line = f.readline() >>> line 'red\n’ >>> line[:-1] 'red’ >>> line.replace('\n', '') 'red' 16 Returning to the Start of the File ◎ You can return the cursor position to the beginning of the file by using the seek file object method and passing 0 in as the argument. ◎ This allows you to read the same lines multiple times if you wish. >>> f = open('colours.txt') >>> f.readline() 'red\n’ >>> f.readline() 'green\n’ >>> f.seek(0) 0 >>> f.readline() 'red\n' red green blue colours.txt 17 Reading with a For Loop ◎ For convenience, Python allows you to use a file object in a for loop. ◎ The file object acts like a sequence of lines. ◎ Behind the scenes, text will be read from the file one line at a time. 18 Example: Displaying File Contents # File: display_file.py file_name = input('Enter file name: ') file = open(file_name) print('---') for line in file: print(line[:-1]) $ python display_file.py Enter file name: colours.txt --red green blue red green blue colours.txt 19 Check Your Understanding Q. Based on your understanding of how readline works, what do you think the result of calling read twice in a row on the same file object would be? 20 Check Your Understanding Q. Based on your understanding of how readline works, what do you think the result of calling read twice in a row on the same file object would be? A. The first call returns the entire contents of the file as a string. The second call returns an empty string. This is because after the first read call, the cursor position is at the end of the file. 21 Reading from file steps 22 Examples of text files 23 Examples 24 Examples 25 2. Writing Text Files 26 File Modes ◎ When opening a file you can specify a file mode. ◎ The file mode determines: ○ Whether the file object allows reading. ○ Whether the file object allows writing. ○ The initial file cursor position. ○ Whether existing files should have their contents kept or erased. ○ Whether the file should be created if it doesn't already exist. 27 File Modes ◎ The default file mode is 'r’. ◎ This file mode allows for the file to be read from, but not written to. f = open('colours.txt') ...is short for... f = open('colours.txt', 'r') 28 Common File Modes MODE READ WRITE POSITION KEEP CONTENTS? CREATE FILE? 'r' 🗸 ✗ Start 🗸 ✗ 'w' ✗ 🗸 Start ✗ 🗸 'a' ✗ 🗸 End 🗸 🗸 'r+' 🗸 🗸 Start 🗸 ✗ 'w+' 🗸 🗸 Start ✗ 🗸 'a+' 🗸 🗸 End 🗸 🗸 29 Common File Modes ◎ For example, when using mode 'a+': ○ It will be possible to both read and write. ○ If the file exists, existing contents will be kept. ○ If the file does not exist, it will be created. ○ The cursor position will initially be at the end. MODE 'a+' READ 🗸 WRITE POSITION KEEP CONTENTS? CREATE FILE? 🗸 End 🗸 🗸 30 Writing Text ◎ To write to a file, you must open it using a file mode which enables writing, such as 'w'. ○ e.g. open('results.txt', 'w’) ◎ You can write to a file using the write method. ◎ When you have finished writing to a file, it should be closed using the close method. ○ This ensures that data is saved to the file correctly. 31 Example: Writing Text f = open('gifts.txt', 'w') f.write('A gift is nice,\n') f.write('but two gifts are better!\n') f.close() Output: A gift is nice, but two gifts are better! gifts.txt Notice that we had to include newline characters (\n) to explicitly indicate when we want a new line in the file to start. This is different from print statements, which automatically add a newline after every message displayed to the user. 32 Appending Text ◎ Opening an existing file with file mode 'w' or 'w+' will erase the contents of the file. ○ Be careful! This could cause you to lose data. ◎ If you want to keep the existing contents of the file you are writing to, use the file mode 'a'. ○ The letter 'a' stands for append. ○ Append means "add to the end". 33 Example: Work Tracker # File: work_tracker.py print('Enter work completed:') work = input('> ') work_file = open('work_log.txt', 'w') work_file.write(work + '\n') work_file.close() 34 Example: Work Tracker $ python work_tracker.py Enter work completed: Dusted the cupboards > Dusted the cupboards work_log.txt 35 Example: Work Tracker $ python work_tracker.py Enter work completed: Vacuumed the floors > Dusted the cupboards $ python work_tracker.py Enter work completed: work_log.txt > Vacuumed the floors 36 Example: Work Tracker # File: work_tracker.py print('Enter work completed:') work = input('> ') work_file = open('work_log.txt', 'w') work_file.write(work + '\n') work_file.close() ◎ Every time the program is run, work_log.txt will start as a blank file. ◎ Any data already in work_log.txt will be erased. 37 Example: Work Tracker # File: work_tracker2.py print('Enter work completed:') work = input('> ') work_file = open('work_log2.txt', 'a') work_file.write(work + '\n') work_file.close() ◎ Here we have changed the file mode to 'a'. ◎ The first time the program is run, a file called work_log2.txt will be created. ◎ On each subsequent run, a new line of text will be appended to the file. 38 Example: Work Tracker $ python work_tracker2.py Enter work completed: Dusted the cupboards > Dusted the cupboards work_log2.txt 39 Example: Work Tracker $ python work_tracker2.py Enter work completed: Dusted the cupboards Vacuumed the floors > Dusted the cupboards $ python work_tracker2.py Enter work completed: work_log2.txt > Vacuumed the floors 40 Check Your Understanding Q. What will be the contents of output.txt after the program finishes running? f = open('output.txt', 'w') for i in range(5): f.write(str(i)) f.close() 41 Check Your Understanding Q. What will be the contents of output.txt after the program finishes running? f = open('output.txt', 'w') for i in range(5): f.write(str(i)) f.close() A. 01234 output.txt ◎ range(5) is the sequence 0,1,2,3,4. ◎ Since the strings that we wrote to the file did not end in a newline, they were all written as part of the same line. 42 Writing to file steps 43 Examples 44 3. File System Operations 45 Files and Directories ◎ There are two types of entries in a computer file system: files and directories. ○ A directory contains other files and/or directories. ○ A file contains data. ◎ Directories are sometimes called "folders". ◎ The open function is for working with files only (not directories). 46 File System Paths ◎ A path is the location of a file or directory. ○ e.g. on Windows: C:\Program Files\Microsoft Office ○ e.g. on Mac OS: /private/etc/hosts ◎ Every file and directory on your computer has a path. ◎ The first argument to open is the path of the file to open. 47 File System Paths ◎ An absolute path is fullyqualified and globally unique on your computer. ◎ If you create a file using the absolute path "C:\fruit.txt", it doesn't matter where you run the program from. ◎ A relative path is relative to the current directory. ◎ If you create a file using the relative path "fruit.txt", it will be placed in the directory that you ran the program from. 48 The os Module ◎ Python provides many functions for working with the file system using paths. ◎ Many of these functions are part of the os module. ◎ Use the following line of code to import the os module: import os 49 Identifying Paths ◎ To see whether a path refers to a file, use ◎ To see whether a path refers to a directory, use ◎ True will be returned if path refers to an existing file. ◎ True will be returned if path refers to an existing directory. os.path.isfile(path) os.path.isdir(path) 50 Example: Identifying Paths # File: identify_path.py import os path = input('Enter a path: ') if os.path.isfile(path): print(f'"{path}" is a file.') elif os.path.isdir(path): print(f'"{path}" is a directory.') else: print(f'"{path}" does not exist.') ◎ This program asks the user to input a path, then outputs whether the path refers to a file or directory. ◎ Works for both absolute and relative paths. 51 Example: Identifying Paths $ python identify_path.py Enter a path: my directory "my directory" is a directory. $ python identify_path.py Enter a path: some_file.txt "some_file.txt" is a file. $ python identify_path.py Enter a path: nothing "nothing" does not exist. 52 Creating Directories ◎ Earlier we saw that files can be created simply by opening them in certain file modes. ◎ Directories can be created using os.mkdir(path). ◎ mkdir is directory". short for >>> import os >>> os.path.isdir('my_dir') False >>> os.mkdir('my_dir') >>> os.path.isdir('my_dir') True "make 53 Listing Directory Entries ◎ Finding the names of files and directories contained within a directory is called listing a directory. ◎ Listing directories is useful when: ○ Searching for files. ○ Batch processing files. ◎ Calling os.listdir(path) will return a sequence of file and directory names in the specified directory. ◎ You can loop over these using a for loop. 54 Renaming Files/Directories ◎ Calling os.rename(source_path, dest_path) will rename the file/directory at source_path to the new name dest_path. ◎ Moving a file is equivalent to renaming it. 55 Removing Files ◎ Calling os.remove(path) will remove the file at path. ◎ This function cannot be used to remove directories. 56 Removing Directories ◎ Calling os.rmdir(path) will remove the directory at path. ○ rmdir is short for "remove directory". ◎ This function can only be used to remove empty directories. 57 File System Operations Reference Table FUNCTION DESCRIPTION os.path.isfile Is an existing file? os.path.isdir Is an existing directory? os.mkdir Create a directory. os.listdir List a directory. os.rename Rename/move a file/directory. os.remove Remove a file. os.rmdir Remove a directory. EXAMPLE os.path.isfile('book.txt') os.path.isdir('Songs') os.path.mkdir('results') os.listdir('input_files') os.rename('old.txt', 'new.txt') os.remove('temporary.dat') os.rmdir('empty_dir') 58 Check Your Understanding Q. Using the file operations explained in this lecture, how might you go about deleting a directory containing files (but no sub-directories)? 59 Check Your Understanding Q. Using the file operations explained in this lecture, how might you go about deleting a directory containing files (but no sub-directories)? A. You could list the files in the directory, delete those files, and then delete the now empty directory. import os d = 'my_dir' for file_name in os.listdir(d): p = os.path.join(d, file_name) os.remove(p) os.rmdir(d) 60 Summary 61 In This Lecture We... ◎ Loaded program input by reading from text files. ◎ Saved program output by writing to text files. ◎ Performed various file system operations with Python code. 62 Next Lecture We Will... ◎ Represent and manipulate arbitrary sequences of items using lists. 63 Thanks for your attention! The slides and lecture recording will be made available on LMS. The “Cordelia” presentation template by Jimena Catalina is licensed under CC BY 4.0. PPT Acknowledgement: Dr Aiden Nibali, CS&IT LTU. 64 Lecture 5.1 Functions Topic 5 Intended Learning Outcomes ◎ By the end of week 5 you should be able to: ○ Define and call functions to reuse sections of code, ○ Define custom types of objects with classes, and ○ Understand how references work, and the difference between mutable and immutable objects. 2 Lecture Overview 1. Function Calls 2. Writing Functions 3. Parameters, Scope, and Return Values 3 1. Function 4 What is a Function? 5 What is a Function? 6 What is a Function? 7 What is a Function? 8 Function Calls ◎ To run the code in a function, you must call the function. ◎ We have already been using function calls! Here are some that should look familiar: ○ print('Hello') ○ input('Enter your age: ‘) ○ range (1,6) 9 Arguments ◎ The inputs supplied to a function are called arguments. ◎ Any kind of expression can be used as an argument: ○ Literals (e.g. type(65.3)), ○ Variables (e.g. str(temperature)), or ○ Complex expressions (e.g. print('$' + str(x * 2))). ◎ Multiple arguments are separated using commas. 10 Things Functions Can Do ◎ A function can cause an effect. ○ For example, the print function causes an output message to be displayed. ◎ A function can compute and return a result. ○ For example, the str function* (str(x * 2)) converts its argument to a string and returns the result. 11 Check Your Understanding Q. What is the second argument in this function call? print('I, Jimbo, am', 18, 'years old') 12 Check Your Understanding Q. What is the second argument in this function call? print('I, Jimbo, am', 18, 'years old') A. 18 is the second argument. ◎ print is the function name, not an argument. ◎ 'I, Jimbo, am' is the first argument. ○ These commas are part of the string. ◎ 'years old' is the third argument. 13 Pythom Functions 14 Built-in Functions import builtins print (dir(builtins)) 15 Built-in Functions 16 Built-in Functions 17 2. Writing Functions - User-Defined Functions 18 Pythom Functions: User-Defined Functions 19 Writing a Function: User-Defined Functions 20 Writing a Function: User-Defined Functions 21 Writing a Function: User-Defined Functions 22 Writing a Function: User-Defined Functions 23 Writing a Function: Control Flow ◎ When a function is called, control flow jumps to the first statement in the function. ◎ When the function finishes, control flow is returned to the place that the function was called from. ◎ The statements in a function are not executed when the function is defined. 24 Example: Control Flow 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() ◎ Let's look at the control flow for this program. ◎ The statements within the tick function are executed with each function call. print('Goodbye!') 25 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() print('Goodbye!') 26 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? print('Goodbye!') 27 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? print('Goodbye!') 28 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick print('Goodbye!') 29 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick Tock print('Goodbye!') 30 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick Tock I am a clock print('Goodbye!') 31 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick Tock I am a clock print('Goodbye!') 32 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick Tock I am a clock Tick print('Goodbye!') 33 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick Tock I am a clock Tick Tock print('Goodbye!') 34 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() print('Goodbye!') Who am I? Tick Tock I am a clock Tick Tock Goodbye! 35 Don't Repeat Yourself ◎ In software development, there's a good practice called DRY (don't repeat yourself). ◎ DRY code avoids code duplication (writing similar code multiple times). ◎ Functions are an effective tool for producing DRY code. 36 Example: Code Duplication 1 2 3 4 5 6 water = 0.712 print('Covered in water:') print(str(water * 100) + '%') land = 1 - water print('Covered in land:') print(str(land * 100) + '%') ◎ Lines 3 and 6 have the same purpose: to display a percentage. ◎ Problems: ○ It is cumbersome to copy/paste. ○ Changing the way percentages are displayed requires multiple edits. ◎ This is error-prone. 37 Example: Code Duplication 1 2 3 4 5 6 water = 0.712 print('Covered in water:') print(str(round(water*100))+'%') land = 1 - water print('Covered in land:') print(str(round(land*100))+'%') ◎ Here we had to edit 2 lines to print percentages as round numbers. ◎ In a larger program, many more edits could be required. ○ It's easy to forget one, or to make a mistake. 38 Example: DRY Code with a Function 1 2 3 4 5 6 7 8 9 def print_percent(x): print(str(round(x*100))+'%') water = 0.712 print('Covered in water:') print_percent(water) land = 1 - water print('Covered in land:') print_percent(land) ◎ Lines 1--2 define the print_percent function. ○ The function has one parameter, x. ◎ Lines 6 and 9 call the function. ○ The code in print_percent will be executed with x set to the argument value. 39 Check Your Understanding Q. How many times will the shown program print output? 1 2 3 4 5 6 7 def funky_func(): for i in range(3): print('Groovy!') funky_func() if 2 + 2 == 5: funky_func() funky_func() 40 Check Your Understanding Q. How many times will the shown program print output? A. 6 times. ◎ Each time funky_func is called, 'Groovy!' is printed 3 times. ◎ funky_func is called twice (lines 4 and 7). ○ Not called from line 6 since the if statement condition is false. 1 2 3 4 5 6 7 def funky_func(): for i in range(3): print('Groovy!') funky_func() if 2 + 2 == 5: funky_func() funky_func() 41 3. Parameters, Scope, and Return Values 42 Parameters and Arguments. ◎ Parameters are function input variables declared as part of defining a function. ○ A function can have zero, one, or many parameters. ○ Act like "placeholders". ◎ Arguments are the values assigned to parameters when calling a function. ○ A function must receive one argument per parameter. 43 Example: Parameters and Arguments 1 2 3 4 def print_product(x, y): print(x * y) print_product(3, 5) ◎ x and y are parameters. ◎ Line 1: "define a function called print_product with two parameters, x and y". 44 Example: Parameters and Arguments 1 2 3 4 def print_product(x, y): print(x * y) ◎ 3 and 5 are arguments. print_product(3, 5) ◎ Line 4: "call print_product with 3 as the first argument and 5 as the second argument". ◎ The order matters---x will take the value of 3, and y will take the value of 5. 45 Function Default Arguments ◎ A default argument is a value given to a parameter when no argument is explicitly provided in the function call. ◎ You can specify default arguments as part of the function definition. 46 Function Default Arguments 47 Example: Default Arguments def print_ticket(age, max_child_age=12): if age <= max_child_age: print('Child') else: print('Full fare') print_ticket(5) #=> Child print_ticket(15) #=> Full fare print_ticket(15, 18) #=> Child 48 Default Arguments Beware! Once you specify a default argument for one parameter, all parameters which come after it must also have default arguments. >>> def do_something(a, b=1, c): ... pass ... File "<stdin>", line 1 SyntaxError: non-default argument follows default argument 49 Named Arguments ◎ Arguments can also be specified by name. ◎ These kinds of arguments are called named arguments (or keyword arguments). def divide(num, denom): print(num / denom) divide(5, 2) #=> 2.5 divide(denom=2, num=5) #=> 2.5 divide(5, denom=2) #=> 2.5 divide(num=5, 2) #=> Error ◎ The order of named arguments doesn't matter. ◎ All named arguments must appear after positional arguments. 50 Named Arguments ◎ In most cases you will not need to use named arguments. ◎ If you think that they will make your code more understandable, go ahead and use them. ◎ Occasionally you will encounter functions that do actually require named arguments. ○ We won't see many in this subject. ○ It will be pointed out to you when we do. 51 Example: Variable Scope def double_number(x): y = x * 2 double_number(5) print(y) Traceback (most recent call last): File "scope.py", line 5, in <module> print(y) NameError: name 'y' is not defined ◎ The code outside of double_number can't "see" x and y. ○ It's as if those variables don't exist. ◎ As a result, the line containing the print statement will raise an error. 52 Return Values ◎ If variables created inside a function aren't accessible outside it, then how do we get the result of a calculation performed inside the function? ○ Answer: use a return value. ○ A function can return one or more values using the return statement. 53 Return Values. ◎ A function can have a return value, which is a value from inside the function which is returned to the caller of the function. ◎ The function call will evaluate to the returned value. ◎ We've actually already used several functions with return values. ○ e.g. abs(-3) evaluates to 3 (its return value). ◎ We can specify which value is returned from a function by using a return statement. 54 Return Statements ◎ A return statement can only be used inside a function. ◎ In Python, a return statement consists of the return keyword followed by a value to be returned. ○ return 'A cool result' ○ return x + 1 ◎ When a return statement is encountered, function execution finishes and the specified value is returned to the caller. 55 Example: Return Statement def double_number(x): y = x * 2 return y z = double_number(5) ◎ The value of variable y is returned from function double_number. print(z) ◎ This means that the expression double_number(5) will evaluate to 10. 56 Example: Return Statement 57 Finishing Function Execution Early ◎ After a return statement is encountered, the function finishes immediately. ○ Statements which appear after the return statement will not be executed. ○ This is similar to continue and break in loops. ◎ The return keyword can be used by itself to finish a function without also returning a value. 58 Check Your Understanding Q. What is the output of the shown program? 1 2 3 4 5 6 def do_something(n): if n < 0: return 0 return n ** 2 print(do_something(-4)) 59 Check Your Understanding Q. What is the output of the shown program? A. 0. ◎ do_something is called with -4 as the first argument (so n is 4). ◎ -4 is less than 0, so 0 is returned. ◎ Line 4 is not reached. 1 2 3 4 5 6 def do_something(n): if n < 0: return 0 return n ** 2 print(do_something(-4)) 60 Summary 61 In This Lecture We... ◎ Used function calls to execute pieces of existing code. ◎ Created our own functions to enable code reuse. ◎ Learnt the difference between arguments and parameters. ◎ Discovered how return statements can be used to get results out of a function. 62 Next Lecture We Will... ◎ Learn about another construct for tackling repetition in code: objects. 63 Thanks for your attention! The slides and lecture recording will be made available on LMS. The “Cordelia” presentation template by Jimena Catalina is licensed under CC BY 4.0. PPT Acknowledgement: Dr Aiden Nibali, CS&IT LTU. 64