#!/usr/bin/env python # Number one thing to recognize: Python is a SPACE SENSITIVE language!!! # Also, Python is an interpreted language, so the line at the top of this # file is required. # Variables are dynamically typed. x = 20 y = 1009.34531 z = "another variable" # Strings like z are treated like strings of characters. # If statements are still if statements. if (z == 'another ' + 'variable'): print 'The two strings sure are the same!' elif x == 20: print 'Whoops, guess I was wrong there!' # Now let's create a list of random data types. # Note how the floating point value 22.22 is displayed. list = ['alpha', 100, ['a','b','c'],22.22] print '\nAnd the contents of the list:' print list[0] print list[1] print list[2] print list[3] print 'The last element of the list is:' , list[-1] print 'The first element of the list are:' , list[:1] print 'The last two elements of the list are:' , list[2:] # For statments are more like Perl For statements. print '\nAnd again, but this time with a For loop' for r in list: print r # While statements are still while statements. # Note the comma which allows for printing on the same line. This # tells the interpreter that you haven't finished with the current line. print 'Type the any key to continue.' p = 10 while p > 0: print p, p -= 1 # Can you believe functions are simple too? And how about some user input? # A function must be defined before use. def a_function_for_you(a): input = raw_input('Type something: ') print 'You typed: "',input,'"' print 'And the argument the function received was: ',a # Now we'll call the function a_function_for_you('Python couldn\'t be easier') # One more important thing, arguments in functions are passed by value, # not reference. def pass_by_reference(arg): print 'Inside function before:',arg arg = 99 print 'Inside function after:',arg num = 2 print 'Before:',num pass_by_reference(num) print 'After:',num # And finally, we come to classes, which are just as simple as functions. # Classes must also be defined before use. class NewClass: a = 99 # 'self' refers to the the class as a whole. This allows for accessing # other variables and functions from NewClass and defining new variables # that will be recognized throughout the class. # __init__ is the contructor function called upon initialization def __init__(self): self.data = [] def print_variables(self): print self.a,self.data def define_data(self, var): self.data.append(var) # Now we initialize the class and play with it. # Note, 'a' is not a private variable. Making variables "private" is # a little sketchy. object = NewClass() print object.a object.print_variables() object.define_data('blah') object.print_variables() # For more information on Python refer to tutorials on the net, there # are some exceptionally good ones.