
#!/apps/perl/bin/perl
if (1)
{
print "Hello, World";
return(0);
}
else
{
print "2012 ...";
return(1);
}
Python uses spaces ...
#!/usr/bin/env python
if True:
print("Hello, World")
return 0
else:
print("2012")
return 1
Seeing that the case for python is recognising the spaces as it's code block, it is of utmost important that the the number or spaces(or tabs) has to be equal for all the codes which falls within the same block.....
#!/usr/bin/env python
if True:
print("Hello, World")
return 0
else:
print("2012") # Error, because indentation not align
return 1
Because of this, Here're some important points ...
#!/usr/bin/env python
print("Hello, World")
Running from terminal:-
%./hello.py
%python Python 2.5.1 (r251:54863, Jul 21 2007, 15:22:34) [GCC 3.4.3 20060612 with Mainsoft fixes] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 'Hello, world' >>> print(a) Hello, world >>>
%python >>> help(str) >>> a = 123 >>> help(a) ### Similar to help(int)
x = 1 y = 10 z = x + y print(z) # 11 y += 1 # y == 11
a = b = c = 5 d, e, f = 6, 7, 8
d > 3 # True d == 3 # False d < e < f # True d is 6 # True f is not 8 # False a is 5 and e is not 6 # True
s = 'Hello World!' print(s) # Prints complete string print(s[0]) # Prints first character of the string print(s[2:5]) # Prints characters starting from 3rd to 6th print(s[2:]) # Prints string starting from 3rd character print(s * 2) # Prints string two times print(s + "TEST") # Prints concatenated stringThere are 3 ways of quoting a string in python
a = 'Lionel is "handsome".'
a = "Lionel can't jump."
a = """Lionel is "handsome", but he can't jump.""" b = ''' Lionel likes PERL, but Python is cool too! '''A few of the string methods ...
a = 'Hello, World!'
a.isalpha() # False
a.isdigit() # False
a.find('o') # 4
a.split(',') # ['Hello', ' World!']
a.startswith('He') # True
For a full list of method...
%python %help(str)
a = ['liang', 25, '012-1234567', 123.64]
print(a[0]) # 'liang'
print(a[1:3]) # [25, '012-1234567']
a.append('haha')
print(a) # ['liang', 25, '012-1234567', 123.64, 'haha']
a.reverse()
print(a) # ['haha', 123.64, '012-1234567', 25, 'liang']
a.sort()
print(a) # [25, 123.64, '012-1234567', 'haha', 'liang']
For a full list of List object methods ==>
%python %help(list)
t = ('liang', 25, '012-1234567', 123.64)
### You can still access to elements of a tuple the same way
### you access thru a list
print(t[0]) # 'liang'
print(t[1:3]) # (25, '012-1234567')
a = list(t) # Copy tuple t to a list object ==> a
print(a) # ['liang', 25, '012-1234567', 123.64, 'haha']
a.reverse()
print(a) # ['haha', 123.64, '012-1234567', 25, 'liang']
a.sort()
print(a) # [25, 123.64, '012-1234567', 'haha', 'liang']
tt = tuple(a)
print(tt) # (25, 123.64, '012-1234567', 'haha', 'liang')
a = {'name':'lionel tan', 'age':25, 'phone':6325}
b = {'name':'yoke liang', 'age':25, 'phone':6315}
employee = {1:a, 2:b}
print(employee[1]['name']) # 'lionel tan'
employee[1]['age'] == employee[2]['age'] # True
a['sex'] = 'male'
print(employee[1]['sex']) # 'male'
alist = ['liang', '25', '012-1234567', '123.64']
for item in alist:
print(item)
### output ###
# 'liang'
# '25'
# '012-1234567'
# '123.64'
#-------------------------------------------------------
adict = {'name':'lionel tan', 'age':'25', 'phone':'6325'}
for key in adict:
print(key + ' - ' + adict[key])
### output ###
# 'name - lionel tan'
# 'age - 25'
# 'phone - 6325'
a = 5
if a < 4:
print("a < 4")
elif a < 10:
print("a < 10")
elif a < 15:
print("a < 15")
else:
print("ELSE")
### Answer: "a < 10"
animals = ['fish', 'cat', 'dog']
for x in animals:
print("This is a " + x)
### Answer:-
### This is a fish
### This is a cat
### This is a dog
stockprice = { 'ALTR':'$42', 'XLNX':'$12', 'INTC':'$15' }
# example #1
for sym in stockprice:
print( sym + " is currently " + stockprice[sym] )
# example #2
for sym,price in stockprice.items():
print( sym + " is curerntly " + price )
### Answer:-
### ALTR is currently $42
### XLNX is currently $12
### INTC is currently $15
a = 3 while a > 0: print(a) a -= 1 ### Answer:- ### 3 ### 2 ### 1
a = 10 while a > 0: print(a) if a == 8: break a = a - 1 ### Answer:- ### 10 ### 9 ### 8
a = 4 while a > 0: if a == 2: continue print(a) a = a - 1 ### Answer:- ### 4 ### 3 ### 1
a = 4
while a > 0:
if a == 2:
break
print(a)
a = a - 1
else:
print("-Loop Ends-")
print("code continue running ...")
### Answer:-
### 4
### 3
### code continue running
a = 4
while a > 0:
print(a)
a = a - 1
else:
print("-Loop Ends-")
print("code continue running ...")
### Answer:-
### 4
### 3
### 2
### 1
### -Loop Ends-
### code continue running
animalList = ["bear","bee","cat","fish","horse","llama"] newlist = [] for animal in animalList: if 'a' in animal: newlist.append(animal) ### newlist ==> ['bear', 'cat', 'llama']
animalList = ["bear","bee","cat","fish","horse","llama"] newlist = [ animal for animal in animalList if 'a' in animal ] ### newlist ==> ['bear', 'cat', 'llama']
animalList = ["bear","bee","cat","fish","horse","llama"] newlist = [ animal.upper() for animal in animalList if 'a' in animal ] ### newlist ==> ['BEAR', 'CAT', 'LLAMA']
def printMyName():
print("My name is Lionel")
def printMyAge():
print("Every year 25")
printMyName() # My name is Lionel
a = printMyName a() # My name is LionelFrom the above example, have you noticed something?
my = {'name':printMyName, 'age':printMyAge}
print("What's your name?")
my['name']()
print("How old are you?")
my['age']()
### Answer:-
### What's your name?
### My name is Lionel
### How old are you?
### Every year 25
def correct():
print("Awesome !!! Fantastic !!!")
def wrong():
print("Stupid ...")
answer = [wrong, correct]
x = 5
answer[ True if x is 5 else False ]()
### Awesome !!! Fantastic !!!
def printMyName(name):
print("My name is " + name)
printMyName("Rain!")
### My name is Rain!
def printMyData(name="Liang, age=25):
print("My name is " + name)
print("I am " + str(age) + " years old.")
printMyData(age=18)
### My name is Liang
### I am 18 years old.
printMyData("YeeChin", 31)
### My name is YeeChin
### I am 31 years old.
def myName():
return("Lionel")
def myData():
return( ['YeeChin', '25'] )
print( myName() )
### Lionel
[name, age] = myData()
print( name + " is " + age + " years old already lor ~~~")
### YeeChin is 25 years old already lor ~~~
filename = "./a.txt" fh = open(filename, 'r') for line in fh: print(line) fh.close()
filename = "./a.txt"
fh = open(filename, 'w')
fh.write("writing this first line into a file...")
fh.write("This is the 2nd line.")
fh.close()
Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables aren't used as frequently as instance variables are.
Data member: A class variable or instance variable that holds data associated with a class and its objects.
Function overloading: The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects (arguments) involved.
Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class.
Inheritance : The transfer of the characteristics of a class to other classes that are derived from it.
Instance: An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.
Instantiation : The creation of an instance of a class.
Method : A special kind of function that is defined in a class definition.
Object : A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods.
Operator overloading: The assignment of more than one function to a particular operator.
class People(): """ This is a documentation. A string that follows right after a block code is always a documentation. It is a good practice to document all your specs/algorithm/documentation here. """ def __init__(self, n, a): """ This is a constructor """ self.name = n self.age = a def getName(self): """ This is a method. A Method is just like a normal function. It's just another way of naming it ;) """ return(self.name) def setStatus(self, status): """ This is another method, which reads in 1 input parameter. """ self.status = status def getStatus(self): return(self.status) def getAge(self) return(self.age)
yltan = People("Lionel", 25)
The above action is call Instantiating a new instance of the class(People).def __init__(self, n, a): self.name = n self.age = a
kyleong = People("Eric", 38)
The class will create another new set of self.name and self.age instance variable,
def getAge(self) return(self.age) def getName(self) return(self.name)Since the created instance is always having a binding with the class, we can therefore
print( kyleong.getName() + " is " + str(kyleong.getAge()) + " years old .... already!" ) print( yltan.getName() + " is " + str(yltan.getAge()) + " years old .... only!" ) ### Eric is 38 years old .... already! ### Lionel is 25 years old .... only!