
-----------------------------------
wtd
Wed Nov 03, 2004 11:16 pm

[Python-tut] Python Basics
-----------------------------------
What is Python?

PythonWhat do you need?

You'll need to install the Python interpreter.  It's available A text editor, preferably with Python syntax highlighting.  For Windows, Python syntax file

How do I use the Python interpreter?

The Python interpreter is typically run from the command-line.  It can either be used to run entire source files, or to interactively run code as you write it.

For learning the language, I would recommend running the interpreter interactively.  To do so, open a console window.  Those using Linux or Mac OS X should know how to do this.  Windows users should go to Start -> Run and type "cmd".  At the prompt, type "python" and hit enter.

Hello, world

Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print "Hello, world"
Hello, world
>>>

Pretty easy, eh?  It prints "Hello, world", then gives you a prompt for the next bit of code.

Variables

There's no need to declare variables in Python.  Simply assign to them and they spring into existence.

>>> foo = 42
>>>

There are literals for integers, floating point numbers, strings, lists, and dictionaries.  Tuples are also there, but they don't come into the picture... yet.

>>> bar = 27.3
>>> baz = "Yo-yo"
>>> hello = [1, 2, 3]
>>> world = {"foo": 42, "bar": 27.3, "hello": hello}
>>>

If... elif... else...

>>> if foo > 21:
...    print "foo is greater than 21"
... elif foo < 3:
...    print "foo is less than 3"
... else:


...    print "foo is between 3 and 21"
...
foo is greater than 21
>>>

Notice that instead of braces or "end", Python uses indentation.  You'd probably indent it anywYou can ay, so this isn't terribly onerous.  Just make sure you use indents consistently.

Other logical operators are ==, !=, "is", "is not", =, "or" and "and".  To negate anything, use "not".  The constants "True", and "False" are also provided.

You can also use "in" and "not in" with lists, dictionaries and strings.

>>> if "he" in "hello":
...    print "It's there"
... else
...    print "It's not there"
...
It's there
>>>

>>> if "z" not in "hello":
...    print "It's not there"
... else:
...    print "It's there"
...
It's not there
>>>

When using these with dictionaries, "in" and "not in" checks to see if the dictionary has a key.

>>> my_dictionary = {"hello" : "world"}
>>> if "hello" in my_dictionary:
...    print "The key is there"
...
The key is there
>>> if "world" in my_dictionary:
...    print "The key is there"
...
>>>

Loops

Two loops are provided.  The most frequently seen is the for loop.

>>> for ch in "hello":
...    print ch
...
h
e
l
l
o
>>>

Each element in "hello" is assigned to ch in turn and the loop body is executed.  This works the same way on lists as well.

It's possible to loop in reverse.

>>> for ch in reversed("hello"):
...    print ch
...
0
l
l
e
h
>>>

Dictionaries work similarly, though we use the iteritems() method to get both the key and value.

>>> for key, value in {"hello": "world"}:
...    print key, value
...
hello world
>>>

We can also count as we move through a list or string, with the enumerate() function.

>>> for i, value in enumerate([76, 42, 27]):
...    print i, value
...
0 76
1 42
2 27
>>> for i, ch in enumerate("hello"):
...    print i, ch
...
0 h
1 e
2 l
3 l
4 o
>>>

While loops are far simpler.

>>> i = 4
>>> while i >= 0:
...    print i
...    i -= 1
...
4
3
2
1
0
>>>

Defining functions

Defining functions is easy.  A simple example, taking zero arguments.

>>> def hello_world():
...    print "Hello, world"
...
>>> hello_world()
Hello, world
>>>

A function which takes an argument.

>>> def hello(name):
...    print "Hello, " + name
...
>>> hello("John")
Hello, John
>>>

We can provide default values for arguments.

>>> def hello(name = "Bob"):
...    print "Hello, " + name
...
>>> hello("John")
Hello, John
>>> hello()
Hello, Bob
>>>

We can use the argument name when we call a function.  This is great for functions with multiple arguments, when you can't remember which arguments come first.

>>> def hello(name):
...    print "Hello, " + name
...
>>> hello(name="John")
Hello, John
>>>

We can "slurp" up any extra arguments provided into a list.

