Author Topic: Coding and Scripting > Learning Python  (Read 8019 times)

Offline Neal ManBear

  • Administrator
  • Super Villain
  • *****
  • Posts: 15847
  • LXDE! Coffee, Bacon and Cheesecake!
Coding and Scripting > Learning Python
« on: December 03, 2009, 12:44:50 PM »
It seems that python has quite a few fans according to our poll, so lets get started.


Neptune

  • Guest
Re: Coding and Scripting > Learning Python
« Reply #1 on: December 03, 2009, 03:02:55 PM »
Hmph - Neal apparently recruits volunteers much the way General Patton did...

What you'll need (for now):
-Python - I believe this is a default for PCLinuxOS, but if not, it's in Synaptic as "python"
-A programmer's editor. Kate, or KWrite is fine. In theory, any program that can edit text will do, but you'll find life easier with features such as auto-indenting and syntax highlighting that you'll get from an editor that "speaks your language".
-A terminal emulator - again, I believe "konsole" is installed by default, and it will do, but if you have a favorite, by all means use it.

What I'll need:
-Some sense of where you are in terms of programming concepts; variables, variable typing, functions, etc. - although, as this forum format is a single-threaded interface, perhaps it's better to assume nothing and start at a very rudimentary level, rather than jumping back and forth in skill/knowledge levels throughout the thread.
-Feedback from you. The last thing I want to do is leave people gasping for air.


Offline Neal ManBear

  • Administrator
  • Super Villain
  • *****
  • Posts: 15847
  • LXDE! Coffee, Bacon and Cheesecake!
Re: Coding and Scripting > Learning Python
« Reply #2 on: December 03, 2009, 03:25:54 PM »
Hmph - Neal apparently recruits volunteers much the way General Patton did...

Well, I did pose it as a question. ;D

Quote
What you'll need (for now):
-Python - I believe this is a default for PCLinuxOS, but if not, it's in Synaptic as "python"
-A programmer's editor. Kate, or KWrite is fine. In theory, any program that can edit text will do, but you'll find life easier with features such as auto-indenting and syntax highlighting that you'll get from an editor that "speaks your language".
-A terminal emulator - again, I believe "konsole" is installed by default, and it will do, but if you have a favorite, by all means use it.

Yes, Python is installed by default on all PCLinuxOS ISOs.
There are several good editors available in the repos, if anyone finds those installed by default not to their liking.
Konsole, Gnome-Terminal, lxterminal and so on are available, if not already installed.

Quote
What I'll need:
-Some sense of where you are in terms of programming concepts; variables, variable typing, functions, etc. - although, as this forum format is a single-threaded interface, perhaps it's better to assume nothing and start at a very rudimentary level, rather than jumping back and forth in skill/knowledge levels throughout the thread.
-Feedback from you. The last thing I want to do is leave people gasping for air.



Well, "assume nothing and start at a very rudimentary level" sounds like a great start to me. Anyone more advanced can pitch in to help answer questions until we catch up to the same level.

I might do a little gasping for air, but I'll do my best to keep up with the others here.


Offline Andy Axnot

  • Hero Member
  • *****
  • Posts: 694
Re: Coding and Scripting > Learning Python
« Reply #3 on: December 03, 2009, 05:45:21 PM »
I started reading through an introductory Python book a few months ago.  Then I had to put it aside.  I just launched Python to see what I remember.  I got hello_world to run!

Code: [Select]
>>> print "hello, world!"
hello, world!
   ;D

That's as much as I remember.  Better start at the beginning.   ::)

Andy
Greetings from beautiful downtown Brooklyn, NY   USA
  Still searching for a replacement for KDE3; E17 is looking good; LXDE, too

"all will be fine soon, once kde3 is back on the main repos" - Titus T6us    :o

Online gseaman

  • PCLinuxOS Tester
  • Hero Member
  • *******
  • Posts: 3800
