Python basics

From SHellium Wiki
Jump to: navigation, search
Geographylogo.png In other languages: English | Afrikaans | Albanian | Arabic | Brazilian | Bulgarian | Catalan | Chinese | Croatian | Czech | Danish | Dutch | Esperanto | Estonian | Filipino | Finnish | Flemish | French | German | Greek | Hebrew | Hindi | Hungarian | Indonesian | Italian | Japanese | Latvian | Lithuanian | Macedonian | Malay | Malayalam | Norwegian (Bokmål) | Norwegian (Nynorsk) | Persian | Polish | Portuguese | Romanian | Russian | Serbian | Slovak | Slovenian | Spanish | Swedish | Turkish | Ukrainian | Urdu

article written originally by Signal360

Contents

An introduction

Python is a wonderful language, it's simple, easy, and quick to learn. It's written and also extendable with C, extending python can make code execute much faster, but we'll start with the basics.


Writing your first application

   print "Hello World!" 

Let's go into more detail!


Code blocks (also known as identation)

In python, a very important thing is to tab every time you go into a new code block, and every time you leave a code block, is to go down one tab. For instance:

In C, we have a simple if statement:

   if (1)
   {
      printf("1 is 1");
      
      ... code inside the if block
   }
   else
   {
      printf("how could 1 possible not be 1?");
      ...code inside the else block
   }

In python, however, to show code-blocks, instead of wrapping the block with curly-brackets, you need to tab, and go up one identation level, Do NOT use spaces!:

   if 1:
      print "1 is 1"
   
      ... code inside the if block
   else:
      ...otherwise?
      print "how could 1 possibly not be 1?"
      ...code inside the else block
   ... code outside the block

if/else/elif statement

If statements in python are fairly easy:

   if condition:
      ... code inside the if block
   elif condition:
      ... code inside the elif block 
   else:
      ... code inside the else block


For example:


   number = 4
   if number < 0:
      print "the number is negative!"
   elif number > 10:
      print "the number is over ten!"
   else:
      print "the number is between 0 and 10!"

executing this program would output:


the number is between 0 and 10!

Loops

The For loop

For loops are very different to that of in C, here is the basic structure

   for thing in iterable:
      print thing

a for loop on iterable would make thing one of the objects in iterable.


for instance:

   for letter in 'abc':
      print letter

now, this would output:

a

b

c

so, basically, the for loop went through that string, and for each letter, executed the code block with the letter variable as the letter. Other iterable objects can be dictionaries and lists.

range()

Ok, if you simply wanted to loop for 10 times, how do you do it?

range() generates an iterable object that has numbers in the range specified.

For instance..!

   for number in range(10):
       print number

This counts from one to ten,

   for number in range(5, 20):
       print number

This counts up from five to twenty.


The While loop

This is quite simple, here is the basic structure:

 while condition:
   ...repeated block until condition is false
   

I.E:

 x = -10
 while x < 0:
   x += 1
   print x
 
 This simply adds on to value x until it's not under zero.
 

Lists and tuples

Lists and tuple is just a posh python term for 'array' but both of them are different.

Tuples

These are kind of like read only arrays. they are defined as so:

 ( 'object one!', 2, ('another tuple?!') )

Each object is seperated by a comma, and the sequence is enclosed in brackets.

Lists

These are very changable arrays, you can append objects, remove objects, insert objects at a certain point, sort objects into order, use it as an iterator.

A list structure would look something like this:

 [ 'object one', 2, ('tuple object?!'), 4, {'a': 'dictionary?'} ]
 
 lists provide functions that let you append/remove/insert objects. here is how:
 
 somelist = [2, 4]
 
 # appending an object, this would change the list to: [2, 4, 3]
 somelist.append(3)
 
 # we need a 5 at the front, we use insert to do it:
 somelist.insert(0, 1)
 # the result is: [1, 2, 4, 3]
 
 # but we want the numbers in order!
 # so, we use sort.
 somelist.sort()
 
 # now, the list is: [1, 2, 3, 4]
 
 # we want to get rid of 3?
 # so, we use pop()
 somelist.pop(2)

Indexing

Say, how do we actually access an object in a list/tuple? Well, it's very simple:

We have a list, somelist = [1, 2, 3, 4]. We want to access 3, so, it's the third item in the list, so, somelist[2] would return the third item (because 0 is first), the number enclosed in the square brackets shows the part we want to get, somelist[0] would return 1, the first item in the list.

The same applies for a tuple.


Dictionaries

A Dictionary (dict()) are like hashes (in C/CPP), it's a data structure that allows you to access other objects with keys.

Here is an example of a dictionary structure:

 mydict = { 'string': "Hello!",
            1: 1,
            "one plus one": 2,
          }

This may look all a bit confusing at first, but as you go along, it will seem much more simple than you think.

For instance, if you wanted to access the string "Hello!", you would call from the interpreter:

 >>> mydict['string']
 'Hello!'

Same thing if you wanted to get 1

 >>> mydict[1]
 1

The string contained between the square brackets is searched for in the dictionary object, if it's found, it returns the object it's associated with, but if it doesn't exist...

 >>> mydict['blah']
 
 Traceback (most recent call last):
   File "<pyshell#9>", line 1, in <module>
     mydict['blah']
 KeyError: 'blah'

Personal tools
Namespaces

Variants
Actions
Navigation
Indexes
SHellium Sites
Toolbox