Python is an interpreted dynamically typed Language with very straightforward syntax. Python comes in two basic versions one in 2.x and 3.x and Python 2 and 3 are quite different. This post is bais for Python 2.x
In Python 2, the "print" is keyword. In Python 3 "print" is a function, and must be invoked with parentheses. There are no curly braces, no begin and end
keywords, no need for semicolons at the ends of lines - the only thing that
organizes code into blocks, functions, or classes is indentation
To mark a comment the line, use a pound sign, ‘#’. use a triple quoted string (use 3 single or 3 double quotes) for multiple lines.
Python Data Types
- int
- long
- float
- complex
- boolean
Python object types (builtin)
- list : Mutable sequence, in square brackets
- tuple : Immutable sequence, in parentheses
- dic : Dictionary with key, value using curly braces
- set : Collection of unique elements unordered
- str : Sequence of characters, immutable
- unicode : Sequence of Unicode encoded characters
Sequence indexes
- x[0] : First element of a sequence
- x[-1] : Last element of a sequence
- x[1:] : Second element from the last element
- x[:-1] : First element up to (but NOT including last element)
- x[:] : All elements - returns a copy of list
- x[1:3] : From Second elements to 3rd element
- x[0::2] : Start at first element, then every second element
1 seq = ['A','B','C','D','E']
2
3 print seq
4 print seq[0]
5 print seq[-1]
6 print seq[1:]
7 print seq[:-1]
8 print seq[:]
9 print seq[1:3]
10 print seq[0::2]
output of above code
Function and Parameters
Functions are defined with the “def” keyword and parenthesis after the function name
1 #defining a function
2 def my_function():
3 """ to do """
4 print "my function is called"
5
6 #calling a defined function
7 my_function()
Parameters can be passed in many ways
- Default parameters:
def foo(x=3, y=2):
print x
foo() - By position:
foo(1, 2) - By name:
foo(x=1)
- As a list:
def foo(*args):
print args
foo(1, 2, 3) - As a dictionary:
1 def foo(a, b=2, c= 3):
2 print a, b, c
3 d = {'a':5, 'b':6, 'c':7}
4
5 foo(**d)
6
7 #need to pass one parameter
8 foo(1)
[1] https://www.python.org/about/gettingstarted/
Add a comment