Python recognizes blocks by indentation. (No worry, you will love it.)
# Simple implementation of Mint problem. # Define constants. INF = 99999 denom = [1, 5, 10, 25, 50] # Initialize the table. table = [0] * 100 # Recursively compute the number of coins. def coins(n): if n < 0: return INF elif n == 0: return 0 else: if table[n] == 0: table[n] = min([ coins(n-d) for d in denom ]) + 1 return table[n] # Sample run print coins(77) print [ coins(i) for i in range(1,100) ]
# Return the quotient and the remainder at once. def div(x, y): quotient = int(x / y) remainder = x % y return (quotient, remainder) # Assign two values to different variables. (q, r) = div(33, 5) print q print r
a = "0 p 1 y 2 t 3 h 4 o 5 n 6"
a[0]
== "p"
a[-1]
== "n"
a[2:4]
== "th"
a[1:]
== "ython"
a[:-3]
== "pyt"
a[2:-1]
== "tho"
Python has nice interactive features (Bash-like line editing, function completion and history), which make it easy to play with built-in functions and libraries. It also includes online help function for almost every function in the library.
Here is a sample session:
$ python Python 2.3.3 (#1, Feb 1 2004, 23:04:28) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> fp=file("/etc/hosts") (get a file object first) >>> fp. (press Tab key here, it tries to expand the available methods) fp.__class__ fp.__new__ fp.closed fp.newlines fp.softspace fp.__delattr__ fp.__reduce__ fp.encoding fp.next fp.tell fp.__doc__ fp.__reduce_ex__ fp.fileno fp.read fp.truncate fp.__getattribute__ fp.__repr__ fp.flush fp.readinto fp.write fp.__hash__ fp.__setattr__ fp.isatty fp.readline fp.writelines fp.__init__ fp.__str__ fp.mode fp.readlines fp.xreadlines fp.__iter__ fp.close fp.name fp.seek >>> fp.read (press Tab again) fp.read fp.readinto fp.readline fp.readlines >>> help(fp.readline) (view the online help of this method) Help on built-in function readline: readline(...) readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. >>> fp.readline() (try using it) '127.0.0.1 localhost\n' >>>
4*33
1.0/3.0
--> 0.33333333333
(1+2j)*(3+4j)
--> (-5+10j)
x = 'abc'
x[1]
--> 'b'
x[1:3]
--> 'bc'
'abc' + 'def'
--> 'abcdef
'abc'*3
--> 'abcabcabc'
x = [1,2,3,4,5]
x[1]
--> 2
x[1:3]
--> [2,3]
x[3] = 3.5
x.append(6)
del x[1]
[0]*100
--> [0,0,0,0, ..., 0,0,0]
(100 elements)
[1,2] + [3,4]
--> [1,2,3,4]
range(10)
--> [0,1,2,3,4,5,6,7,8,9]
[ n*n for n in range(10) ]
--> [0,1,4,9,16,25,36,49,64,81]
[ n*n for n in range(10) if n%2 == 0]
--> [0,4,16,36,64]
x = {"a":1, "b":2}
x["a"]
--> 1
x["nosuchkey"]
--> Exception
x["newkey"] = 4
del x["newkey"]
myobj = MyClass()
(Unlike Java, there's no need of "new
" operator)
myobj.method(args)
print myobj
(Customizable print function)