Python Overview
Features of Python
Syntax Rules
Control Structures
if condition:
instructions
elif condition: #*
instructions
else: # optional
instructions
while condition:
instructions
else: # optional
instructions
for var in S:
instructions
else: # optional
instructions
for i in range(n):
instructions
Built-in Data Structures
x = [1,2,3] x.append(4) print x[2] # result: 3
x = (1,2,3)
x = {}
x["word"] = reference
for k in x.keys():
print x[k]
Functions and Parameters
def function_name (par1, par2, ...):
body of the function
More Built-in Functions
if type(x) == type(0): ...
x = input()
return True
Example of Conditional
def check_type(x):
if type(x) == type(0):
print x, "is an integer"
elif type(x) == type(1.0):
print x, "is a float"
elif type(x) == type(""):
print x, "is a string"
elif type(x) == type([]):
print x, "is an array"
elif type(x) == type({}):
print x, "is a dictionary"
else:
print x, "is probably an object of a class"
Example of while/else
def Euler(a, b):
if b==0:
return a
r = a % b
while r:
a = b
b = r
r = a % b
else:
print "a divisible by b"
return b
return r
Booleans
x = 0 if not x: print "0 is False"
Default Values for Parameters
def function (var1 = value, var2 = value, ...):
def GCD1(a=10, b=20): ... GCD1() -> 10 GCD1(125) -> 5 GCD1(12, 39) -> 3
Variables and Scope
Example Scope
def test_scope():
for i in range(4):
for j in range (3):
x = i*10+j
if x>20:
print x,
print x
test_scope()
21 22 30 31 32 32
Try - Except
def scope1():
y = 15
y = 20
def scope2():
y = 25
def scope3():
try:
print y
except:
print "cannot access global y"
print days
y = 25
print y
days=["monday", "tuesday"]
More examples in the file examples1.py.