Python Examples
Comments and Printing
# Comments
'''
this is a comment block
'''
# Echo
print( "hello world" )
Variables and Lists
# Variables
a = 20
b = "40"
# Strings
s = "Strings "
print( s.count('s') ) # 1
print( s.find('i') ) # 3
print( s.lower() ) # strings
print( s.upper() ) # STRINGS
print( s.replace('s', '') ) # String
print( s.strip() ) # Strings
print( s[1:3] ) # tr
print( s[:-3] ) # Strin
print( 'this is a formatted string %.2f' % 123.234 ) # this is a formatted string 123.23
s += "concat"
print( "this is {}".format(12)) # this is 12
# Lists
l = [1, 2, 3, 4, 5]
print( l )
print( l[3] )
for a in l:
print( a )
for idx, val in enumerate(l):
print(idx, val)
l.append('x')
print( l )
l.count(2)
print( l )
l.count('2')
print( l )
l.index('x')
print( l )
l.insert(1, 'z')
print( l )
l.remove('x')
print( l )
l.pop()
print( l )
l.reverse()
print( l )
l.sort()
print( l )
# map a function and built a new list
l = map(l, lambda x: x + 1)
# Tuples
t = (1, 2, 3)
l = list(t)
l.append(4)
t = tuple(l)
print( t )
# Dictionaries
d = {'a': 1, 'b': 2, 'c': 3}
print( d )
d['d'] = 4
print( d )
for a in d:
print( a, d[a] )
Conditionals
if a < 15:
print( "if" )
elif a > 15 and a < 20:
print( "elif" )
else:
print( "else" )
# For loop
for a in range( 10, 30 ):
print( a )
# While loop
a = 1
while a < 10:
print(a)
a += 1
Functions and Classes
# Functions
def someFunction( a, b ):
print(a + b)
someFunction(10, 20)
# Classes
class Calculator(object):
def __init__(self):
self.current = 0
def add(self, amount):
self.current += amount
def get_current(self):
return self.current
@staticmethod
def get_pi():
return 3.14
c = Calculator()
c.add(3)
c.add(2)
print( c.getCurrent() )
print( Calculator.get_pi() )
# Lambda
def run(func):
return func(5)
ten = run(lambda x: x * 2)
Exceptions and Errors
# Exceptions
a = 1
try:
a = a + '2'
except:
print( a, "is not a number" )
System and File
# Files
f = open( "test.txt", "w+" )
f.write( "hello\n" )
f.close()
f = open( "test.txt", "a" )
f.write( "there" )
f.close()
f = open( "test.txt", "r" )
print( f.read(1) )
print( f.readline() )
print( f.read() )
f.close()
# System
from subprocess import call
r = call(["echo", "123"])
print( r )