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

=== JoeSett is now known as JoeMaverickSett
=== AlanChicken is now known as AlanBell
=== Funkrat is now known as Mossyfunk
=== yofel_ is now known as yofel
=== nigelbabu is now known as nigelb
=== starcraft is now known as starcraftman
=== JanC_ is now known as JanC
=== 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 || UOW Survey: http://is.gd/fZlwL || Event: Beginners Team Dev Academy - Current Session: Introduction to Python: Part 5 - Instructors: pedro3005
pedro3005Hello folks20:00
pedro3005Can whoever's here raise hands?20:01
pedro3005Good, good20:01
pedro3005Well, let me talk a bit about the class itself now20:02
pedro3005We're nearing the end20:02
pedro3005If you check out the official python tutorial, we're almost done with the basic python. From this point on they start talking about the standard library20:03
pedro3005Which is huge20:03
pedro3005So I won't be going over every detail of that20:03
pedro3005But with the knowledge you have from these classes, you will have no problem understanding the docs20:03
pedro3005hopefully20:03
pedro3005So last class we were talking about functions, dictionaries, files...20:04
pedro3005does anyone have any question or doubt?20:04
pedro3005Good.20:05
pedro3005So, today we can discuss a very important aspect of programming20:05
pedro3005no matter how much care you take in writing your code, things will screw up at some point20:06
pedro3005it happens20:06
pedro3005That's why we have to discuss error handling20:06
pedro3005Fortunately, Python has a system which makes it all easy20:06
pedro3005Hence exceptions!20:06
pedro3005An exception is an error form raised when something bad happens20:07
pedro3005for instance, let's look at this case20:07
pedro3005We learned about type conversion20:07
pedro3005What happens if you try to do int("a") ?20:07
pedro3005>>> int("a")20:07
pedro3005Traceback (most recent call last):20:07
pedro3005  File "<stdin>", line 1, in <module>20:07
pedro3005ValueError: invalid literal for int() with base 10: 'a'20:07
pedro3005The most interesting part here for us is the last line20:08
pedro3005notice the name ValueError20:08
pedro3005that's the name of a python exception20:08
pedro3005which was raised in this case because there's no way to convert the string "a" to an int20:08
pedro3005This exception being raised caused our program to fail20:09
pedro3005now that's a very bad thing20:09
pedro3005But fortunately, we can catch that exception20:09
pedro3005that is, acknowledge in our code that if it happens, the program shouldn't crash, but instead do what you tell it to!20:10
pedro3005Now, how do we do that?20:10
pedro3005we wrap it in a try block20:10
pedro3005Take this example20:10
pedro3005we received input from the user20:10
pedro3005age = raw_input("What is your age? ")20:11
pedro3005now, he might've typed his age, a number, or maybe something else20:11
pedro3005if we directly try to do int(age), it might work, but it might also fail pretty bad20:11
pedro3005remember raw_input() is of type STRING20:11
pedro3005we want to make it an integer, because that makes sense for an age variable20:11
pedro3005So what do we do? Well, we can wrap the int(age) in a try block20:12
pedro3005try:20:12
pedro3005    age = int(age)20:12
pedro3005except ValueError:20:12
pedro3005    print "You didn't input a valid age"20:12
pedro3005You can add an else block after all the exception catches20:14
pedro3005that will be ran if no exception was caught20:14
pedro3005in this example20:14
pedro3005else:20:14
pedro3005    print "The age is valid"20:14
pedro3005We have other built-in expressions20:15
pedro3005I mean exceptions20:15
pedro3005sorry20:15
pedro3005in fact you can see them all here http://docs.python.org/library/exceptions.html#bltin-exceptions20:15
pedro3005let's analyse for instance the case of a dictionary20:15
pedro3005Suppose you have a dict20:16
pedro3005and you try to access an element which is not there20:16
pedro3005>>> a = {}20:16
pedro3005>>> a["bla"]20:16
pedro3005Traceback (most recent call last):20:16
pedro3005  File "<stdin>", line 1, in <module>20:16
pedro3005KeyError: 'bla'20:16
pedro3005It raises the KeyError exception20:16
pedro3005So, suppose your dict is mapping person -> age20:17
pedro3005but age is still type string20:17
pedro3005we have20:17
pedro3005ages = {"Joe": "20", "Mary": "30"}20:18
pedro3005and our program has two interfaces20:19
pedro3005one which allows you to input a new person and their age20:19
pedro3005and another one which allows you to see a person's age20:19
pedro3005unfortunately, some user mapped a name e.g. "Foo" to a non-numerical string, "Bar"20:20
pedro3005so when we try to convert that to int we'll get a ValueError expression20:20
pedro3005but it could happen that a user also tries to access a non-existing person in this dict20:20
pedro3005one min please20:21
pedro3005We might need to catch BOTH exceptions20:22
pedro3005that is easy, we just stick them in a tuple20:22
pedro3005that is20:22
pedro3005except (ValueError, KeyError):20:23
pedro3005    handle_error()20:23
pedro3005assuming we have a handle_error() function here20:23
pedro3005the outcome isn't really important in our present analysis20:23
pedro3005Now, it could happen that you see something like this20:23
pedro3005except:20:23
pedro3005    pass20:24
pedro3005Let's analyse that20:24
pedro3005the 'pass' keyword is a placeholder20:24
pedro3005you can use it when python is expecting something to be there but you don't want it to do anything20:24
pedro3005so 'pass' is telling python to do nothing20:24
pedro3005the except: statement alone will catch ANY exception20:24
pedro3005So this block would be saying that if any exception happens, do nothing about it20:25
pedro3005That is poor practice!20:25
pedro3005You should always try to specify the exception20:25
pedro3005or maybe use except: to later write it down in a log20:26
pedro3005To do that, you may use the traceback module20:28
pedro3005simply import traceback and use the command traceback.print_last() for instance, to get the last exception20:28
pedro3005or, if you catch it in a try block20:29
pedro3005you can write it to a file20:29
pedro3005a log file20:29
pedro3005traceback.print_exc(file=log)20:30
pedro3005assuming you have created the log file descriptor20:30
pedro3005Take this program, for example20:32
pedro3005here I will use sys.stdout so you can all see the outcome20:32
pedro3005but it could just as well have been any file descriptor20:32
pedro3005>>> import sys, traceback20:32
pedro3005>>> def run():20:32
pedro3005...     age = raw_input("Enter your age: ")20:32
pedro3005...     try:20:32
pedro3005...             age = int(age)20:32
pedro3005...     except:20:32
pedro3005...             traceback.print_exc(file=sys.stdout)20:32
pedro3005...20:32
pedro3005>>> run()20:32
pedro3005Enter your age: foo20:32
pedro3005Traceback (most recent call last):20:32
pedro3005  File "<stdin>", line 4, in run20:32
pedro3005ValueError: invalid literal for int() with base 10: 'foo'20:32
pedro3005The traceback module has other functions, and as always, you can learn about them here http://docs.python.org/library/traceback.html20:33
pedro3005Questions?20:33
pedro3005Ok20:34
pedro3005let's have a quick look at import statements then20:34
pedro3005to pave the road for modules20:34
pedro3005We have been using them for a while20:35
pedro3005the import statement brings a module into your program20:35
pedro3005for instance20:35
pedro3005>>> import math20:35
pedro3005>>> math.sqrt(math.pi)20:35
pedro30051.772453850905515920:35
pedro3005we can also use the 'as' keyword20:35
pedro3005>>> import math as magic20:36
pedro3005>>> magic.sqrt(10)20:36
pedro30053.162277660168379520:36
pedro3005and we have the 'from' keyword20:37
pedro3005we can use that to import only a specific attribute we want20:37
pedro3005>>> from math import cos20:38
pedro3005>>> cos(0)20:38
pedro30051.020:38
pedro3005notice we did cos(0) and not math.cos(0)20:38
pedro3005because with the 'from' keyword we're importing it directly onto our namespace20:38
pedro3005similarly you can use * to mean everything20:38
pedro3005>>> from math import *20:40
pedro3005>>> sqrt(factorial(5))20:40
pedro300510.95445115010332220:40
pedro3005Questions?20:41
pedro3005Good20:42
pedro3005You can import your own file20:42
pedro3005for instance20:42
pedro3005let's say you made a function which checks if a number is odd20:43
pedro3005in your file odd.py20:43
pedro3005def is_odd(x):20:43
pedro3005    return x % 2 != 020:44
pedro3005let's look at that function closer20:44
pedro3005it seems a bit weird20:44
pedro3005but it makes sense20:44
pedro3005x % 2 != 0 is a boolean expression20:44
pedro3005it will be evaluated to either True or False20:44
pedro3005and that's what we return20:44
pedro3005any questions about that?20:44
pedro3005good20:45
pedro3005now, in a python terminal we can import that file20:45
pedro3005if we open it in the same folder20:46
pedro3005>>> import odd20:46
pedro3005>>> odd.is_odd(5)20:46
pedro3005True20:46
pedro3005now let's look at a line present in many python scripts20:48
pedro3005if you have analyzed some, you maybe have noticed it20:48
pedro3005towards the bottom it has something like20:48
pedro3005if __name__ == "__main__":20:48
pedro3005What does that mean?20:48
pedro3005It basically checks if the script was called directly "python odd.py" or imported20:48
pedro3005if it was imported, the if check fails20:48
pedro3005so let's suppose that if someone runs 'python odd.py' you want to display the message "Welcome to odd.py"20:49
pedro3005but if someone imports it from another program or shell, then do nothing20:49
pedro3005let's add that line20:49
pedro3005if __name__ == "__main__":20:49
pedro3005    print "Welcome to odd.py!"20:49
pedro3005now if we run it directly, we get the message20:50
ClassBotThere are 10 minutes remaining in the current session.20:50
pedro3005[pedro@pedro ~]$ python odd.py20:50
pedro3005Welcome to odd.py!20:50
pedro3005but if we import it instead20:50
pedro3005>>> import odd20:50
pedro3005>>>20:50
pedro3005nothing :)20:50
pedro3005So to end today let's talk about command line arguments20:51
pedro3005they're like when you call a program with certain parameters20:51
pedro3005'ls -a'20:51
pedro3005-a is an argument20:51
pedro3005just like in a function20:51
pedro3005our python programs can have that to20:51
pedro3005first we need to import the module sys20:52
pedro3005import sys20:52
pedro3005then, the arguments can be accessed in sys.argv20:52
pedro3005let's try that20:52
pedro3005in our arg.py file we have20:53
pedro3005import sys20:53
pedro3005print sys.argv20:53
pedro3005so let's call it20:53
pedro3005[pedro@pedro ~]$ python arg.py these are arguments20:53
pedro3005['arg.py', 'these', 'are', 'arguments']20:53
pedro3005well20:54
pedro3005what if I set that as executable via chmod20:55
pedro3005then I need to add our good old shebang line20:55
pedro3005#!/usr/bin/env python20:55
ClassBotThere are 5 minutes remaining in the current session.20:55
pedro3005to the start of our program20:55
pedro3005and by calling it the exact same way we get the same thing20:55
pedro3005[pedro@pedro ~]$ ./arg.py these are arguments20:55
pedro3005['./arg.py', 'these', 'are', 'arguments']20:55
pedro3005Now, if you're a C programmer, you might be wondering about sys.argc, but that is not needed. Since we have a great list functionality, we can merely use len(sys.argv)20:56
pedro3005which is the count of how many command line arguments we have20:56
pedro3005Questions?20:56
pedro3005Well, good20:58
pedro3005that marks the end of today's session20:58
pedro3005Hope you all had a good time20:59
pedro3005thanks for the attention20:59
ClassBotLogs for this session will be available at http://irclogs.ubuntu.com/2010/10/16/%23ubuntu-classroom.html21: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 || UOW Survey: http://is.gd/fZlwL ||
palhmbswhere are logs for this channel?21:00
palhmbsah - never mind21:00
palhmbshow long does it take for logs to be populated?21:01
nigelbpalhmbs: should be ready now21:04
palhmbsyep - got them21:04
palhmbsthanks21:04
palhmbsonly just found about this - #ubuntu-classroom thing - it's awesome21:05
nigelb\o/21:05
palhmbsnigelb, your involved with the Ubuntu Youth team?21:05
nigelbpalhmbs: no, but I am involved with the classroom team21:06
palhmbsI'm 32, is their a middle-aged group for beginners?21:06
nigelbwell, there's the beginners team21:06
nigelbhttps://wiki.ubuntu.com/BeginnersTeam21:06
palhmbsah, I want to be more involved with Ubuntu, help - I've joined Openhatch.org - heard of it?21:07
nigelbyeah, paulproteus wrote it21:07
palhmbsI've been trying to get Gobby-0.5 connecting to gobby's main server....21:09
palhmbswould gobby be a good way to teach programming?21:10
nigelbIt would if you can find someone willing to teach :)21:12
palhmbsnigelb, do you know when the calendar will be updated, I don't see any stuff for the next 2 weeks?21:37
nigelbpalhmbs: that's because there isn't anything for the next 2 weeks21:38
palhmbsnigelb, oh well, gives me opportunity to read the logs for the next 2 weeks.... I suppose21:40
nigelbheh :)21:40
=== JoeSett is now known as JoeMaverickSett

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