Python4Programmers

Ubuntu Opportunistic Developers Week Ubuntu Opp Dev Week Prep: Intro to Python for Programmers - Rick Spencer

[16:05] <rickspencer3> anyone here for Python for For Folks who know another language?
[16:06] <rickspencer3> alright then
[16:06] <rickspencer3> let us rock
[16:06] <rickspencer3> if you know me at all, you can predict that I created a wiki page and over pre-pared for the class :)
[16:06] <rickspencer3> https://wiki.ubuntu.com/UbuntuOpportunisticDeveloperWeek/IntroToPythonForProgrammers
[16:06] <rickspencer3> keep in mind - I am not a python expert
[16:06] <rickspencer3> sorry!
[16:07] <rickspencer3> but I have learned lots and lots of languages over the years
[16:07] <rickspencer3> so whenever I learn a new language I have to create a kind of map in my mind that maps old languages to the new one
[16:08] <rickspencer3> so, what I want to do is just give you a jump start by providing that mental map
[16:09] <rickspencer3> to me, Python is one of the "native" languages of the Ubuntu desktop
[16:09] <rickspencer3> because Ubuntu is a Gnome based distro
[16:09] <rickspencer3> it's well suited to app development and,
[16:09] <ClassBot> dscassel asked: For me, language is lesss of an issue than environment, tooling and libraries. We'll get to that, yes?
[16:09] <rickspencer3> over the years I have come to love programming in Python
[16:10] <rickspencer3> dscassel, a bit, I'll answer your question in a moment
[16:10] <rickspencer3> when I first started with python it seemed weirdly terse and constrictive
[16:10] <rickspencer3> but now I find that my creativity really flows through the language
[16:10] <rickspencer3> so
[16:10] <rickspencer3> to dscassel question, what is python?
[16:10] <rickspencer3> it is a language
[16:11] <rickspencer3> but it is *also* a standard library
[16:11] <rickspencer3> it's hard to talk about one without the other
[16:11] <rickspencer3> so I won't try to make hard and fast distinctions here, I'll just mix it up
[16:11] <rickspencer3> but I put a link to the language ref and the library ref on the wiki page
[16:12] <ClassBot> Johonunu asked: is python procedural or object oriented language ?
[16:12] <rickspencer3> python is also on interpreter
[16:12] <rickspencer3> Johonunu, yes
[16:12] <rickspencer3> :)
[16:12] <rickspencer3> Python supports both paradigms well
[16:13] <rickspencer3> I prefer to use the OO approach for larger programs, so I will cover that syntax near the end of this session
[16:13] <rickspencer3> let's rock
[16:13] <rickspencer3> if you type "python" into your terminal window
[16:13] <rickspencer3> you get the python interpreter
[16:13] <rickspencer3> where you can write a bit of python
[16:13] <rickspencer3> in samples if you see a >>>
[16:13] <ClassBot> AdamK19 asked: what makes Python so great? any notable advantages over say, C# or Java?
[16:13] <rickspencer3> that means the sample was done in the "interactive shell"
[16:14] <rickspencer3> AdamK19, well, linguistic choices are perosnal to some degree
[16:14] <rickspencer3> I know C# and Java both quite well
[16:14] <rickspencer3> I find Python to have significantly less syntactic and semantic overhead, and easier to read other people's python code
[16:14] <rickspencer3> but I won't say one is "better"
[16:15] <rickspencer3> Python is great for Ubuntu because it is a real FOSS community language in terms of origins and the community around it
[16:15] <rickspencer3> so
[16:15] <rickspencer3> let's start with some language concepts
[16:15] <rickspencer3> 1. Indentation levels
[16:15] <ClassBot> hemanth asked: market scope of python vs java ?
[16:15] <rickspencer3> # controls scoping instead of {}, "end", etc...
[16:15] <rickspencer3> # standard is to use 4 spaces for each indentation level
[16:15] <rickspencer3> # you will get used to it, and probably format you code this way anyway
[16:16] <rickspencer3> so this means that white space is meaningful in a way it is not in other languages
[16:16] <rickspencer3> you will have many bugs in your code from this the first few days of using python
[16:16] <rickspencer3> you may find you hate this at first, but you may learn to love it
[16:17] <rickspencer3> anyway, real programmers indent their code for readability, so you probably have this habbit already
[16:17] <ClassBot> abgalphabet asked: python gets different implementation, is it a language spec too?
[16:17] <rickspencer3> for i in xrange(5,20):
[16:17] <rickspencer3>     print i
[16:18] <rickspencer3> "print i" is indented 4 spaces, thus the it is within the scope of the for loop
[16:18] <rickspencer3> hemanth, deep question, let's talk later
[16:18] <rickspencer3> abgalphabet, yes
[16:18] <ClassBot> abgalphabet asked: 4 spaces? not tab?
[16:18] <rickspencer3> 4 spaces!
[16:19] <rickspencer3> technically, the language support both, but 4 spaces is standard
[16:19] <rickspencer3> set your editor to do 4 spaces for tab with python, you will be much happier in the long run that way!
[16:19] <rickspencer3> let's talk typing real quick
[16:19] <rickspencer3> Python is Dynamically typed, but it is also Strongly typed
[16:20] <rickspencer3> >>> x = 1
[16:20] <rickspencer3> >>> x
[16:20] <rickspencer3> 1
[16:20] <rickspencer3> >>> type(x)
[16:20] <rickspencer3> <type 'int'>
[16:20] <rickspencer3> >>> x = "string"
[16:20] <rickspencer3> >>> x
[16:20] <rickspencer3> 'string'
[16:20] <rickspencer3> >>> type(x)
[16:20] <rickspencer3> <type 'str'>
[16:20] <rickspencer3> this shows dynamic typing
[16:20] <rickspencer3> x is an int just because I said it was
[16:20] <rickspencer3> I said it was by assigning an int to it
[16:20] <rickspencer3> then I changed x to be a string
[16:21] <rickspencer3> I did this by assigning a string to it!
[16:21] <rickspencer3> woah
[16:21] <rickspencer3> so you don't declare the type of a variable because you can change the type laer
[16:21] <rickspencer3> thus "dynamic" typing
[16:21] <rickspencer3> but unlike some other dynamically typed languages, Python is strongly typed
[16:21] <rickspencer3> so types are converted from one to other automatically
[16:21] <ClassBot> kript asked: probably stupid,but how do you run code in the emulator?
[16:22] <rickspencer3> >>> x = 1
[16:22] <rickspencer3> >>> print x + " is a string"
[16:22] <rickspencer3> Traceback (most recent call last):
[16:22] <rickspencer3>   File "<stdin>", line 1, in <module>
[16:22] <rickspencer3> TypeError: unsupported operand type(s) for +: 'int' and 'str'
[16:22] <rickspencer3> kript, if you mean in the interactive shell, you just type it in
[16:22] <rickspencer3> it will run as blocks of code are complete
[16:22] <rickspencer3> also, install iPython
[16:23] <rickspencer3> it's an interactive shell that supports tab completion
[16:23] <rickspencer3> so you can inspect data structures and such as you are typing
[16:23] <ClassBot> theopensourcerer asked: Can you enforce type so you can't change it later?
[16:23] <rickspencer3> theopensourcerer, not that I know of, as it is a dynamically typed language
[16:23] <rickspencer3> (but there may be a way I don't know about)
[16:24] <rickspencer3> if you are used to statically typed languages this seems weirdly dangerous
[16:24] <rickspencer3> but after a while static typing will seem like unneceesary programing overhead
[16:24] <rickspencer3> ok, so moving on
[16:24] <rickspencer3> since it is a strongly typed language, there are types
[16:25] <rickspencer3> it's easy to look up the types, so I won't bore you with details here
[16:25] <rickspencer3> but here is some info to get your mental map started
[16:25] <rickspencer3> there are numeric types
[16:25] <rickspencer3> Integer, Long Integer, Float, Complex
[16:25] <ClassBot> AdamK19 asked: does python have something like c# interfaces (and if, how dose it fit with dynamic types)
[16:25] <rickspencer3> AdamK19, no
[16:25] <rickspencer3> interfaces are necessary for strongly typed languages
[16:26] <rickspencer3> because you want different implementations to be callable, right?
[16:26] <rickspencer3> so in Python, you just add the members to your class that will be needed by the caller
[16:26] <rickspencer3> however, Python does have multiple inheritance, so you can do interface like things, but include a default implementation
[16:27] <rickspencer3> (at least that's the way I understand it)
[16:27] <rickspencer3> ok so one thing abut numeric types is that you can mix em up in your math
[16:27] <rickspencer3> the result will always be the least restrictive type
[16:28] <rickspencer3> so if you add an in to a float, the result will be a float
[16:28] <ClassBot> m_anish asked: Is there a way to declare constant variables like we do in C/C++
[16:28] <rickspencer3> if you want the result to be an int, you can conver it to an int like this:
[16:28] <rickspencer3> x = int(x)
[16:28] <rickspencer3> m_anish, I don't know for sure
[16:28] <rickspencer3> there is a convention to use all caps
[16:29] <rickspencer3> MY_CONSTANT_VARIABLE = "foo"
[16:29] <rickspencer3> but I don't know that the language can enforce immutability
[16:29] <rickspencer3> sorry
[16:29] <rickspencer3> moving on
[16:29] <rickspencer3> a quick word on string
[16:29] <rickspencer3> strings are highly functional in Python
[16:30] <rickspencer3> this is an example of where the line between language and library is nicely blurred
[16:31] <rickspencer3> note that there is no "character" type
[16:31] <rickspencer3> you can concat with "+" and stuff like that
[16:31] <ClassBot> malev asked: capitals does not make a variable inmutable, sorry
[16:31] <rickspencer3> and you get "foo".endswith("o"), etc... for free
[16:31] <rickspencer3> you can use " or ' to surround your string
[16:31] <rickspencer3> malev, no, it's just a convention
[16:32] <rickspencer3> so when people read your code, they think "ah, all caps, the author believes this should not change"
[16:32] <ClassBot> abgalphabet asked: is python case-sensitive
[16:32] <rickspencer3> abgalphabet, yes
[16:32] <rickspencer3> so more on types
[16:32] <rickspencer3> there is an object called None
[16:32] <rickspencer3> it is of the type NoneType
[16:33] <rickspencer3> it;s kind of like null
[16:33] <rickspencer3> None is an instance of NoneType
[16:33] <rickspencer3> undeclared variables *are not* None, they are just undeclared
[16:33] <rickspencer3> so you can't do:
[16:33] <rickspencer3> if foo is not None:
[16:33] <rickspencer3>     #do something
[16:33] <rickspencer3> to test if foo is declared
[16:34] <rickspencer3> that will be an error
[16:34] <rickspencer3> ok
[16:34] <rickspencer3> so python has three types are very feature rich
[16:35] <rickspencer3> Lists, Tuples, and Dictionaries
[16:35] <rickspencer3> lists and tuples are kind of like arrays in other languages
[16:35] <rickspencer3> but they aren't typed
[16:35] <rickspencer3> !
[16:35] <rickspencer3> it would be like an array of Objects in C# or java
[16:35] <rickspencer3> by "not typed", I mean, this is fine:
[16:35] <rickspencer3> my_tuple = (1,"one",False)
[16:36] <rickspencer3> you can mix up types in them
[16:36] <rickspencer3> very cool
[16:36] <rickspencer3> the main difference between tuples and lists is that tuple are immutable
[16:36] <rickspencer3> this makes them a bit faster to iterate and stuff like that
[16:36] <rickspencer3> also keeps other parts of your program from messing with them
[16:37] <ClassBot> mcphargus asked: I'm unclear on the immutability of tuples, can you add or remove from a tuple? or just not change the objects in the tuple?
[16:37] <rickspencer3> mcphargus, nope
[16:37] <rickspencer3> you cannot add or remove items from a tuple
[16:38] <rickspencer3> I assume that you can change an object that is in a tuple from outside of tuple
[16:38] <rickspencer3> but I'm not 100% certain
[16:38] <rickspencer3> I use tuple for stuff like this:
[16:38] <rickspencer3> >>> wintermonths = ("December","January","February")
[16:38] <rickspencer3> >>> wintermonths
[16:38] <rickspencer3> ('December', 'January', 'February')
[16:38] <rickspencer3> like I know I won't change that list, I care about the order, and I'll be iterating it
[16:39]  * rickspencer3 tries changing a value in a tuple
[16:39] <rickspencer3> >>> foo = "boo"
[16:39] <rickspencer3> >>> t = (1, foo)
[16:39] <rickspencer3> >>> t
[16:39] <rickspencer3> (1, 'boo')
[16:39] <rickspencer3> >>> foo = "baz"
[16:39] <rickspencer3> >>> t
[16:39] <rickspencer3> (1, 'boo')
[16:39] <rickspencer3> >>>
[16:39] <rickspencer3> immutable :)
[16:40] <rickspencer3> tuple are created with ()
[16:40] <rickspencer3> lists with []
[16:40] <rickspencer3> >>> grades = ["A","A-","B","C"]
[16:40] <rickspencer3> >>> grades
[16:40] <rickspencer3> ['A', 'A-', 'B', 'C']
[16:40] <rickspencer3> you index lists and tuples with [] as in most languages
[16:41] <rickspencer3> >>> wintermonths
[16:41] <rickspencer3> ('December', 'January', 'February')
[16:41] <rickspencer3> >>> wintermonths[0]
[16:41] <rickspencer3> 'December'
[16:41] <rickspencer3> one sweet thing is that you can start from the back!
[16:41] <rickspencer3> >>> grades
[16:41] <rickspencer3> ['A', 'A-', 'B', 'C']
[16:41] <rickspencer3> >>> grades[-1]
[16:41] <rickspencer3> 'C'
[16:41] <rickspencer3> >>> grades[-2]
[16:41] <rickspencer3> 'B'
[16:41] <rickspencer3> getting the last item in a list or tuple is so easy
[16:42] <rickspencer3> to test if a list or tuple (or dictionary for that matter) contains a value (or key for a dictionary), use "in"
[16:42] <rickspencer3> it's sweet"
[16:42] <rickspencer3> >>> grades = ["A","A-","B","C"]
[16:42] <rickspencer3> >>> grades
[16:42] <rickspencer3> ['A', 'A-', 'B', 'C']
[16:42] <rickspencer3> >>> "A" in grades
[16:42] <rickspencer3> True
[16:42] <rickspencer3> >>> "F" in grades
[16:42] <rickspencer3> False
[16:42] <ClassBot> hemanth asked: how immutability increases speed in iterations ?
[16:43] <rickspencer3> hemanth, I have no idea, I assume it's implementation specific
[16:43] <rickspencer3> sorry
[16:43] <rickspencer3> so, let's move on to dictionaries
[16:43] <rickspencer3> these are really common to use in Python and save tons and tons of time and code
[16:43] <rickspencer3> a dictionary is basically a hash table, but it's built into the langauge
[16:44] <ClassBot> virkang asked: So, you could use a tuple with length 1 to make a constant variable, right ? Is that used like that in practice ?
[16:44] <rickspencer3> virkang, I suppose
[16:44] <rickspencer3> this has never been something that I cared to do in a Python program
[16:44] <rickspencer3> there may be other experts that could better answer that for you
[16:44] <rickspencer3> like I say, I'm not a Python expert, I just know lots of languages ;)
[16:45] <rickspencer3> so moving on to dictionaries:
[16:45] <rickspencer3> >>> grades = {"English":"D","Math":"A-","History":"C+"}
[16:45] <rickspencer3> >>> grades
[16:45] <rickspencer3> {'History': 'C+', 'Math': 'A-', 'English': 'D'}
[16:46] <rickspencer3> using {} you can easily create a dictionary
[16:46] <rickspencer3> again, they don't require certain types to be used for keys and values
[16:46] <rickspencer3> though some types can't be used for keys
[16:46] <rickspencer3> like you can't use a dictionary to be a key in another dictionary
[16:46] <ClassBot> hemanth asked: i was unclear when you said "this makes them a bit faster to iterate and stuff like that"
[16:47] <rickspencer3> hemanth, well, if you don't need to change the contents of a list, you can get some slight speed boosts in your code by using a tuple
[16:47] <rickspencer3> because it won't have to support "append" and all this
[16:47] <rickspencer3> so it can be optimized inside the Python run time
[16:47] <rickspencer3> at least that's what I think
[16:48] <rickspencer3> so, dictionaries
[16:48] <rickspencer3> use 'em, love 'em
[16:48] <rickspencer3> looks like I screwed up the wiki a but
[16:48] <rickspencer3> a bit, even
[16:48] <rickspencer3> I'll add the dictionary stuff in later today
[16:48] <ClassBot> theopensourcerer asked: So a dictionary is like an associative array?
[16:48] <rickspencer3> Note that dictionaries don't store their items in any particular order, so indexing into them with [] and some integer doesn't work. You must use [] with a key.
[16:49] <rickspencer3> >>> grades
[16:49] <rickspencer3> {'History': 'C+', 'Math': 'A-', 'English': 'D'}
[16:49] <rickspencer3> >>> grades["History"]
[16:49] <rickspencer3> 'C+'
[16:49] <rickspencer3> To change the value associated with a key, simply reassign to the indexed key:
[16:49] <rickspencer3> >>> grades
[16:49] <rickspencer3> {'History': 'C+', 'Math': 'A-', 'English': 'D'}
[16:49] <rickspencer3> >>> grades["History"] = "B-"
[16:49] <rickspencer3> >>> grades
[16:49] <rickspencer3> {'History': 'B-', 'Math': 'A-', 'English': 'D'}
[16:49] <rickspencer3> You can add a key/value pair the exact same way:
[16:49] <rickspencer3> >>> grades
[16:49] <rickspencer3> {'History': 'B-', 'Math': 'A-', 'English': 'D'}
[16:49] <rickspencer3> >>> grades["Gym"] = "F"
[16:49] <rickspencer3> >>> grades
[16:49] <rickspencer3> {'Gym': 'F', 'History': 'B-', 'Math': 'A-', 'English': 'D'}
[16:49] <rickspencer3> To delete a key/value pair, use the global del() function:
[16:49] <rickspencer3> >>> grades
[16:49] <rickspencer3> {'Gym': 'F', 'History': 'B-', 'Math': 'A-', 'English': 'D'}
[16:49] <rickspencer3> >>> del(grades["English"])
[16:49] <rickspencer3> >>> grades
[16:50] <rickspencer3> {'Gym': 'F', 'History': 'B-', 'Math': 'A-'}
[16:50] <rickspencer3> You can retrieve all the keys from a dictionary using the "keys()" function, and all of the values using the values() functions. To retrieve all of the key/value pairs as a list of tuples, use  items().
[16:50] <rickspencer3> >>> grades
[16:50] <rickspencer3> {'Gym': 'F', 'History': 'B-', 'Math': 'A-'}
[16:50] <rickspencer3> >>> grades.keys()
[16:50] <rickspencer3> ['Gym', 'History', 'Math']
[16:50] <rickspencer3> >>> grades.values()
[16:50] <rickspencer3> ['F', 'B-', 'A-']
[16:50] <rickspencer3> >>> grades.items()
[16:50] <rickspencer3> [('Gym', 'F'), ('History', 'B-'), ('Math', 'A-')]
[16:50] <rickspencer3> to see if a dictionary has a certain key, don't look in keys, just look in the dictionary
[16:50] <rickspencer3> so you go:
[16:50] <rickspencer3> if Gym in grades:
[16:50] <rickspencer3>     #do something
[16:50] <rickspencer3> Remember that a dictionary does not store items in any particular order, so the list of tuples returned by items() may not be in the order that items were created.
[16:51] <rickspencer3> never count on a dictionary having anything in a particular order!
[16:51] <ClassBot> abgalphabet asked: dictionary created by {}?
[16:51] <rickspencer3> abgalphabet, right
[16:51] <rickspencer3> very similar to json
[16:51] <ClassBot> theopensourcerer asked: Can you have multi-dimension dictionaries?
[16:51] <rickspencer3> also like jason, a list is defied with[]
[16:52] <rickspencer3> theopensourcerer, yes, a dictionary can be a value in another dictionary, but it can not be a key in another dictionary
[16:53] <rickspencer3> let's skip to OO syntax since someone asked about that at the beginning, and I only have 7 minutes
[16:53] <rickspencer3> sound ok?
[16:54] <rickspencer3> if I wanted to define a class called "program2" I do it like this:
[16:54] <rickspencer3> class program2:
[16:54] <ClassBot> wharp asked: grades and grades.items() produce the same output, is there a difference?
[16:54] <rickspencer3> if I want program3 to derive from program2, I do it like this
[16:54] <rickspencer3> wharp. that's just because of what would be the to_string() funciton in other languages
[16:55] <rickspencer3> in the interactive interperted when you just type a variable, it tries to print something sensible for you to read
[16:55] <rickspencer3> in a program grades and grades.items() are very different
[16:55] <rickspencer3> grades is the dictionary, grades.items() returns a list of the values
[16:56] <rickspencer3> so, back to classes real quick
[16:56] <rickspencer3> a couple of points I want to touch on
[16:56] <rickspencer3> before we break
[16:56] <rickspencer3> __init__(self):
[16:56] <rickspencer3> this is a function that is more or less the constructor for a class
[16:56] <rickspencer3> it is optional
[16:57] <rickspencer3> unless your super class has one, your subclass has to call the super class's __init__() at some point
[16:57] <rickspencer3> finally, a point about private members
[16:57] <rickspencer3> this is a bit odd in Python
[16:57] <rickspencer3> *there are no private members in Python*
[16:58] <rickspencer3> this badly breaks encapsulation
[16:58] <rickspencer3> however, there are two ways around this
[16:58] <rickspencer3> if you want a private member that you want to be available to subclasses
[16:58] <rickspencer3> use a single underscore to start the variable name
[16:58] <rickspencer3> so:
[16:59] <rickspencer3> self._private
[16:59] <rickspencer3> it's not really private, but the underscore is a convention
[16:59] <rickspencer3> if you don't want it to be accessible to sub classes, use two underscores
[16:59] <rickspencer3> self.__my_very_private
[17:00] <rickspencer3> python will "munge" the variable name at run time
[17:00] <rickspencer3> so it won't be accessible
[17:00] <rickspencer3> well, it kind of will be, but it's harder for other programmers to get at it
[17:00] <rickspencer3> ok, I am out of time :/
[17:00] <rickspencer3> sorry, there was more I wanted to go into
[17:00] <cjohnston> more classes!
[17:01] <rickspencer3> I would stay, but I have to run to a meeting
[17:01] <rickspencer3> please let jono know if you would like more or a follow up or something
[17:01] <rickspencer3> also, #ubuntu-all-devel is a good place for questions
[17:01] <cjohnston> #ubuntu-app-devel
[17:01] <rickspencer3> oops
[17:01] <rickspencer3> sorry, typing and calling :/

MeetingLogs/OpWeek1002/Python4Programmers (last edited 2010-03-01 19:41:59 by dieb)