Tuesday, November 22, 2011

Sample example for python

#! python

print "Hello, Python"
a = 10
print a
fruits = ['banana', 'orange', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]

print "thanks"

##################################################

for letter in 'Is A Good Boy':
if letter == 'I':
pass
print "block passed"
print 'Current is :', letter

##################################################

var = 10
while var > 0:
print 'Current is value:', var
var -= 1
if var == 5:
break
###################################################

def printme (str):
"this function prints only this line"
print str
return

printme ("hello ji")

##################################################

# Fibonacci series:

a, b = 0, 1
while b < 200:
print b,
a, b = b, a+b

###################################################

# input and operator if

x = int(raw_input("Please enter an integer: "))

if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'

##################################################

# operator for:

a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)

###################################################

# range function

print range(10)

print range(5, 10)

print range(0, 10, 3)


a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print i, a[i]

###################################################


for n in range(2, 1000):
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell through without finding a factor
print n, 'is a prime number'

####################################################


# Dictionaries are sometimes as ``associative memories'' or ``associative arrays''

tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print tel

print tel['jack']

del tel['sape']
tel['irv'] = 4127
print tel

print tel.keys()

x=tel.has_key('guido')
print x

No comments:

Post a Comment