def main(): print "Hello World" # Python does not have scope delemiters, it uses indents. # dec var f = 0; print f #re dec var f = "ABC"; print f #strongly typed language print "String type " + 123 #above line will error, will not convert int to str when run. #this will work print "String type " + str(123) #converts to string on run. #global vs local vars. def someFunction() global f #tell function this is a global var/effects the value globally f = "def" pring f #will return DEF someFunction() print f #will return 0 again del f #deletes the variable print f #will error, f is not defined due to del cmd (undefine in realtime) ## FUNCTIONS ## #colon denotes the scope of the function is starting, has to be indented def func1(): print "I am a function" func1() #runs the function above print func1() #runs the function -- but no return value, trying to print whatever return value was - will return python default none print func1 #print function 1 without invoke -- prints the value of the func1 object - not useful but see how python treats objects #function that takes arguments def func2(arg1,arg2): print arg1, " ",arg2 func2(10,20) def cube(x): return x*x*x print cube(3) #func with default value for argument def power(num, x=1): result = 1; for i in range(x): result = result * num return result print power(2) print power(2,3) #or to overide the default arg value 'x' print power(x=2,num=3) #args do not have to be in order if named #func with multipul arguments def multi_add(*args): result = 0; #local var for x in args: #loop arguments and add each time result = result + x return result #return to func call print multi_add(2,3,4) ## CONDITIONALS ## x, y = 1000, 100 if(x < y): st = "x is less than y" elif(x == y): #REMEMBER elif is else if st = "x and y is the same" else: st = "x is greater than y" print st #conditionals all on one line. #same as the if construct above but all on one line. st = "x is less than y" if (x < y) else "x is greater than or equal to y" print st ## LOOPS ## #Tell python that from datetime mod, you want to import the date time classes from datetime import date today = date.today() print "Today's daye is ", today #or print individual components. print "Today's Date is", today.day, today.month, today.year #retrive weekday number print "Today's weekday #:" , today.weekday() #datetime time = datetime.now() #creat current time class t = datetime.time(datetime.now())
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question