The Basics: Python Synatx, Indentation, Comments, etc ...

Variables

  • Python has similar syntax to C/C++/Java so it uses the same convention for naming variables: variable names can contain upper and lower case character & numbers, including the underscore (_) character.
  • Variable names are case sensitive
  • Variable names can't start with numbers or special characters (except for the undescore character)
  • Variables cannot have the same names as Python keywords
Keywords
and assert as break class continue def del
elif else except exec finally for from global
if import in is lambda not or pass
print raise return try while with yield

In [3]:
# this is a correct variable name
variable_name = 10

In [4]:
# this is not a correct variable name - variable names can't start with a number
4tops = 5


  File "<ipython-input-4-fb63971d7854>", line 2
    4tops = 5
        ^
SyntaxError: invalid syntax

In [6]:
# these variables are not the same
distance = 10
Distance = 20
disTance = 30

print "distance = ", distance
print "Distance = ", Distance
print "disTance = ", disTance


distance =  10
Distance =  20
disTance =  30

Indentation and Code Blocks


In [7]:
x = 11

if x == 10:
    print 'x = 10'
else:
    print 'x != 10'
    print 'Done'

print "Bye now"


x != 10
Done
Bye now

Statements/Multiline statements

A new line signals the end of a statement


In [ ]:
# these are two separate statements
a = 4
b = 6

For multi-line statements, use the \ character at the end of the line


In [10]:
# use line continuation symbol (use with care)
a = 10 \
    + \
    10 + 10
print a


30

or put the multilines in ()


In [14]:
# use prenthesis (preferable way)
a = (10
    +            20 +    
    10 + 10)
print a


50

Comments

Comments begin after the # character which can appear anywhere on the line. Multiline comments begin and end with 3 matching ' or " characters.


In [15]:
# this is a line comment
a = 10 # this is also a line comment
'''
this is indsie a multi-line comment
so is this
and this
'''
a = 100 # this is outside the multi-line comment

"""
This is another way to declare a multi-line comment
Inside it
inside it too
"""

a = 100 # this is outside the multi-line comment

You can put a comment inside a muliline statement


In [1]:
# multiline statement with comments
a = (10 # this is line 1
    +            20 +    # this is line 2
    10 + 10)
print a


50