[Python-tut] Python Basics
Author |
Message |
wtd
|
Posted: Wed Nov 03, 2004 11:16 pm Post subject: [Python-tut] Python Basics |
|
|
What is Python?
Python is an interpreted, object-oriented programming language.
What do you need?
- You'll need to install the Python interpreter. It's available for Windows here. If you have Linux or Mac OS X, you can grab the source for it here.
- A text editor, preferably with Python syntax highlighting. For Windows, Textpad is a superb option, especially when equipped with the 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
code: | 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.
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.
code: | >>> bar = 27.3
>>> baz = "Yo-yo"
>>> hello = [1, 2, 3]
>>> world = {"foo": 42, "bar": 27.3, "hello": hello}
>>> |
If... elif... else...
code: | >>> 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", <=, and >=, "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.
code: | >>> if "he" in "hello":
... print "It's there"
... else
... print "It's not there"
...
It's there
>>> |
code: | >>> 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.
code: | >>> 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.
code: | >>> 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.
code: | >>> 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.
code: | >>> 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.
code: | >>> 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.
code: | >>> 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.
code: | >>> def hello_world():
... print "Hello, world"
...
>>> hello_world()
Hello, world
>>> |
A function which takes an argument.
code: | >>> def hello(name):
... print "Hello, " + name
...
>>> hello("John")
Hello, John
>>> |
We can provide default values for arguments.
code: | >>> 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.
code: | >>> def hello(name):
... print "Hello, " + name
...
>>> hello(name="John")
Hello, John
>>> |
We can "slurp" up any extra arguments provided into a list.
code: | >>> 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.
code: | >>> 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
>>> |
|
|
|
|
|
|
Sponsor Sponsor
|
|
|
Mazer
|
Posted: Thu Nov 04, 2004 8:31 am Post subject: (No subject) |
|
|
YAY it's python! Thanks wtd. |
|
|
|
|
|
wtd
|
Posted: Thu Nov 04, 2004 2:54 pm Post subject: (No subject) |
|
|
Coutsos wrote: YAY it's python! Thanks wtd.
You're quite welcome. |
|
|
|
|
|
Amailer
|
Posted: Sun Nov 07, 2004 1:39 am Post subject: (No subject) |
|
|
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
replace it with
code: |
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
|
Posted: Sun Nov 07, 2004 4:28 am Post subject: (No subject) |
|
|
Amailer wrote: 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
replace it with
code: |
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
code: | str = "<span style='font-weight:bold'>Hello</span>"
revised_str = str.gsub(/span\s+style/i, "span class='code' style") |
In Python
code: | from string import replace
str = "<span style='font-weight:bold'>Hello</span>"
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
|
Posted: Wed Apr 20, 2005 10:20 am Post subject: (No subject) |
|
|
wow i'v got a lot of learning to do
this python stuff is a lot more difficult then turing
any suggestions on were i should start
cuz i am sooooo lost |
|
|
|
|
|
wtd
|
Posted: Wed Apr 20, 2005 2:05 pm Post subject: (No subject) |
|
|
fatboi wrote: wow i'v got a lot of learning to do
this python stuff is a lot more difficult then turing
any suggestions on were i should start
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
|
Posted: Sat Jan 12, 2008 1:37 pm Post subject: Re: [Python-tut] Python Basics |
|
|
To an extent yes... but the for loop seems harder to me... |
|
|
|
|
|
Sponsor Sponsor
|
|
|
SIXAXIS
|
Posted: Mon Feb 18, 2008 1:17 pm Post subject: Re: [Python-tut] Python Basics |
|
|
Quick question for you Python masters. When I enter this:
Python: | 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
|
Posted: Mon Feb 18, 2008 1:23 pm Post subject: 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
|
Posted: Mon Feb 18, 2008 2:25 pm Post subject: 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
|
Posted: Sat Jun 14, 2008 6:09 am Post subject: RE:[Python-tut] Python Basics |
|
|
Thanks for this tut! Great starting point |
|
|
|
|
|
juzten
|
Posted: Mon Sep 08, 2008 3:08 pm Post subject: RE:[Python-tut] Python Basics |
|
|
Yeah thanks, I am just learning python and this explained alot of my questions |
|
|
|
|
|
|
|