Re: Coding and Scripting > Learning Python
« Reply #4 on: December 03, 2009, 06:22:42 PM »
I've experimented with c and c++ tutorials (started up again). I understand everything up to and including the concept of pointers but I easily get lost in the details. Did a little basic back in the day. I've done a little bash coding, but I haven't even looked at python code before. I'll keep up with the lessons, so give us the first assignment, boss!

Galen

Neptune

  • Guest
Re: Coding and Scripting > Learning Python
« Reply #5 on: December 03, 2009, 06:34:19 PM »
Let's see how it goes.

What is Python, anyway? As has been noted, it is a scripting language. Scripting languages are translated into "computer-speak" as they run. This is as opposed to languages like C, which are pre-translated into a format the machine can digest by using compilers and linkers. Scripting programs generally execute more slowly for this reason, but have a faster development cycle, since you skip the whole compile/link step as you go through development iterations. In an age of multi-gigahertz processors, the perceived speed handicap of scripting languages is becoming less and less relevant.

Python is an object-oriented language. Everything in Python is an object. Generally, think of an object like a car - it has attributes, and methods. Car attributes might include four wheels, green paint, glass windows. Car methods might include accelerating, braking and steering. Similarly, objects in Python will (mostly) have attributes, and methods, which we'll get into shortly.

But first, open your favorite terminal program, such as Konsole, and type in what you see in green, then press enter:


