You are on page 1of 3

#!/usr/bin/python3 : This is shebang line and it’s purpose it to indicate python interpreter path.

This
is mostly used in unix based environment. Mac also need this.

To print : print(“Hello”)

Conditional

a, b = 0, 1 see how variables’ are declared and assigned

if a < b: see if else structure, all code indented becomes part of the if or else

print('a ({}) is less than b ({})'.format(a, b)) see here {} will be replaced by a and b

else:

print('a ({}) is not less than b ({})'.format(a, b))

Ternary operator

print("foo" if a< b else "bar") it will print foo

While loop

a, b = 0, 1

while b < 50:

print(b)

b=b+1

For loop

# read the lines from the file

fh = open('lines.txt')

for line in fh.readlines():

print(line)

Define function

def isprime(n):

if n == 1:
print("1 is special")

return False

for x in range(2, n):

if n % x == 0:

print("{} equals {} x {}".format(n, x, n // x))

return False

else:

print(n, "is a prime number")

return True

for n in range(1, 20):

isprime(n)

Generator function

def isprime(n):

if n == 1:

return False

for x in range(2, n):

if n % x == 0:

return False

else:

return True

def primes(n = 1):

while(True):

if isprime(n): yield n //return n


n += 1

for n in primes():

if n > 100: break

print(n)

Object and classes

# simple fibonacci series

# the sum of two elements defines the next set

class Fibonacci():

def __init__(self, a, b): #__init__ is constructor, self is like this

self.a = a

self.b = b

def series(self):

while(True):

yield(self.b)

self.a, self.b = self.b, self.a + self.b

f = Fibonacci(0, 1)

for r in f.series():

if r > 100: break

print(r, end=' ')

You might also like