/srv/irclogs.ubuntu.com/2010/10/09/#ubuntu-classroom.txt

=== stingernewt is now known as damionloop
=== ChanServ changed the topic of #ubuntu-classroom to: Welcome to the Ubuntu Classroom - https://wiki.ubuntu.com/Classroom || Support in #ubuntu || Upcoming Schedule: http://is.gd/8rtIi || Questions in #ubuntu-classroom-chat || Event: Beginners Team Dev Academy - Current Session: Introduction to Python: Part 4 - Instructors: pedro3005
ClassBotLogs for this session will be available at http://irclogs.ubuntu.com/2010/10/09/%23ubuntu-classroom.html following the conclusion of the session.20:00
pedro3005Hello folks20:01
pedro3005Anybody out there?20:01
pedro3005erm20:01
pedro3005my fail20:01
pedro3005ok, I'm in -chat now20:02
pedro3005Alright, let's begin20:02
pedro3005Last class we were talking about functions and list comprehension20:03
pedro3005now these are difficult subjects20:03
pedro3005I gave some examples but I realized they might've been unclear20:03
pedro3005Functions are used a lot in programming20:04
pedro3005List comprehension isn't used as much, but it still is used not rarely20:04
pedro3005The purpose of functions is simple20:05
pedro3005When we are doing one procedure over an over, we can direct it to a function to avoid code repetition20:05
pedro3005For instance, suppose we are coding a little greeting program, which talks to the user20:06
pedro3005the user gave you his name, something like "Mr. H" or "Mrs. K"20:07
pedro3005Now, suppose you have many lines which are oriented by gender20:07
pedro3005before each of these lines, you are doing:20:08
pedro3005if name.startswith("Mr."):20:08
pedro3005bla20:08
pedro3005To avoid all this code being repeated over and over, you might use... functions!20:08
pedro3005as we learned last class, you can define a function with the keyword def20:09
pedro3005All functions return a value20:09
pedro3005but some functions return Null20:09
pedro3005Functions may or may not receive parameters, which are kind of like informations about the things it's supposed to do20:10
pedro3005In our case, it makes sense that our function receives as a parameter the name of the person20:10
pedro3005So it can determine the person's gender20:11
pedro3005Enough talk, let's get dirty20:11
pedro3005>>> def gender(name):20:12
pedro3005...     if name.startswith("Mr."):20:13
pedro3005...             return "male"20:13
pedro3005...     elif name.startswith("Mrs."):20:13
pedro3005...             return "female"20:13
pedro3005...20:13
pedro3005you can observe it returning20:13
pedro3005>>> gender("Mr. Rob")20:13
pedro3005'male'20:13
pedro3005Now, let me share a dirty little secret with you20:14
pedro3005In this function, we're just assuming the parameter <name> is a string20:15
pedro3005what happens if we call it with an integer, for instance?20:15
pedro3005>>> gender(2)20:15
pedro3005Traceback (most recent call last):20:15
pedro3005  File "<stdin>", line 1, in <module>20:15
pedro3005  File "<stdin>", line 2, in gender20:15
pedro3005AttributeError: 'int' object has no attribute 'startswith'20:15
pedro3005But, worry not, my lad20:16
pedro3005You, sir, are the programmer20:17
pedro3005You know better than to pass an int into your function expecting a string20:17
pedro3005But you must be careful with user values20:17
pedro3005If the user typed a value, you should NEVER assume it is what it's meant to be20:17
pedro3005We've discussed that previously, I just wanted to stress it again20:17
pedro3005We can also have functions with no parameters20:19
pedro3005As an example, we have the print_help function20:20
pedro3005Our program could have a help message20:20
pedro3005and we want to create a function to display it20:20
pedro3005But I don't really have any parameters, I just want the damn thing to print it20:20
pedro3005>>> def print_help():20:20
pedro3005...     print "rtfm"20:20
pedro3005You may ask: what does this function return?20:22
pedro3005I didn't tell it to return anything20:22
pedro3005Well, we can tru to assign it to a variable20:22
pedro3005try*20:23
pedro3005>>> a = print_help()20:23
pedro3005rtfm20:23
pedro3005>>> print a20:23
pedro3005None20:23
pedro3005You can note that the function returns None20:23
ClassBotTrueCryer45 asked: None as value? not Null?20:24
pedro3005Yeah, I got the name wrong on the first time20:24
pedro3005:P20:24
pedro3005It's None20:24
ClassBotmatematikaadit asked: none is none20:25
pedro3005>>> None is None20:25
pedro3005True20:25
pedro3005does that answer your question?20:25
pedro3005We also talked about the scope of functions20:26
pedro3005A function has its own scope of variables20:26
pedro3005for instance, if you declare a variable inside a function, it doesn't exist outside that function20:27
pedro3005if you declare variables outside the function, you can access the variable from within the function, but you cannot change it (unless if you call it global)20:27
pedro3005let's go over that20:27
pedro3005>>> def a():20:28
pedro3005...     n = 120:28
pedro3005...20:28
pedro3005>>> a()20:28
pedro3005>>> n20:28
pedro3005Traceback (most recent call last):20:28
pedro3005  File "<stdin>", line 1, in <module>20:28
pedro3005NameError: name 'n' is not defined20:28
pedro3005Here, we can clearly see the effects of this20:28
pedro3005n is not defined outside the function20:28
pedro3005>>> n = 120:29
pedro3005>>> def a():20:29
pedro3005...     print n20:29
pedro3005...20:29
pedro3005>>> a()20:29
pedro3005120:29
pedro3005here, we show that you can access the variable even though it wasn't defined in that very function20:29
pedro3005>>> def a():20:29
pedro3005...     n = 220:29
pedro3005...20:29
pedro3005>>> a()20:29
pedro3005>>> n20:29
pedro3005120:29
pedro3005But here, you see that you cannot change n20:30
pedro3005When you try to define a new value to n, you are actually creating a new, different n20:30
pedro3005this n exists only inside a()20:30
pedro3005when you get out of that function20:30
pedro3005there is another n20:30
pedro3005which is still 120:30
pedro3005it was not changed20:30
pedro3005We can use the global keyword to identify it as a global variable20:31
pedro3005>>> def a():20:31
pedro3005...     global n20:31
pedro3005...     n = 220:31
pedro3005...20:31
pedro3005>>> n = 120:31
pedro3005>>> a()20:31
pedro3005>>> n20:31
pedro3005220:31
pedro3005Are we clear on this, everyone?20:31
pedro3005Good20:34
pedro3005Let's introduce a new subject then20:34
pedro3005Named parameters20:35
pedro3005this is useful for holding default values20:35
pedro3005for instance, suppose you have a help function20:36
pedro3005if you call that with a certain command, it displays help about the command20:37
pedro3005if you call it by itself, it displays a general help message20:37
pedro3005we can accomplish this with named parameters20:37
pedro3005>>> def p_help(command=None):20:38
pedro3005...     if command == None:20:38
pedro3005...             print "general help message"20:38
pedro3005...     else:20:38
pedro3005...             print "specific help about %s" % command20:38
pedro3005...20:38
pedro3005>>> p_help("ls")20:38
pedro3005specific help about ls20:38
pedro3005>>> p_help()20:38
pedro3005general help message20:38
pedro3005if you don't pass anything, command gets the default value of None20:39
pedro3005>>> def p_help(command=None, detailed=None):20:42
pedro3005...     if command == None:20:42
pedro3005...             if detailed:20:42
pedro3005...                     print "detailed general help message"20:42
pedro3005...             else:20:42
pedro3005...                     print "general help message"20:42
pedro3005...     else:20:42
pedro3005...             if detailed:20:42
pedro3005...                     print "detailed help message about %s" % command20:42
pedro3005...             else:20:42
pedro3005...                     print "help message about %s" % command20:42
pedro3005...20:42
pedro3005>>> p_help(detailed=True)20:43
pedro3005detailed general help message20:43
pedro3005So as you see in this last function, you can use named parameters to only pass a certain value to the function20:44
pedro3005Any questions?20:44
ClassBotOttoBusDriver asked: Can you call functions with named parameters with positional paramters? EG p_help('command', True)20:45
pedro3005Yes20:45
pedro3005>>> p_help("ls", True)20:45
pedro3005detailed help message about ls20:45
ClassBotOttoBusDriver asked: And can you define a function with positional and named parameters?20:46
pedro3005didn't we just do that?20:46
pedro3005def p_help(command=None, detailed=None):20:46
pedro3005Good20:48
pedro3005It seems we are all clear on this subject20:48
pedro3005Let me see if there's anything more of functions I should go through today20:48
pedro3005Oh yes20:50
pedro3005this looks hard but it is actually quite easy20:50
pedro3005Python has a shortcut for easy, one-expression functions20:50
pedro3005if you have a function that just grabs a value x and adds 2, for instance20:50
pedro3005or grabs the value x and calls some_random_function(x)20:50
pedro3005you can use lambda expressions20:50
pedro3005>>> a = lambda x: x + 220:51
pedro3005>>> a(40)20:51
pedro30054220:51
pedro3005lambda of x is x + 220:52
pedro3005the syntax is a bit different from the def keyword20:52
pedro3005you must assign it to a variable, as you see20:52
pedro3005the x is actually the parameter20:52
pedro3005not the function's name20:52
pedro3005lambda expressions can take in multiple parameters20:52
pedro3005>>> a = lambda x, y: x + y20:53
pedro3005>>> a(2, 3)20:53
pedro3005520:53
pedro3005>>> a = lambda x=1, y=2: x + y20:53
pedro3005>>> a()20:53
pedro3005320:53
pedro3005>>> a(2)20:53
pedro3005420:53
pedro3005And you have named parameters with lambdas ^20:53
pedro3005Lambda comes from functional programming, which (obviously) bases itself heavily on functions20:54
pedro3005so it was needed to create a shorter path to small functions20:54
pedro3005thus lambda20:54
pedro3005It's not used much outside of FP (functional programming), but I wanted to go over it because FP knowledge is important to any decent programmer20:55
pedro3005Any questions?20:55
pedro3005Alright20:57
pedro3005this is it for functions20:57
pedro3005I mean, there is more to it, but I think I have explained most of it20:57
pedro3005you should play with functions, use them in your programs, get used to them20:58
pedro3005they are really important in programming20:58
pedro3005Also reference to last class where I explained functions as well20:58
pedro3005(to find out that a function can receive another function as argument)20:58
pedro3005But let us continue on exploring data structures20:59
pedro3005We've been talking about lists20:59
pedro3005they are ways of sequencing things20:59
pedro3005you can create a list for instace20:59
pedro3005instance*20:59
pedro3005numbers = [1, 2, 3, 4, 5]21:00
pedro3005And we went over various things you can do with lists21:00
pedro3005grab elements21:00
pedro3005numbers[0] being the first21:00
pedro3005put in new elements, with numbers.append(6) or numbers.insert(0, 0)21:00
pedro3005(insert 0 at the position 0)21:00
pedro3005http://docs.python.org/tutorial/datastructures.html#more-on-lists21:01
pedro3005those are all the methods you have with lists21:01
pedro3005I want to go over a new type today21:01
pedro3005it is called a dict21:01
pedro3005short for dictionary21:01
pedro3005let's think about real dicitonaries21:02
pedro3005they have a word and a definition21:02
pedro3005so they are kind of like mapping tools21:02
pedro3005they link one thing to another21:02
pedro3005in our case, a word to a definition21:02
pedro3005In python, we have that21:02
pedro3005we have dictionaries that map a string to an object21:03
pedro3005but get this21:03
pedro3005everything is an object21:03
pedro3005a fuction is an object, a list is an object, they're all objects21:03
pedro3005so a dict maps a string to pretty much anything21:03
pedro3005let's go over the syntax21:03
pedro3005imagine you have three users, Rob, Joe and Max21:04
pedro3005and they have user ids of 1, 2 and 3 respectively21:04
pedro3005let's create a dictionary which maps user to user id21:04
pedro3005users = {"Rob":1, "Joe":2, "Max":3}21:05
pedro3005Notice we use {}21:05
pedro3005We can access an element of this dict by calling: users["Rob"]21:05
pedro3005that will return 121:05
pedro3005because Rob is mapped to 121:06
pedro3005>>> users["Rob"]21:06
pedro3005121:06
pedro3005Questions?21:07
pedro3005Good21:07
pedro3005In Python terms, "Rob", "Joe" and "Max" are keys of the dict users21:08
pedro3005And how do you get all the keys in users?21:08
pedro3005>>> users.keys()21:08
pedro3005['Max', 'Rob', 'Joe']21:08
pedro3005But hey, wait a minute!21:09
pedro3005I put in Rob _first_21:09
pedro3005Why did I get Rob in second?21:09
pedro3005What the hell is python thinking?!21:09
pedro3005It's simple21:09
pedro3005they're random21:10
pedro3005You see, Python doesn't guarantee that your dict will be in the order you left it21:10
pedro3005The function of dicts is to relate string to anything21:12
pedro3005and that function is kept21:12
pedro3005I think python 3 will have ordered dicts21:12
pedro3005or was that 2.7?21:12
pedro3005not sure21:12
ClassBotmatematikaadit asked: is it possible a key related to nothing?21:12
pedro3005well, sure21:13
pedro3005but in python we call nothing None :)21:13
pedro3005>>> a = {"a": None}21:13
pedro3005>>> a["a"]21:13
pedro3005Questions?21:14
pedro3005Good21:14
ClassBotmatematikaadit asked: users.keys() is for calling the key, how about the value?21:16
pedro3005As TrueCryer45 lovely pointed out, users.values()21:16
pedro3005You can use the method .has_key() to check if a dict has a certain key21:16
pedro3005>>> users.has_key("Rob")21:16
pedro3005True21:16
pedro3005example:21:17
pedro3005>>> if users.has_key("Rob"):21:17
pedro3005...     print "Rob is here. His ID is %s" % users["Rob"]21:17
pedro3005...21:17
pedro3005Rob is here. His ID is 121:17
pedro3005Here we are mapping a string ("Rob", "Joe", whatever) to an int (1, 2, 3 ..)21:18
pedro3005But who's to say we can't map strings to lists, for instance?21:18
pedro3005We can!21:18
pedro3005>>> boxes = {"box1": ["a key", "an old cd"], "box2": ["three coins", "a phone"]}21:19
pedro3005>>> boxes["box1"][0]21:19
pedro3005'a key'21:19
pedro3005Hell, we can map strings to functions, other dicts, other dicts that have dicts within them, other dicts with dicts with dicts within..21:21
pedro3005in short, we can map strings to practically anything21:21
pedro3005with dictionaries21:21
pedro3005What if we wanted to print each user's name and id?21:22
pedro3005We need to iterate over this dict21:22
pedro3005we would use a for loop (I hope you all remember the for loop class)21:22
pedro3005>>> for user, id in users.iteritems():21:23
pedro3005...     print user, id21:23
pedro3005...21:23
pedro3005Max 321:23
pedro3005Rob 121:23
pedro3005Joe 221:23
pedro3005now, let's analyze that21:23
pedro3005do you guys remember tuples? they we're like (1, 2)21:24
pedro3005sort of like lists21:24
pedro3005I taught that we could unpack these tuples into variables21:24
pedro3005x, y = (1, 2)21:24
pedro3005x = 1 and y = 221:24
pedro3005this is exactly what happens in the for loop21:24
pedro3005the function returns something like ('Max', 3)21:25
pedro3005and it's unpacked into user and in21:25
pedro3005id*21:25
pedro3005then we print these21:25
pedro3005Questions?21:25
pedro3005Ok, good21:27
pedro3005Now21:28
pedro3005Let's turn our attentions to something more tangible21:28
pedro3005Hang in there guys21:28
pedro3005we're nearly getting over the basic python21:28
pedro3005Programs usually have a functionality of reading and writing to files21:29
pedro3005so let's learn how to do that in python21:29
pedro3005All this time, you've been reading and writing to files and you didn't know it21:29
pedro3005print "bla"21:30
pedro3005this writes "bla" into the file stdout21:30
pedro3005which in our case is the terminal21:30
pedro3005when you call raw_input() you're reading from stdin21:30
pedro3005how cool is that?21:30
pedro3005When we change to other files, it's not much different21:30
pedro3005We use the open() function to open a file21:31
pedro3005We do it like this:21:32
pedro3005f = open("some_text_file")21:32
pedro3005notice that we didn't define a mode here21:32
pedro3005by default, it is in reading mode21:32
pedro3005that is equivalent to21:32
pedro3005f = open("some_text_file", "r")21:33
pedro3005now you can do things with f21:33
pedro3005for instance, let's read our file21:33
pedro3005f.read()21:33
pedro3005this returns a string with the entire file21:34
pedro3005it will not remove newlines ("\n") etc21:34
pedro3005Let me quote the python docs21:34
pedro3005To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an emp21:34
pedro3005ty string ("").21:34
pedro3005You may call f.readline() to read just one line21:37
pedro3005and you can iterate over the file21:37
pedro3005>>> for line in f:21:38
pedro3005...     print line21:38
pedro3005...21:38
pedro3005this21:38
pedro3005is21:38
pedro3005a21:38
pedro3005file21:38
pedro3005iterating over f will give you line by line21:39
pedro3005Questions?21:39
pedro3005Good21:41
pedro3005Writing to files is just as easy21:41
pedro3005Open it in "w" mode21:41
pedro3005f = open("some_file", "w")21:41
pedro3005and then call write()21:41
pedro3005f.write("blablabla")21:41
pedro3005when you're done, don't forget21:42
pedro3005f.close()21:42
pedro3005remember that you must call write with a string21:42
pedro3005so imagine you have21:42
pedro3005answer = 4221:42
pedro3005you can't do21:43
pedro3005f.write(answer)21:43
pedro3005because answer has type int21:43
pedro3005convert it to string21:43
pedro3005f.write(str(answer))21:43
pedro3005There are more methods to files21:44
pedro3005these are the most used21:44
pedro3005http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects21:44
pedro3005I recommend you read this21:44
pedro3005Given this, I think now you are experienced enough to try your hands at a challenge21:46
pedro3005http://ubuntuforums.org/showthread.php?t=88439421:46
pedro3005OH, I forgot to mention21:48
pedro3005files also havc the append mode21:48
pedro3005which is similar to write21:48
pedro3005but you begin writing where the file stop21:48
pedro3005whereas the file is cleared if you open it in write mode21:48
pedro3005f = open("bla", "w")21:48
pedro3005and f = open("bla", "a")21:48
pedro3005Is that clear?21:48
ClassBotThere are 10 minutes remaining in the current session.21:50
pedro3005So just for recalling21:55
ClassBotThere are 5 minutes remaining in the current session.21:55
pedro3005so far we went over variables, user input, outputting (print), types, type checking & conversion, boolean expressions, if blocks, for and while loops, functions, lists and dicts, list comprehension, files21:55
pedro3005So it'd be good if you all were sharp on these subjects21:56
pedro3005I think in the next class I will present a program, so we can study how to actually develop full stuff21:58
pedro3005But anyway21:58
pedro3005Time for us to call it a day21:58
pedro3005I hope this was of some use21:58
ClassBotLogs for this session will be available at http://irclogs.ubuntu.com/2010/10/09/%23ubuntu-classroom.html22:00
=== ChanServ changed the topic of #ubuntu-classroom to: Welcome to the Ubuntu Classroom - https://wiki.ubuntu.com/Classroom || Support in #ubuntu || Upcoming Schedule: http://is.gd/8rtIi || Questions in #ubuntu-classroom-chat ||
=== yofel_ is now known as yofel

Generated by irclog2html.py 2.7 by Marius Gedminas - find it at mg.pov.lt!