Python Quick Notes :: Part - 1
Bhaskar S | 02/09/2013 |
Overview
Python is a modern general purpose programming language with the following characteristics:
Cross Platform
Scripting Language
Interpreted
Dynamic Typed
Modular
Object Oriented
Automatic Garbage Collection
Setup
Download and install the following software:
Python Programming Language (www.python.org)
Ninja IDE (www.ninja-ide.org)
Hands-on With Python - I
Best way to learn any language is to get our hands dirty. So without much further ado lets get started.
Basic built-in scalar data types supported by Python:
bool - True or False
int - Signed Numbers (Unlimited Size)
float - Floating Point Numbers (Unlimited Size)
complex - A complex number has a real part and an imaginary part. For example, (3 + 5j) is a complex number where 3 is the real part and 5 is the imaginary part. The real part can be accessed as g.real and the imaginary part can be accessed as g.imag
str - An immutable string of characters
Basic built-in functions (for basic data types) supported by Python:
abs(n) - Return the absolute positive value of the number n
chr(n) - Convert the integer n to an ascii character
eval(s) - Evaluate the string expression s
len(a) - Return the number of elements (length) in the object a
max(a, b, ...) - Return the largest of the specified objects a, b, ...
min(a, b, ...) - Return the smallest of the specified objects a, b, ...
type(a) - Return the type of the object a
round(n) - Round the specified number n to the closest multiple of 10
raw_input(s) - Display the string s and prompt the user for input which is returned as a string
input(s) - Display the string s and prompt the user for input which then returns the evaluated value of the user input. Think of it as an equivalent of eval(input(s))
Some of the special built-in operators (for numbers and strings) supported by Python:
** - Is the exponential operator and can be applied to numbers. For example, 10 ** 2 will result in 100 (10 to the power of 2)
[n] - Where n is a signed integer, is the index operator and can be applied to strings. The string index starts at 0 which points to the first character of the string. A negative index of -1 points to the last character of the string
[m:n] - Where m, n are signed integers, m is the start index, n is the end index is the slice operator and can be applied to strings
+ - On strings, it performs concatenation
* - Followed by an integer on string, it performs repeated concatenation of the same string the specifed number of times. For example, "Python" * 3, will result in the string PythonPythonPython
% - On strings, it performs formatting
The following is our first python program named sample-01.py:
NOTE :: Python program files have the extension ".py"
Execute the following command:
python sample-01.py
The following is the output:
a = True b = 65 c = -725 d = 1234567891 e = 2.5 f = 987654321.75 g = (3+4j) g (real) = 3.0 g (imag) = 4.0 h = This is a String i = False j = 885 k = 23500.0 l (before) = 25 m (before) = 50 l (after) = 50 m (after) = 25 n = 75 o = 1234567888.5 p = (7.5+10j) q = -1702853 r = 493827156.4 s = 11 t = 7888609052210118054117285652827862296732064351090230047702789306640625 abs(c) = 725 chr(b) = A eval('l+m') = 75 len(h) = 16 max(1, 2, 3, 4, 5) = 5 min(-1, -2, -3, -4, -5) = -5 round(f/e) = 395061729.0 Type of a: <type 'bool'> Type of d: <type 'int'> Type of e: <type 'float'> Type of g: <type 'complex'> Type of h: <type 'str'> Enter some text: Python Enter some number: 1275 len(text) = 6 text[0] = P text[-1] = n text[1:5] = ytho text[2:] = thon text[:3] = Pyt u = hello python v = pythonpythonpython String h = 'This is a String' and integer b = 65
Built-in string methods supported by Python:
capitalize() - Returns the string after capitalizing the first letter in the string
endswith(s) - Returns True if the string ends with the specified string s. Else returns False
find(s) - Returns the index in the string where the specified string s occurs starting from front. Else returns -1
lower() - Returns the string after converting all letters to lowercase in the string
lstrip() - Returns the string after removing all the leading whitespaces
replace(s1, s2) - Returns the string after replacing the occurence of the specified string s1 with s2
rfind(s) - Returns the index in the string where the specified string s occurs starting from back. Else returns -1
rstrip() - Returns the string after removing all the trailing whitespaces
startswith(s) - Returns True if the string starts with the specified string s. Else returns False
strip() - Returns the string after removing both the leading and trailing whitespaces
title() - Returns the string after capitalizing the first letter of each of the words in the string
upper() - Returns the string after converting all letters to uppercase in the string
The following is the python program named sample-02.py:
Execute the following command:
python sample-02.py
The following is the output:
str1 = 'welcome to python', str2 = ' Hello Python ' str1.capitalize() = Welcome to python str1.title() = Welcome To Python str1.startswith('welcome') = True str2.startswith('welcome') = False str1.endswith('python') = True str2.endswith('python') = False str1.find('P') = -1 str2.find('P') = 9 str1.rfind('o') = 15 str2.rfind('c') = -1 str2.lstrip() = 'Hello Python ' str2.rstrip() = ' Hello Python' str2.strip() = 'Hello Python' str2.lower() = ' hello python ' str1.upper() = 'WELCOME TO PYTHON' str2.replace('Hello', 'COOL') = ' COOL Python '
Simple control flow structures supported by Python:
if-elif-else - Execute the block of code for the first condition that evaluates to True in list of if or elif statements. If none of the condition evaluate to True, then execute the block of code under else
while - Execute the block of code as long as the conditon is True
for - Execute the block of code for each element in the sequence
NOTE :: The logical operators in Python are and, or, not
The following is the python program named sample-03.py:
Execute the following command:
python sample-03.py
The following is the output:
Enter some text: Hello Python Text length: 12 Enter number between 1 to 10: 7 Number = 7 Not less than 5 Either is greater than 5 counter (while): 0 counter (while): 1 counter (while): 2 counter (while): 3 counter (while): 4 counter (while): 5 counter (while): 6 counter (for): 0 counter (for): 1 counter (for): 2 counter (for): 3 counter (for): 4 counter (for): 5 counter (for): 6 t ( 0 ) = H t ( 1 ) = e t ( 2 ) = l t ( 3 ) = l t ( 4 ) = o t ( 5 ) = t ( 6 ) = P t ( 7 ) = y t ( 8 ) = t t ( 9 ) = h t ( 10 ) = o t ( 11 ) = n
Complex built-in data types supported by Python:
list - A list is a mutable sequence of comma separated values between square brackets []
tuple - A tuple is an immutable sequence of comma separated values between parentheses ()
dict - A dictionary is a mutable sequence of comma separated key:value (key is separated from value by a colon) pairs between curly braces {}
Basic built-in functions (for complex data types) supported by Python:
cmp(a, b) - Compares the items in the lists (or tuples or dicts) a and b. If a > b, return 1. If a = b, return 0. If a < b, return -1
len(a) - Return the number of items (length) in the list (or tuple or dict) a
max(a) - Return the largest item in the list (or tuple) a. Does not apply to dict
min(a) - Return the smallest item in the list (or tuple) a. Does not apply to dict
type(a) - Return the type of the object a
list(t) - Converts the specified tuple t to a list. Does not apply to dict
tuple(l) - Converts the specified list l to a tuple. Does not apply to dict
Some of the special built-in operators (for lists and tuples) supported by Python:
[n] - Where n is a signed integer, is the index operator and can be applied to lists and tuples. The index starts at 0 which points to the first item in the list or tuple. A negative index of -1 points to the last item in the list or tuple
[m:n] - Where m, n are signed integers, m is the start index, n is the end index is the slice operator and can be applied to lists or tuples
+ - On lists or tuples, it performs concatenation
* - Followed by an integer on list or tuple, it performs repeated concatenation of the same list or tuple the specifed number of times. For example, [1, 2, 3] * 3, will result in the list [1, 2, 3, 1, 2, 3, 1, 2, 3]
in - On lists and tuples, it checks if an item belows in the specified list or tuple. For example, 3 in [1, 2, 3] return True. It can also be used for iterating over a list or tuple in a for loop. For example: for a in (1, 2, 3): print a will print each of the items 1, 2, and 3 respectively
Built-in list methods supported by Python:
append(a) - Appends the specified object a to the end of the list
count(a) - Returns the count of how many times the specified object a appears in the list
extend(x) - Appends the items from the specified list (or tuple) x to the end of the list
index(a) - Returns the index in the list where the specified object a occurs starting from front
insert(n, a) - Inserts the object a into the list at the specified index n
pop() - Removes and returns the last item from the list
pop(n) - Removes and returns the item at the specified index n from the list
remove(a) - Removes the specified object a from the list
reverse() - Reverses the items in the list
sort() - Arranges the items in the list in a sorted order
The following is the python program named sample-04.py:
Execute the following command:
python sample-04.py
The following is the output:
type(list) = <type 'list'> list = [9, 1, 8, 2, 7, 3, 5, 4] len(list) = 8 max(list) = 9 min(list) = 1 list[0] = 9 list[1:3] = [1, 8] list[2:] = [8, 2, 7, 3, 5, 4] list[:3] = [9, 1, 8] list (before) = [9, 1, 8, 2, 7, 3, 5, 4] list (after) = [9, 0, 8, 1, 7, 2, 5, 3] list2 = [1, 2.5, 'Python'] [1, 2, 3] * 3 = [1, 2, 3, 1, 2, 3, 1, 2, 3] list3 = [1, 2.5, 'Python', 'A', -3, (3+5j)] -3 in list3 = True 5 in list3 = False list2: x = 1 list2: x = 2.5 list2: x = Python list2 = [1, 2.5, 'Python', 0.02] list2 = [1, 2.5, 'Python', 0.02, 9, 0, 8, 1, 7, 2, 5, 3] list2.count(1) = 2 list2.index(9) = 4 list2 (after insert) = [1, 2.5, 'Python', 0.02, 9, 100, 0, 8, 1, 7, 2, 5, 3] list2 (after pop) = [1, 2.5, 'Python', 0.02, 9, 100, 0, 8, 1, 7, 2, 5] list2 (after pop 3) = [1, 2.5, 'Python', 9, 100, 0, 8, 1, 7, 2, 5] list3 (after remove 3+5j) = [1, 2.5, 'Python', 'A', -3] list2 (after reverse) = [5, 2, 7, 1, 8, 0, 100, 9, 'Python', 2.5, 1] list (after sort) = [0, 1, 2, 3, 5, 7, 8, 9]
Built-in tuple methods supported by Python:
count(a) - Returns the count of how many times the specified object a appears in the tuple
index(a) - Returns the index in the tuple where the specified object a occurs starting from front
The following is the python program named sample-05.py:
Execute the following command:
python sample-05.py
The following is the output:
type(tuple) = <type 'tuple'> tuple = (9, 1, 8, 2, 7, 3, 5, 4) len(tuple) = 8 max(tuple) = 9 min(tuple) = 1 tuple[0] = 9 tuple[1:3] = (1, 8) tuple[2:] = (8, 2, 7, 3, 5, 4) tuple[:3] = (9, 1, 8) tuple2 = (1, 2.5, 'Python') (1, 2, 3) * 3 = (1, 2, 3, 1, 2, 3, 1, 2, 3) tuple3 = (1, 2.5, 'Python', 'A', -3, (3+5j)) -3 in tuple3 = True 5 in tuple3 = False tuple2: x = 1 tuple2: x = 2.5 tuple2: x = Python tuple2.count(1) = 1 tuple2.index(2.5) = 1
Some of the special built-in operators (for dict) supported by Python:
[k] - Get or set the value associated with the specified key k
Built-in dict methods supported by Python:
clear() - Removes all the key:value pairs from the dict
get(k) - Returns the value associated with the specified key k
get(k, a) - Returns the value associated with the specified key k. If the specified key k is not found, returns the specified default value a
has_key(k) - Returns True if the specified key k is found. Else returns False
items() - Returns a list of all the key:value pairs as (key, value) tuples
keys() - Returns the list of all the keys from the dict
values() - Returns the list of all the values from the dict
The following is the python program named sample-06.py:
Execute the following command:
python sample-06.py
The following is the output:
type(dict) = <type 'dict'> dict = {'a': 5, 'c': 15, 'b': 10, 'd': 20} len(dict) = 4 dict['b'] = 10 dict['b'] (after update) = 25 List of keys = ['a', 'c', 'b', 'd'] List of values = [5, 15, 25, 20] dict.get('c') = 15 dict.get('x', -1) = -1 dict.has_key('c') = True dict.has_key('x') = False List of (key, value) tuples = [('a', 5), ('c', 15), ('b', 25), ('d', 20)] dict (after clear) = {}