# for comments
variables. easy.
concatenating strings a bit more troublesome.
eg.:
i = 1.23
s = "hello"
a = s + i
will give error
have to convert to string
a = s + str(i)
b = True
b = not b #store False. same as b = !b
if-else conditions
while loop still ok. but must get used to the : at the back
eg.:
for loop v different.
functions
eg.:
classes and objects
modules
save into separate .py files
and then import
using import hello (if module is hello.py)
or use from hello import *
variables. easy.
concatenating strings a bit more troublesome.
eg.:
i = 1.23
s = "hello"
a = s + i
will give error
have to convert to string
a = s + str(i)
b = True
b = not b #store False. same as b = !b
if-else conditions
>>> if x < 0: ... x = 0 ... print 'Negative changed to zero' ... elif x == 0: ... print 'Zero' ... elif x == 1: ... print 'Single' ... else: ... print 'More' ...
while loop still ok. but must get used to the : at the back
eg.:
i = 0 while i<= 10: # : is equivalent of starting a curly brace { print i # identation used to indicate within while loop i = i + 1 # what happened to ++, --?!
for loop v different.
>>> # Measure some strings: ... a = ['cat', 'window', 'defenestrate'] >>> for x in a: ... print x, len(x)
OR
for i in range(10): print i # print 0, 1, 2,..., 9
functions
eg.:
def functionName(): print "running in function"
classes and objects
class MyClass: property = 1 # static variable
self.myVar = "hello" # instance variable def __init__(self, p): # contructor, self = this self.property = p def method1(self): # note the need for self, even with no arguments/parameters print "running method"
@staticmethod def staticMethod2(args, arg2): print "call me by classname, eg.: MyClass.staticMethod2(1,2)" x = MyClass() # instantiate print x.property x.method1() class DerivedClass(MyClass): # inheritance newProperty = 2 class SubSubClass(Class1, Class2, Class3): # multiple inheritance supported # fields & methods
modules
save into separate .py files
and then import
using import hello (if module is hello.py)
or use from hello import *
No comments:
Post a Comment