CPython
Implementation of programming language PythonLinks:
Examples:
Hello, World!:
Example for versions Python 2.5.2print "Hello, World!"
Factorial:
Example for versions Python 2.5.2, Python 2.6.5This example uses recursive factorial definition.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
for n in range(16 + 1):
print "%d! = %d" % (n, factorial(n))
Fibonacci numbers:
Example for versions Python 2.5.2, Python 2.6.5This example uses recursive definition of Fibonacci numbers.
#! /usr/bin/env python
def fibonacci(n):
if n < 3:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
for n in range(1, 16 + 1):
print "%i," % fibonacci(n) ,
print "..."
Factorial:
Example for versions Python 2.5.2, Python 2.6.5This example uses iterative method of calculating factorials.
def factorial(n):
if n == 0:
return 1
f = 1
for i in range(1, n + 1):
f *= i
return f
for n in range(16 + 1):
print "%d! = %d" % (n, factorial(n))
Quadratic equation:
Example for versions Python 2.6.5import math
import sys
A = float(raw_input("A = "))
if A == 0:
print "Not a quadratic equation"
sys.exit()
B = float(raw_input("B = "))
C = float(raw_input("C = "))
D = B * B - 4 * A * C
if D == 0:
print "x =", -B / 2.0 / A
sys.exit()
if D > 0:
print "x1 =", (-B + math.sqrt(D)) / 2.0 / A
print "x2 =", (-B - math.sqrt(D)) / 2.0 / A
else:
print "x1 = (", -B / 2.0 / A, ",", math.sqrt(-D) / 2.0 / A, ")"
print "x2 = (", -B / 2.0 / A, ",", -math.sqrt(-D) / 2.0 / A, ")"
CamelCase:
Example for versions Python 2.6.5The program uses Python standard library functions translate
and title
.
title
counts all non-letters as word delimiters, so no need to change them to spaces before calling title
.
non_letters = ''.join(c for c in map(chr, range(256)) if not c.isalpha())
def camel_case(s):
return s.title().translate(None, non_letters)
print camel_case(raw_input())
Comments
]]>blog comments powered by Disqus
]]>