MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaLang DesignEmacsUnicode ♥

Python: Learn Python in 3 Hours

,

This is a Python tutorial. Spend 3 hours, and you shoud have a basic understanding of the language.

Examples on this page are based on Python 2.7. For python 3, see: Python 3 Basics.

Strings

Strings are enclosed using single quote or double quote. example

# -*- coding: utf-8 -*-
# python

a = "tiger"
b = 'rabbit' # single/double quotes are basically the same in Python
print a, b   # prints 「tiger rabbit」

You can use \n for linebreak, and \t for tab, etc.

Triple Quotes for Multi-Line String

To quote a string of multiple lines, use triple quotes. Example:

d = """this
will be printed
in 3 lines"""

print d

「r"…"」 for Raw String

You can add r in front of the quote symbol. This way, backslash characters will NOT be interpreted as as escapes. (“r” for “raw”)

c = r"this\n and that"
print c # prints a single line

more detail: Python, Ruby, Perl: Quoting Strings

Unicode in String or Source File

If your string contains Unicode, or anywhere in your source file, the first or second line should be # -*- coding: utf-8 -*-. I recommend to always start your file with this.

Also, any string containing Unicode should have “u” prefix u"…".

# -*- coding: utf-8 -*-
# python

a = u"I ♥ Emacs"                    # string with unicode heart 「♥」

substring, length

Substring extraction is done by appending a bracket [‹begin index›:‹end index›]. Index can be negative, which counts from the end.

# -*- coding: utf-8 -*-
# python

b="01234567"
print b[1:4] # prints “123”

Length of the string is len().

a="this"
print len(a) # 4

Strings can be joined by a plus sign +.

print "this" + " that"

String can be repeated using *.

print "this" * 2

Python, Ruby, Perl: Basic String Operations

Arithmetic

# -*- coding: utf-8 -*-
# python

print(3 + 4)                    # 7
print(3 - 4)                    # -1
print(3 + - 4)                  # -1
print(3 * 4)                    # 12

print(2 ** 3)                    # 8 power

