functions, list and string methods
TRANSCRIPT
![Page 1: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/1.jpg)
Functions and (list and string methods)
Python SIG – PYA Class 3 – 3/10/15
![Page 2: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/2.jpg)
These are things you should know pretty well by now:
• raw_input, printing• help(), dir(), online docs, searching the
internet• The fact that Python is awesome. (No, really,
I’m just being completely objective here.)
![Page 3: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/3.jpg)
(Revision of)Useful built-ins
• len()• range() (and xrange())• sum(), max(), min()• int(), float(), str()• dir() – use it to find list and string methods• Use help() to find out about them
![Page 4: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/4.jpg)
(Revision of)if else elif
if SomethingThatEvaluatesToABoolean:# code
elif SomethingElseThatEvaluatesToABoolean:# code
else:# code
![Page 5: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/5.jpg)
(Revision of)String formatting
• What is it? (Immutable)• %something - %d, %f, %s – ‘a = %d’ % (a)
• Prefer .format()• {} sufficient – numbers optional• More complex things possible
![Page 6: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/6.jpg)
(Revision of)Loops
• for – for when you how many iterations• while - while you don’t know how many
iterations• while SomethingThatEvaluatesToABoolean:
# code• for loop syntax in Python– for iterVar in (x)range(iterNum):
# code
![Page 7: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/7.jpg)
(Revision of)for loops can do more!
• What is this ‘in’ anyway? (different time complexity for different cases)
• for char in string• for line in text• for item in sequence– Example: for i in [1,’a’,3]:
print i# output: 1\na\n3
![Page 8: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/8.jpg)
And one more thingDon’t be afraid of these:
Exception EOFError OSError
StopIteration ImportError SyntaxError
SystemExit KeyboardInterrupt IndentationError
StandardError LookupError SystemError
ArithmeticError IndexError SystemExit
OverflowError KeyError TypeError
FloatingPointError NameError ValueError
ZeroDivisonError UnboundLocalError RuntimeError
AssertionError EnvironmentError NotImplementedError
AttributeError IOError SomeRandomError
![Page 9: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/9.jpg)
And one more thing
• If nothing, look at what error it is and what line it is on. And make sure you look above and below that line.
• Further reading – 16 common runtime errors Python beginners find:http://inventwithpython.com/blog/2012/07/09/16-common-python-runtime-errors/
![Page 10: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/10.jpg)
Obligatory xkcd reference[1]
![Page 11: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/11.jpg)
Serious questions:
• What are functions?• Why are they important?• What is the difference between a
function and a method? (OOP language guys should answer)
![Page 12: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/12.jpg)
Functions are:
“Functions are reusable pieces of programs.They allow you to give a name to a block of statements, allowing you to run that block using the specified name anywhere in yourprogram and any number of times. This is known as calling the function.” - Byte of Python, Swaroop CH[2]
![Page 13: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/13.jpg)
General syntax• def function_name(param_1, ..., param_n):
# code to do something[return some_tuple] # square brackets because # optional
• Why param not arg?• That is, what is the difference between
arguments and parameters?• Fact: Functions in Python always return
something. So, in a function that just prints something, what does it return?
![Page 14: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/14.jpg)
More about functions
• Flow of execution – jumping when called, ending when a return is reached
• Try making a IndentationError or SyntaxError in your function definition. Is it caught without calling your function?
• What about other types of errors? That is, runtime errors.( dir(__builtins__) lists (yes, LISTs), among other things, all possible [Something]Error)
![Page 15: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/15.jpg)
Docstrings
• Let’s open some random library’s .py files and look at the code. (Be careful about modifying it, though.)
• Have you noticed __doc__?• Ignoring classes (and double underscores) for now.• def somefunction(args):
“””This is a docstring and itdescribes what the function does“””
![Page 16: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/16.jpg)
Functions that return
• What is the point of this?• How to receive what the function returns?• Be careful about number of arguments.• Idea of local variables. • Global variables using global statement
(But bad practice!)• Functional programming – stateless, no side
effects
![Page 17: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/17.jpg)
Imported stuff
• Before going to assignments for functions, let’s take a little detour to the import statement.
• Modules vs. Libraries – basic difference• And before going to import, let’s take a little
detour to...
![Page 18: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/18.jpg)
Remember import antigravity?
• For those who don’t:
![Page 19: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/19.jpg)
(not so) Serious questions:
• Do you think I’m just looking for an excuse to put xkcd comics in my slides or they actually have served a purpose in every case (so far)?
![Page 20: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/20.jpg)
Why am I talking about that anyway?
• Because whatever we import are usually .pyor .pyc files
• And I found antigravity.py and antigravity.pyc in C:\Python27\Lib
• Let’s open both with a text editor.• What happens when we click on both?• What happens when we modify the .py file?• Does is effect the .pyc file? Should it?
![Page 21: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/21.jpg)
(Again)Why am I talking about that anyway?
• To explain better how import works– The .pyc file is unaffected until we modify, save
and import antigravity again– Searches everything in sys.path
• Just to give you an idea that Python is not a complex or rigid as you think it is.
• Open source for the win!
![Page 22: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/22.jpg)
Try ‘this’. Literally.
• Try ‘import this’.• Find “this.py” and try to make sense of it.• Make a .py file called “this_1.py” and modify it to
print whatever you want.• Save it in a non C: partition• Now find a way to run it in a Python session
without navigating to saved location.• After you’ve finished, read the output of import
this. It’s pretty well written!
![Page 23: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/23.jpg)
Make a dice rolling gameFind a module that helps you with pseudorandom generation of numbers and use it to create a program to emulate a dice.Then it should roll the dice until the user gets the same number three times in a row or m tries, whichever is earlier. (m is entered by the user at the beginning)In case of the former, it prints, “You’re lucky.”Otherwise it prints “m chances up. ” It should also print no. of chances remaining at every roll and display the results of the last 3 rolls.
![Page 24: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/24.jpg)
For those who have finished• Try playing the game to see if you “are lucky”!
How big should your m be to win consistently?• What is the ideal probability for a random
dice? (1/6th per toss, one doesn’t affect the other.)
• But here it is pseudorandom. • Further reading – Blog post by Jeff Atwood:
https://blog.codinghorror.com/computers-are-lousy-random-number-generators/
![Page 25: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/25.jpg)
Default args
• Functions can use a default value as argument in case it is not passed while calling it.
• “Only those parameters which are at the end of the parameter list can be given default argument values ” [2]
• def func_name(param1, param2 = 0):• NOT def func_name(param1 = 0, param2):
![Page 26: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/26.jpg)
*args and **kwargs
• Variable number of arguments• kwargs – keyword arguments• def complex_func(*args, **kwargs):
# try thisa = args; b = kwargsprint(a, type(a)); print(b,type(b))
![Page 27: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/27.jpg)
*args and **kwargs
• You can use for loops to iterate over the arguments.
• args is a tuple • kwargs is a dictionary• How to call such a function? What is the value
of the dictionary?
![Page 28: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/28.jpg)
Other things about functions
• Functions can return multiple values. Use tuples (if confused, just comma-separate the variables for now)
• Too many arguments make a function argumentative. Limit yourself to fewer arguments per function; and more functions if required.
![Page 29: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/29.jpg)
List and string methods
• Why is this important enough to be a separate topic?
• What is the main difference between them?• Hint: This goes back to mutability.• Hint: Try something on both. What is the
return type
![Page 30: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/30.jpg)
List methods
• Do dir([]) and try to guess what each of the methods might do to a list.
• list.append(element)• list.extend(list)• list.remove(element)• list.pop(index)• list.reverse()• list.sort()
![Page 31: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/31.jpg)
AssignmentWrite a function which takes an input ‘n’.Then it asks for ‘n’ numbers and makes a list of Boolean values that are returned by a function is_greater(arg1, arg2) by comparing input values in order. That is, when 4 values a, b, c and d are given. The value of the list is:[a > b, b > c, c > d]. The program runs until the user types ‘end’.
![Page 32: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/32.jpg)
AssignmentA list containing ints, floats, and strings, when unsorted
looks like this:Example: l1_unsorted = [[1], 1, 2, 1.0, ‘aa’, ‘a’, ‘b’, [‘b’], [‘a’]]Using the default sort gives:Example: l1_sorted = [1, 1.0, 2, [1], ['a'], ['b'], 'a', 'aa', 'b']Write a program that returns:l1_custom_sorted = [[‘a’], [‘b’], ‘b’, ‘aa’, ‘a’, 2, 1,1.0] . Make sure that no more than 4 lines of code is outside a function. Functionify you code!
![Page 33: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/33.jpg)
String methods
• Do dir(‘’) and try to guess what each of methods might do to a string.
• string.split(delimiter)• string.upper() / .lower()• ‘ ‘.join([list of things to join])• string.startswith() / .endswith()
![Page 34: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/34.jpg)
Palindrome checker
• Write a palindrome checker.• That’s it. Up to you how complex you make it.
![Page 36: Functions, List and String methods](https://reader035.vdocuments.net/reader035/viewer/2022062822/5883fcba1a28ab884b8b4fab/html5/thumbnails/36.jpg)
References
All (Revision of) slides were taken from the class2 presentation that was made by me and used on 29/9/15
1. xkcd – Wisdom of the ancients https://xkcd.com/979
2. Byte of Python by Swaroop CH, available online at http://www.swaroopch.com/notes/python