[zccw01@LapNix ~]$ python
Python 2.5.2 (r252:60911, Jun 28 2008, 14:11:09)
[GCC 4.1.1 20060724 (prerelease) (4.1.1-4pclos2007)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>          



If you don't see something that resembles the above, scream now. This is the python interactive shell. Try the following, entering the text shown in green and pressing enter.

[zccw01@LapNix ~]$ python
Python 2.5.2 (r252:60911, Jun 28 2008, 14:11:09)
[GCC 4.1.1 20060724 (prerelease) (4.1.1-4pclos2007)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 5+3.14159
8.1415900000000008
>>>        


Several important things just happened here.

First, Python parsed the expression, and discovered that it had two constants, 5 and 3.14159, with a binary operator, +.

Second, it determined the "type" of the constants. 5 is an integer number, and 3.14159 is a floating-point number.

Third, based on the type of the operands, 5 and 3.14159, it decided that the + operator should be a mathematical summation - addition. The + operator is "overloaded" in Python - depending on the operands, it may perform a different operation, such as concatenating two strings.

Fourth, it "upgraded" the integer, 5 to a floating point. You didn't ask Python to do this, but if there are mixed operand types, Python will always try to A) do what's expected, and B) give you the most precise result. This conversion was necessary because integers and floating-point numbers are stored in two very different ways - binary math operators require that the operand be of the same type before they can work properly.

Fifth, it calculated the result, formatted it and printed it for you.

And, sixth - it got the answer wrong. The wrong answer wasn't really Python's fault - it's a necessary evil of trying to store decimal fractions into a bunch of binary on/off switches  All languages, to one degree or another, share this problem, and in programming, you have to keep it in mind - There are ways to be more accurate - much more accurate, but never completely accurate. Just be sure that your results are accurate enough for the task at hand.

So, since Python is so obliging with object typing, it should have no problem with the following (enter the green text into the Python shell and press enter):
5+"23" # Note the quotes - Yes, enter this too, on the same line

Did you get something that looks like the following?:

[zccw01@LapNix ~]$ python
Python 2.5.2 (r252:60911, Jun 28 2008, 14:11:09)
[GCC 4.1.1 20060724 (prerelease) (4.1.1-4pclos2007)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 5+3.14159
8.1415900000000008
>>> 5+"23" # Note the quotes - Yes, enter this too, on the same line
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>            


Congratulations - you've just crashed your first program. What happened? Was it that extra # Note the quotes - Yes, enter this too, on the same line?
Nope - the # sign is signifies a comment to python, and the interpreter ignores the comment, and everything that follows on the same line. So that wasn't the problem. If we examine the result, you'll see that your program died in line 1 (not surprising, as there's only one line) and that the operand types are unsupported for the + operator.

This is not strictly true. The plus operator does support string and integer types - just not in the same expression.

Enter the following lines into the python interpreter, pressing enter after each line:

a="53";b=27
a+str(b)
int(a)+b


(sleazy data entry tip - highlight the line with your mouse in the browser window, then, in the terminal window that's running the python shell, click down on your mousewheel, or middle button - I know, every one already knows this, but...)

Did you get something like the following?:

>>> a="53";b=27
>>> a+str(b)
'5327'
>>> int(a)+b
80
>>>      


The first line is really two lines. The semicolon allows you to put more than one logical Python line on a single physical line - don't abuse this trick. Python reads easier vertically than horizontally. On this line, we created two new variables, a and b. Using the = assignment operator, we assigned the string constant '53' to variable a, and the integer constant, 27 to variable b.

On the next line,  a+str(b), we brought a new trick to the party - explicit casting. Up til now, we've let Python imply the casting of variable and constant types, but sometimes, slick as it is, Python needs a little guidance. In this line, we used the explicit str() cast to force the variable, b, to be evaluated as a string type. As a result, the interpreter evaluated two string operands, and decided that the + operator should perform concatenation, instead of addition. The result was that the two strings, '53' and '27' were concatenated to give '5327'.

In the final line, we explicitly cast the string variable a as an integer. The result was the + operator dealing with two integers, and an addition that yielded 80 for an answer.

So, given the preceding, you should have some idea of what will happen when you enter the following:
'This ' * 8 + 'That'

Did that surprise you? Here's what I got:

>>> 'This ' * 8 + 'That'
'This This This This This This This This That'
>>>  


When you think about it, it makes sense - after all, if Python can overload the + operator to mean either addition or concatenation, then it makes sense that the * operator is similarly overloaded to mean either multiplication (which is just repeated addition) or multiple concatenation.

So when the teacher asks you to stay after class and write 'I Love Python' twenty times on the chalkboard...

print('I Love Python\n' * 20)

Should do the job - and introduce you to the ideas of text formatting (\n), and functions, such as print()

Play with the above, and when you're finished, press CTRL-d to close the Python shell.

Next up: Functions and modules and bears, oh my!


« Last Edit: December 03, 2009, 06:41:51 PM by Neptune »

Offline Andy Axnot

  • Hero Member
  • *****
  • Posts: 694
Re: Coding and Scripting > Learning Python
« Reply #6 on: December 03, 2009, 08:26:31 PM »
Wow!  This is a truly excellent start!

Have you thought about how you will pace this tutorial?  We certainly want to give everyone time to read the material, do the exercises and ask questions.

Again, I'm so impressed with this tutorial.  You writing a book on Python or somethin'?   :)

Andy
Greetings from beautiful downtown Brooklyn, NY   USA
  Still searching for a replacement for KDE3; E17 is looking good; LXDE, too

"all will be fine soon, once kde3 is back on the main repos" - Titus T6us    :o

Offline Crow

  • Hero Member
  • *****
  • Posts: 8770
  • OBJECTS IN MIRROR... ARE LOSING
Re: Coding and Scripting > Learning Python
« Reply #7 on: December 03, 2009, 08:50:36 PM »
I wonder, why is a lot of dust around me?  ;)

Thank you
I shall pass this way but once;
any good therefore that I can do,
or any kindness that I can show
let me not defer nor neglect it,
for I shall not pass this way again.

Linux User #330412

Online gseaman

  • PCLinuxOS Tester
  • Hero Member
  • *******
  • Posts: 3800
Re: Coding and Scripting > Learning Python
« Reply #8 on: December 03, 2009, 09:53:50 PM »
I think about one lesson a day would be a good pace for me, if you are willing. If someone misses a few days, they should be able to catch up quickly. Is anyone joining us besides Neal, Andy Axnot, Crow, myself and our professor, Neptune? (What is the best source for python info?)

Galen

Offline Bald Brick

  • PCLinuxOS Tester
  • Hero Member
  • *******
  • Posts: 6386
  • I'm going South
Re: Coding and Scripting > Learning Python
« Reply #9 on: December 03, 2009, 10:08:21 PM »
Is anyone joining us besides Neal, Andy Axnot, Crow, myself and our professor, Neptune?

Me too.
Feed the trolls!
They need it!

AMD Athlon 7450 Dual-Core Processor, 7.80 GiB RAM, Nvidia GeForce GT 120/PCIe/SSE2, OpenGL/ES-version: 3.3 0 NVIDIA 295.40, SBx00 Azalia (Intel HDA) soundcard, ‎Logitech B500 webcam, SAA7146 DVB card, HDDs: Seagate 250824AS, Western Digital WD10EAVS-00D

Offline Old-Polack

  • Administrator
  • Super Villain
  • *****
  • Posts: 11591
  • ----IOFLU----
Re: Coding and Scripting > Learning Python
« Reply #10 on: December 03, 2009, 10:30:47 PM »
Is anyone joining us besides Neal, Andy Axnot, Crow, myself and our professor, Neptune?

But, of course! ;)
Old-Polack