>>> def hello(name, *other_names):
...    print "Hello, " + name
...    for other_name in other_names:
...       print "Hi " + other_name
...
>>> hello("Bob", "Mike", "Alan")
Hello, Bob
Hi Mike
Hi Alan
>>>

Oh, and we can slurp up arguments given names that we didn't specify.

>>> def foo(**named_args):
...    for key, value in named_args.iteritems():
...       print key, ":", value
...
>>> foo(name="wtd", title="Newbe God")
name : wtd
title : Newbe God
>>>

-----------------------------------
Mazer
Thu Nov 04, 2004 8:31 am


-----------------------------------
YAY it's python! Thanks wtd.

-----------------------------------
wtd
Thu Nov 04, 2004 2:54 pm


-----------------------------------
YAY it's python! Thanks wtd.

You're quite welcome.

-----------------------------------
Amailer
Sun Nov 07, 2004 1:39 am


-----------------------------------
hey thanks.
Now even though im not learing Python, I want to edit this viewCvs scritpt but I can't seem to get the string.replace function to work (i think thats the name of hte function).

What I want to do is
for every


span style


replace it with


span class="code" style


strange, I could do it in php but not rudy (I think i got the location and variabele which is 'html' correct).

Thanks

-----------------------------------
wtd
Sun Nov 07, 2004 4:28 am


-----------------------------------
hey thanks.
Now even though im not learing Python, I want to edit this viewCvs scritpt but I can't seem to get the string.replace function to work (i think thats the name of hte function).

What I want to do is
for every


span style


replace it with


span class="code" style


strange, I could do it in php but not rudy (I think i got the location and variabele which is 'html' correct).

Thanks

Well, in Ruby

str = "Hello"
revised_str = str.gsub(/span\s+style/i, "span class='code' style")

In Python

from string import replace

str = "Hello"
revised_str = replace(str, "span style", "span class='code' style")

Unfortunately regular expressions aren't as easy in Python, so the Python example isn't as flexible.

-----------------------------------
Shyfire
Wed Apr 20, 2005 10:20 am


-----------------------------------
wow i'v got a lot of learning to do  :shock:  

this python stuff is a lot more difficult then turing
any suggestions on were i should start :lol: 

cuz i am sooooo lost :?:

-----------------------------------
wtd
Wed Apr 20, 2005 2:05 pm


-----------------------------------
wow i'v got a lot of learning to do  :shock:  

this python stuff is a lot more difficult then turing
any suggestions on were i should start :lol: 

cuz i am sooooo lost :?:

Actually, I'd wager it's a lot easier to learn than Turing.  ;)

You may wish to check out the tutorial at python.org.

-----------------------------------
StealthArcher
Sat Jan 12, 2008 1:37 pm

Re: [Python-tut] Python Basics
-----------------------------------
To an extent yes...  but the for loop seems harder to me...

-----------------------------------
SIXAXIS
Mon Feb 18, 2008 1:17 pm

Re: [Python-tut] Python Basics
-----------------------------------
Quick question for you Python masters. When I enter this:

foo=raw_input ("")
if foo > 23:
	print "foo is greater than 23."
if foo < 3:
	print "foo is less than 3."
else:
	print "foo is between 3 and 23."

It always says that foo is greater than 23. What am I doing wrong. BTW, I tried this without having user input.

-----------------------------------
McKenzie
Mon Feb 18, 2008 1:23 pm

Re: [Python-tut] Python Basics
-----------------------------------
Two errors,
1. Use input() for numbers. raw_input() returns a string
2. use elif for your second condition otherwise 50 is both greater than 23 and between 3 and 23.

-----------------------------------
wtd
Mon Feb 18, 2008 2:25 pm

RE:[Python-tut] Python Basics
-----------------------------------
Alternatively, if you can get a string with raw_input, and you know how to turn a string into an integer, then you know full well how to use raw_input to get an integer.

-----------------------------------
Epic Tissue
Sat Jun 14, 2008 6:09 am

RE:[Python-tut] Python Basics
-----------------------------------
Thanks for this tut! Great starting point :)

-----------------------------------
juzten
Mon Sep 08, 2008 3:08 pm

RE:[Python-tut] Python Basics
-----------------------------------
Yeah thanks, I am just learning python and this explained alot of my questions
