Python Basics
Python Basics
Python Identifiers:
count(x)
sort()
reverse()
Python Tuples and Sequences
A tuple is another sequence data type that is similar to the
list. A tuple consists of a number of values separated by
commas. Unlike lists, however, tuples are enclosed
within parentheses
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple
print tuple[0]
print tuple[1:3]
print tuple[2:]
print tinytuple * 2
print tuple + tinytuple
The list methods make it very easy to use a list
as a stack, where the last element added is the
first element retrieved.To add an item to the top
of the stack, use append(). For eg.
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print stack
stack.pop()
print stack
add an item to the back of the queue, use
append(). To retrieve an item from the front of
the queue, use pop() with 0 as the index. For
example:
queue = ["Eric", "John", "Michael"]
queue.append("Terry") # Terry arrives
queue.append("Graham")
queue.pop(0)
queue.pop(0)
queue
There is a way to remove an item from a list
given its index instead of its value.
a = [-1, 1, 66.6, 333, 333, 1234.5]
del a[0]
a
del a[2:4]
a
del can also be used to delete entire variables:
del a
Dictionaries use keys to index values.
The keys does not have numeric values to
index the data item; it can be any immutable
data type such as strings,numbers,or tuples.
A python dictionary is an unordered set of
KEY:VALUE pair.
Key in a dictionary is unique.one key can be
associated with only a single value.
Each KEY:VALUE pair is separated by
comma(,).
Dictionaries is enclosed within curly braces({}).
For Example:
dict1={‘name’:’sun’,’ecode’:9062,’dept’:’maths’}
dict1[‘dept’] # maths
Not necessary for all keys in a dictionary to
enumerate() function
for i, v in enumerate([’tic’, ’tac’, ’toe’]):
print i, v
zip() function.
To loop over two or more sequences at the
same time, the entries can be paired with the
zip() function.for example
questions = [’name’, ’quest’, ’favorite color’]
answers = [’lancelot’, ’the holy grail’, ’blue’]
for q, a in zip(questions, answers):
print ’What is your %s? It is %s.’ % (q, a)
The comparison operators in and not in check
whether a value occurs (does not occur) in a
sequence.
import fibo
fibo.fib(1000)
fibo.fib2(1000)
Modules can import other modules. It is
customary but not required to place all import
statements at thebeginning of a module.
from fibo import fib, fib2
fib(500)
There is even a variant to import all names that
a module defines:
from fibo import *
fib(500)
Python comes with a library of standard
modules, described in a separate document, the
Python Library Reference.Some modules are
built into the interpreter.
One particular module deserves some
attention: sys, which is built into every Python
interpreter. The variables sys.ps1 and sys.ps2
define the strings used as primary and
secondary prompts:
import sys
sys.ps1
# ’>>> ’
sys.ps2
# ’... ’
The built-in function dir() is used to find out
which names a module defines. It returns a
sorted list of strings.
import fibo, sys
dir(fibo)
# o/p [’__name__’, ’fib’, ’fib2’]
dir(sys)
Without arguments, dir() lists the names you
have defined currently:
a = [1, 2, 3, 4, 5]
import fibo, sys
fib = fibo.fib
dir()
// o/p [’__name__’, ’a’, ’fib’, ’fibo’, ’sys’]
import __builtin__
dir(__builtin__)
Packages are a way of structuring Python’s
module namespace by using “dotted module
names”. For example,
the module name A.B designates a submodule
named ‘B’ in a package named ‘A’.
When importing the package, Python searches
through the directories on sys.path looking for
the package subdirectory.
Users of the package can import individual
modules from the package, for example:
import Sound.Effects.echo
Python has ways to convert any value to a
string: pass it to the repr() or str() functions.
s = ’Hello, world.’
str(s) # o/p ’Hello, world.’
repr(s) # o/p "’Hello, world.’”
str(0.1)#o/p ’0.1’
repr(0.1) #o/p ’0.10000000000000001’
open() returns a file object, and is most
commonly used with two arguments:
‘open(filename, mode)’.
f=open(’/python27/test1’, ’w’)
print f
# o/p<open file ’/tmp/workfile’, mode ’w’ at
80a0960>
To read a file’s contents, call f.read(size),
which reads some quantity of data and returns
it as a string.for example
f=open(’/python27/test1.txt’, ’r’)
f.read()
f.readline() reads a single line from the file; a
newline character (\n) is left at the end of the
string. for example
f=open(’/python27/test1.txt’, ’r’)
f.readline()
f.readlines() returns a list containing all the
lines of data in the file.
f.write(string) writes the contents of string to
the file, returning None.
f.tell() returns an integer giving the file
object’s current position in the file, measured
in bytes from the beginning of the file.
call f.close() to close file and free up any
system resources taken up by the openfile.
There are (at least) two distinguishable kinds of
errors: syntax errors and exceptions.
Syntax Errors
The parser repeats the offending line and displays
a little ‘arrow’ pointing at the earliest point in the
line where the error was detected.for eg:
while True print ’Hello world’
File "<stdin>", line 1, in ?
while True print ’Hello world’
^
Even if a statement or expression is syntactically
correct, it may cause an error when an attempt is
made to execute it. Errors detected during execution
are called exceptions
>>> 10 * (1/0)
ZeroDivisionError
>>> 4 + spam*3
NameError
>>> ’2’ + 2
TypeError
while True:
try:
x = int(raw_input("Please enter a number:
"))
break
except ValueError:
print "Oops! That was no valid number.
Try again..."
The raise statement allows the programmer to
force a specified exception to occur. For example:
>>> try:
x = MyClass()
creates a new instance of the class and assigns
this object to the local variable x.