Of what use be there for joy, if not for the sharing thereof?



Lest we forget...

Online gseaman

  • PCLinuxOS Tester
  • Hero Member
  • *******
  • Posts: 3800
Re: Coding and Scripting > Learning Python
« Reply #11 on: December 03, 2009, 10:39:26 PM »
Just say 'here' when I call your name ;D

Neptune
Neal
Andy Axnot
Crow
Old-polack
gseaman

and blackbird (oops!)
and critter too.
« Last Edit: December 04, 2009, 01:12:52 AM by gseaman »

Neptune

  • Guest
Re: Coding and Scripting > Learning Python
« Reply #12 on: December 03, 2009, 11:05:44 PM »
Wow!  This is a truly excellent start!

Glad you liked it.

Quote
Have you thought about how you will pace this tutorial?  We certainly want to give everyone time to read the material, do the exercises and ask questions.

Pacing is up to the class - but keep in mind I'm an old guy and this stuff leaks out of my head about as fast as I can write it down. I guess we could just go with a thread "show of hands" when you have some degree of comfort with the segment - This is kind of a different format for learning, so we may just have to make up the rules as we go along - thoughts?

Quote
Again, I'm so impressed with this tutorial.  You writing a book on Python or somethin'?   :)

Nah, all the good books on Python have been written. My main goal is to get folks to the point that they have enough confidence to take off the training wheels and ride on their own to Python programming glory.

Crow:
Quote
I wonder, why is a lot of dust around me?

That would be me - some days I'm dusty, others, foggy.

Gseaman:
Quote
I think about one lesson a day would be a good pace for me, if you are willing.

That's that pacing thing - we'll see how the group paces itself. Some installments may take a little more cud-chewing than others.

Quote
What is the best source for Python info.

Well... that's kind of subjective. python-docs in synaptic is a good reference. python.org, is of course a mother-lode of python documentation. 'Dive into Python' is freely available on the web, but it's geared towards experienced programmers, and can be a bit like realizing that you accidentally got onto one of the black slopes at your ski resort. Then there are various "cookbook" websites that have python snippets that perform various tasks.

blackbird and old-polack - glad to have you. Rumor has it there is some actual programming talent lurking in the classroom, so chime in if I say anything particularly idiotic, like "you MUST comment every line."

Offline critter

  • Full Member
  • ***
  • Posts: 220
Re: Coding and Scripting > Learning Python
« Reply #13 on: December 04, 2009, 12:46:12 AM »
I always preferred scripting to coding but never tried python before.
I'd like to tag along if you don't mind :)
Motherboard   Gigabyte Z68X-UD3H-B3
Hard Drives      2 x Maxtor STM350032 500GB SATA
Memory      16GB RAM
Processor      Intel core i5 3.30GHz
Video         nVidia GeForce GT430
Sound      HDA Intel PCH
PCLinuxOS          KDE

musonio

  • Guest
Re: Coding and Scripting > Learning Python
« Reply #14 on: December 04, 2009, 02:00:40 AM »
Cmon man. I want more!!
(And I'm too lazy to search for python in google)