print(11 / 5)                    # 2 (quotient)
print(11 / 5.)                   # 2.2 (force to float)
print(11 // 5)                   # 2 (quotient)
print(11 % 5)                    # 1 remainder (modulo)

print(divmod(11, 5))            # (2, 1) quotient and remainder
print(divmod(11.2, 5))          # (2.0, 1.1999) quotient and remainder

In Python, power is “**”. The “^” is used for bitwise xor. 〔☛ Python 3: Operators

Warning: in Python 2, 11/5 returns 2, not 2.2.

Convert to {int, float, string}

Python doesn't automatically convert between {int, float, string}.

Assignment Operators

# -*- coding: utf-8 -*-
# Python

# add and assign
c = 0
c += 1
print c                         # 1

# substract and assign
c = 0
c -= 2
print c                         # -2

# multiply and assign
c = 2
c *= 3
print c                         # 6

# exponent and assign
c = 3
c **= 2
print c                         # 9

# divide and assign
c = 7
c /= 2
print c                         # 3    note: note 3.5

# modulus (remainder) and assign
c = 13
c %= 5
print c                         # 3

# quotient and assign
c = 13
c //= 5
print c                         # 2

Note: Python doesn't support ++ or --.

Warning: ++i may not generate any error, but it doesn't do anything.

For bitwise and other operators, see: Python 3: Operators.

True & False

The following evaluates to false:

Empty string and Empty list-like things are all false.

# -*- coding: utf-8 -*-
# python

my_thing = []

if my_thing:
    print "yes"
else:
    print "no"

Conditional: if then else

#-*- coding: utf-8 -*-
# python

x = -1
if x < 0:
    print 'neg'
#-*- coding: utf-8 -*-
# python

x = -1
if x < 0:
    print 'negative'
else:
    print '0 or positive'
#-*- coding: utf-8 -*-
# python

# Examples of if

x = -1
if x<0:
    print 'neg'
elif x==0:
    print 'zero'
elif x==1:
    print 'one'
else:
    print 'other'

# the elif can be omitted.

Loop, Iteration

# -*- coding: utf-8 -*-
# python

a = range(1,5) # creates a list from 1 to 4. (does NOT include the end range)
for x in a:
    if x % 2 == 0:
        print x, 'even'

In the above, the percent “%” symbol calculates the remainder of division. The range(m,n) function gives a list from m to n-1.

Python also supports “break” and “continue” to exit the loop. “break” will exit the loop. “continue” will skip code and start the next iteration. Example of using “break”.

#-*- coding: utf-8 -*-
# python

for x in range(1,9):
    print 'yay:', x
    if x == 5:
        break
#-*- coding: utf-8 -*-
# python

x = 1
while x < 9:
    print x
    x += 1

List

Creating a list.

a = [0, 1, 2, "more", 4, 5, 6]
print a

Counting elements:

a = ["more", 4, 6]
print len(a) # prints 3

Getting a element. Use the syntax ‹list›[‹index›]. Index start at 0. Negative index counts from right. Last element has index -1.

a = ["more", 4, 6]
print a[1] # prints 4

Extracting a sequences of elements (aka sublist, slice): ‹myList›[‹startIndex›:‹endIndex›].

a = ["nil", "uni", "bi", "tri", "quad", "quint", "sex"]
print a[2:4]   # prints ["bi", "tri"]

WARNING: The extraction is not inclusive. For example, ‹myList›[2:4] returns only 2 elements, not 3.

Modify elements: ‹myList›[‹index›] = ‹new value›.

a = ["nilpotent", "unisex", "bisexual"]
a[2] = "two"
print a # prints ['nilpotent', 'unisex', 'two']

A slice (continuous sequence) of elements can be changed by assigning to a list directly. The length of the slice need not match the length of new list.

# -*- coding: utf-8 -*-
# python

a = ["nilpotent", "unisex", "bisexual", "tribadism", "quadriceps", "quintessence", "sex"]
a[0:6] = ["two", "three"]
print a                         # prints ['two', 'three', 'sex']

Nested Lists. Lists can be nested arbitrarily. Append extra bracket to get element of nested list.

a = [3, 4, [7, 8]]
print a
print a[2][1]    # returns 8

List Join. Lists can be joined with plus sign.

b = ["a", "b"] + [7, 6]
print b      # prints ['a', 'b', 7, 6]

Python, Ruby, Perl: List Basics

tuple

Python has a “tuple” type. It's like list, except it's immutable (that is, the elements cannot be changed).

Syntax for tuble is using round brackets instead of square brackets.

# -*- coding: utf-8 -*-
# python

# tuple
t1 = (3, 4 , 5)                 # a tuple of 3 elements
print t1                        # (3, 4 , 5)
print t1[0]                     # 3

# nested tuple
t2 = ((3,8), (4,9), ("a", 5, 5))
print t2[0]                           # (3,8)
print t2[0][0]                        # 3

# a list of tuples
t3 = [(3,8), (4,9), (2,1)]
print t3[0]                           # (3,8)
print t3[0][0]                        # 3

〔☛ Python: What's the Difference Between Tuple and List?

Python Sequence Types

In Python, {string, list, tuple} are called “sequence types”. They all have the same methods. Here's example of operations that can be used on sequence type.

# -*- coding: utf-8 -*-
# python

# operations on sequence types

# a list
ss = [0, 1, 2, 3, 4, 5, 6]

# length
print len(ss)                    # 7

# ith item
print ss[0]                     # 0

# slice of items
print ss[0:3]                   # [0, 1, 2]

# slice of items with jump step
print ss[0:10:2]                # [0, 2, 4, 6, 8]

# check if a element exist
print 3 in ss                   # True. (or False)

# check if a element does NOT exist
print 3 not in ss               # False

# concatenation
print ss + ss             # [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6]

# repeat
print ss * 2              # [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6]

# smallest item
print min(ss)                   # 0

# largest item
print max(ss)                   # 6

# index of the first occurence
print ss.index(3)                       # 3

# total number of occurences
print ss.count(3)                       # 1

Dictionary; Hash Table; Associative List

A keyed list in Python is called “dictionary”. It is a unordered list of pairs, each consists of a key and a value.

#-*- coding: utf-8 -*-
# python

# define a keyed list
aa = {"john":3, "mary":4, "jane":5, "vicky":7}
print "aa is:", aa

# getting value from a key
print "mary is:", aa["mary"]

# add a entry
aa["pretty"] = 99
print "added pretty:", aa

# delete a entry
del aa["vicky"]
print "deleted vicky", aa

# get just the keys
print "just keys", aa.keys()
# to get just values, use “.values()”

# check if a key exists
print "is mary there:", aa.has_key("mary")

http://docs.python.org/lib/typesmapping.html

See: Python & Perl: Dictionary, Hash

Looping Thru a List

Here is a example of going thru a list by element.

myList=['one', 'two', 'three', 'infinity']
for x in myList:
     print x

You can loop thru a list and get both {index, value} of a element. Example:

myList=['one', 'two', 'three', 'infinity']
for i, v in enumerate(myList):
     print i, v

# 0 one
# 1 two
# 2 three
# 3 infinity

The following construct loops thru a dictionary, each time assigning both keys and values to variables.

myDict = {'john':3, 'mary':4, 'jane':5, 'vicky':7}
for k, v in myDict.iteritems():
     print k, ' is ', v

See also: Python, Ruby, Perl: Apply a Function to a List.

Using Library

A library in Python is called a module.

# -*- coding: utf-8 -*-
# python

# import the standard module named os
import os

# example of using a function
print 'current dir is:', os.getcwd()
# -*- coding: utf-8 -*-
# python

import os

# print all names exported by the module
print dir(os)

More: Python & Perl: Using Modules/Packages/Library.

Defining a Function

The following is a example of defining a function.

def myFun(x,y):
     """myFun returns x+y."""
     result = x+y
     return result

print myFun(3,4) # prints 7

A string immediately following the function definition is the function's documentation.

A function can have optional parameters. If no argument is given, a default value is assumed. Example:

def myFun(x, y=1):
    """myFun returns x+y.
    Parameter y is optional and default to 1"""
    return x+y

print myFun(3)

For defining infinite number of parameters, or unspecified keyword parameters, see: Python, Ruby, Perl: Defining A Function.

Classes and Objects

Example:

# -*- coding: utf-8 -*-
# python

# in the following, we define a set of data and functions as a class,
# and name it xxx

class xxx:
     "A class extempore! =(^_^)="
     i=1 # i'm a piece of data
     def okaydokey(self): return "okaydokey"
     def square(self,a): return a*a

# in the following, we create a object of the class xxx.  This is
# called “instantiating a class”.
x = xxx()

# Data or functions defined in a class are called the class's
# attributes or methods. To use them, append a dot and their name
# after the object's name.
print 'value of attribute i is:', x.i
print "3 squared is:", x.square(3)
print "okaydokey called:", x.okaydokey()

# In the definition of function inside a class, the first parameter
# “self” is necessary. It is just side-effect of the language design.

# The first line in the class definition is the class's
# documentation. It can be accessed thru the __doc__ attribute.
print "xxx's doc string is:", x.__doc__

# var inside the class can be change like this
x.i = 400

# new data can be added to the class
x.j=4
print x.j

# A class's method can also be over-rided
x.square = 333
# (the following line will no longer work)
## print "3 squared is:", x.square(3)

Writing a Module

Here's a basic example. Save the following line in a file and name it mymodule.py.

def f1(n): return n+1

To load the file, use import import mymodule, then to call the function, use moduleName.functionName. Example:

import mymodule           # import the module
print mymodule.f1(5)      # calling its function
print mymodule.__name__   # list its functions and variables

http://docs.python.org/lib/typesmodules.html

blog comments powered by Disqus