Quick, Non-Comprehensive Introduction to Python Syntax
Based on http://en.wikipedia.org/wiki/Python_syntax_and_semantics
Hello World As easy as they go
print('Hello World!')
Hello World!
As a Script
#!/usr/bin/env python
if __name__ == '__main__':
print('Hello World!')
Hello World!
List of Python Keywords
from keyword import kwlist
for keyword in kwlist:
print(keyword)
False None True and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield
Python uses whitespace to delimit program blocks
def isEven(number):
return number%2==0
for x in range(1,5):
#Loop starts here
if isEven(x):
print(x,'is even')
else:
print(x,'is odd')
print('This will be printed every iteration')
#Loop ends here
print('This will only be printed once')
1 is odd This will be printed every iteration 2 is even This will be printed every iteration 3 is odd This will be printed every iteration 4 is even This will be printed every iteration This will only be printed once
Data Structures
def a_function(an_argument):
#An inline comment
a_string = 'String'
# Raw strings are useful to avoid string formatting, I mainly use them for file paths
a_raw_string = r'C:\Foo\Bar'
an_integer = 2
a_float = 3.14
#Lists are your standard collections
a_list = [1,2,3,'Four']
#Access the list
a_list[0] # is 1
#Dictionaries are key-value stores
a_dictionary = {'Key' : 'Value',
'Perth' : 'Just Right',
'Melbourne' : 'Bad Weather',
'Sydney' : 'Too Busy'}
#Access the Dictionary
a_dictionary['Perth'] # is equal to 'Just Right'
#Tuples are like lists but are immutable, I personally don't use them very much
a_tuple = ('Perth', 'Melbourne', 'Sydney')
#Access a tuple
a_tuple[0] # == Perth
#Sets are unordered collections of unique elements, they are very useful for set operations!
a_set = {0, False, 'Perth'}
Functional Programming
#List comprehensions are one of the most useful features of python
#Creating complicated lists becomes easy!
X = [x for x in range(0,100) if x%3==0]
#Anonymous functions
double = lambda x: x + x
#map may be more readable than list comprehensions if you have already defined a function
#In Python 3 it returns an iterable rather than a list for efficiency
map(double, range(0,10))
for number in map(double, range(0,10)):
print(number)
0 2 4 6 8 10 12 14 16 18