Tuesday, August 21, 2012

A day on Python - Basics

Why Python: Provide better inegration with other language.

How to start Python: login to command promp and type python

Basic Syntax: Require tabs or equal number of spaces to make block.
No Declaration required.

a=10
a =>10
print a => 10

a="Hello\n how are u"
a => "Hello\n how are u"
print a => Hello
                how r u
print type(a) => 'str'

a=2+3j
print a.real and print a.imag
operators: ==,!=,<>, bitwise operators, += ,...

a=10
a is 10 => true
a is not 10 => false

a='hello'
'h' in a => true
'H' in a => false

which python => path and name of interpreter.

Create Script:
vi Script.py
#! /user/bin/

import Script.py => This will execute all the command defined outsids the functions
To import function use: from script import function/variable/*

Using modules::
help()
modules =>List of all modules

To write command in multiple lines:
a='''line1
line2
line3'''
print a => line1
                line2
                line3

Type Casting:
a='458'
b = int(a)

a="Part1"
b="and Part2"
a+' '+b => Part1 and Part2
s= a*2
print s => Part1Part1

If Statement
if a>10:
(tab) print "true"
(tab) print "If done"
else:
(tab) print "Else Part"
(press ctrl+D) to terminate the command if using on prompt

a=[1,2,3]
for var in a
(tab/space) print var
for i in range(1,10)
(tab/space) print var


Using else with while
i=2
a=10
while i<a:
  if  a%i ==0
    print "Not Prime"
    break
 i+=1
else:
   print "Prime" => This else will only be executed when the condition of while is false, not when break is called.

Taking inputs:
1) Integer inputs:
a = input("Enter Value")
Enter Value 10
a => 10
2) String/Char input:
a=raw_input("Enter")
Enter 10
a => '10'

List of Char/String to String
a=['a','b']
s= ''.join(a)
print s =>'ab'
Split again to list
list(s) => ['a','b']
a="hello"
list(a) => ['h','e','l','l','o']
a="Hello how r u"
a.split(' ') => ['Hello', 'how', 'r', 'u']

Concatinate:
a=[1,2,3,4]
a+[10,20] => [1,2,3,4,10,20]

Sorting
a=[1,2,5,4,3]
a.sotr() => [1,2,3,4,5]
a.reverse()
a.pop() => Delete last element and return that element
a.pop(index) => Delete element at index
a.remove(3) => Will remove elemement 3 itself (not at index 3)
a.append([1,2,3]) =>will append [1,2,3] as list at last position
a.insert(0,10) => insert at 0th index

Call be Value and Reference
a=[1,2,3]
b=a => by reference
c=a[:] => by value

Dictionary::
dict={key1:'Value', key2:Value}
dict.has_key(key1) => True
dick.get(key1) => Value
del dick[Key1] => Will delete Key1
d.keys() => Return all Keys
d.values()
d.items()
d.iterkeys() => To iterate over keys

Tuple: Unmodifiable list
a= 1,2,3 or a=(1,2,3)

Using Functions
def functionName(n):
(tab/space) function body

Exception Handling
try:
     body
except ExceptionType,msg
     print msg

Using Modules:
Math: This module provides map, reduce and filter

No comments:

Post a Comment