Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
203 views

Python Basics

Python identifiers refer to variables, functions, classes and other objects. An identifier starts with a letter or underscore, followed by letters, numbers or underscores. Python has various data types like numbers, strings, lists, tuples and dictionaries. Key programming constructs include conditionals, loops, functions and modules. Lists can be used as stacks and queues by adding/removing elements from the ends. Tuples are similar to lists but immutable. Dictionaries contain keys mapped to values.

Uploaded by

sundhar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
203 views

Python Basics

Python identifiers refer to variables, functions, classes and other objects. An identifier starts with a letter or underscore, followed by letters, numbers or underscores. Python has various data types like numbers, strings, lists, tuples and dictionaries. Key programming constructs include conditionals, loops, functions and modules. Lists can be used as stacks and queues by adding/removing elements from the ends. Tuples are similar to lists but immutable. Dictionaries contain keys mapped to values.

Uploaded by

sundhar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 65

Python Identifiers:

 A Python identifier is a name used to identify a


variable, function, class, module, or other
object. An identifier starts with a letter A to Z
or a to z or an underscore (_) followed by zero
or more letters, underscores, and digits (0 to
9).
 Python does not allow punctuation characters
such as @, $, and % within identifiers. Python
is a case sensitive programming language.
Thus Manpower and manpower are two
different identifiers in Python.
 Here are following identifier naming convention
for Python:
 Class names start with an uppercase letter and all
other identifiers with a lowercase letter.
 Starting an identifier with a single leading
underscore indicates by convention that the
identifier is meant to be private.
Reserved Words

 The following list shows the reserved words in


Python.Keywords contain lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Indentation

 when learning Python is the fact that there are no


braces to indicate blocks of code for class and
function definitions or flow control. Blocks of
code are denoted by line indentation.
Sample program
if True:
print "True“
else:
print "False“
Multi-Line Statements

 Statements in Python typically end with a new


line. Python does, however, allow the use of the
line continuation character (\) to denote that the
line should continue. For example:
 total = item_one + \ item_two + \ item_three
Statements contained within the [], {}, or ()
brackets do not need to use the line continuation
character. For example:
 days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation in Python

 Python accepts single ('), double (") and triple ('''


or """) quotes to denote string literals, as long as
the same type of quote starts and ends the string.
 The triple quotes can be used to span the string
across multiple lines. For example, all the
following are legal:
word = 'word' sentence = "This is a sentence."
paragraph = """This is a paragraph. It is made up
of multiple lines and sentences."""
Assigning Values

 The equal sign (=) is used to assign values to


variables.
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
Multiple Assignment
 You can also assign a single value to several
variables simultaneously. For example:
a=b=c=1
You can also assign multiple objects to multiple
variables. For example:
a,b,c=1,2,”John”
DATA TYPES
Python has five standard data types:
• Numbers
• String
• List
• Tuple
• Dictionary
Python supports four different numerical types:
• int (signed integers)
• long (long integers [can also be represented in octal
and hexadecimal])
• float (floating point real values)
• complex (complex numbers)
Python Strings
 The plus ( + ) sign is the string concatenation
operator, and the asterisk ( * ) is the repetition
operator.
str = 'Hello World!‘
print str
print str[2:5]
print str[2:]
print str * 2
print str + "TEST”
 Python language supports following type of
operators.
Arithmetic Operators
Comparision Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Lets have a look on all operators one by one.
The if statement

The syntax of the if statement is


if expression:
statement(s)
Example:
var1 = 100
if var1:
print "1 - Got a true expression value“
print var1 var2 = 0
if var2:
print "2 - Got a true expression value“
print var2 print "Good bye!"
The else Statement:
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value“
print var1
The elif Statement
The syntax of the if...elif statement is:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else: statement(s)
The while Loop
The syntax of the while loop is:
while expression:
statement(s)
Example:
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
The for Loop

 The for loop in Python has the ability to iterate over


the items of any sequence, such as a list or a string.
 The syntax of the loop look is:

for iterating_var in sequence:


statements(s)
EXAMPLE:
for letter in 'Python':
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print 'Current fruit :', fruit
The break Statement:
 The break statement in Python terminates the
current loop and resumes execution at the next
statement
for letter in 'Python':
if letter == 'h':
break
print 'Current Letter :', letter
 The continue statement in Python returns the
control to the beginning of the while loop. The
continue statement rejects all the remaining
statements in the current iteration of the loop
and moves the control back to the top of the
loop.
 The continue statement can be used in both
while and for loops.
for letter in 'Python':
if letter == 'h':
continue
print 'Current Letter :', letter
Defining a Function
 Function blocks begin with the keyword def
followed by the function name and parentheses
( ( ) ).
 The code block within every function starts with
a colon (:) and is indented.
 Syntax:
 def functionname( parameters ):
"function_docstring" function_suite return
[expression]
Example:
def printme( str ):
"This prints a passed string into this
function“
print str return
Calling a Function
 Defining a function only gives it a name,
specifies the parameters that are to be included
in the function, and structures the blocks of
code.
 Once the basic structure of a function is
finalized, you can execute it by calling it from
another function or directly from the Python
prompt.
 def printme( str ):
"This prints a passed string into this function“
print str; return; # Now you can call printme
printme("I'm first call to user defined function!");
printme("Again second call to the same
function");
 Python provides two built-in functions to read
a line of text from standard input, which by
default comes from the keyboard. These
functions are:
raw_input
input
 The raw_input([prompt]) function reads one line
from standard input and returns it as a string
(removing the trailing newline)

 str = raw_input("Enter your input: ");


print "Received input is : ", str
 The input([prompt]) function is equivalent to
raw_input, except that it assumes the input is a
valid Python expression and returns the evaluated
result to you:
Example:
str = input("Enter your input: ");
print "Received input is : ", str
Python Lists
 Lists are the most versatile of Python's compound
data types. A list contains items separated by
commas and enclosed within square brackets ([]).
 list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

tinylist = [123, 'john']


print list
print list[0]
print list[1:3]
print list[2:]
print tinylist * 2
print list + tinylist
More on Lists
 append(x)

Add an item to the end of the list;


 extend(L)

Extend the list by appending all the items in the


given list;
 insert(i, x)

Insert an item at a given position. The first


argument is the index of the element before
which to insert,so a.insert(0, x) inserts at the
front of the list
 remove(x)
Remove the first item from the list whose value
is x. It is an error if there is no such item.
 pop([i ])

Remove the item at the given position in the list,


and return it. If no index is specified, a.pop()
returns the last item in the list.
 index(x)

 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

belong to same data type.


dict2={‘2’:11571,2:’mca’,6.5:’07mca031’}
 the length of dictionary is number of key:pairs in
it.
len(dict2)
 iteritems() function
knights = {’gallahad’: ’the pure’, ’robin’: ’the
brave’}
for k, v in knights.iteritems():
print k, v

 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.

 The operators is and is not compare whether


two objects are really the same object; this
only matters for mutable objects like lists.
 Sequence objects may be compared to other
objects with the same sequence type.
(1, 2, 3) < (1, 2, 4)
[‘a’]<[‘A’]
(1, 2, 3) == (1.0, 2.0, 3.0)
 Python has a way to put definitions in a file and
use them in a script or in an interactive instance
of the interpreter. Such a file is called a module;
 definitions from a module can be imported into
other modules or into the main module
 import the module with the following command:

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:

raise NameError, ’HiThere’


except NameError:
print ’An exception flew by!’
raise
 Class Definition Syntax
The simplest form of class definition looks like
this:
class ClassName:
<statement-1>
.
.
.
<statement-N>
 Class objects support two kinds of operations:
attribute references and instantiation.
 Attribute references use the standard syntax used
for all attribute references in Python: obj.name.
class MyClass:
"A simple example class"
i = 12345
def f(self):
return ’hello world’
 then MyClass.i and MyClass.f are valid attribute
references, returning an integer and a method
object,respectively.
 Class instantiation uses function notation.

x = MyClass()
 creates a new instance of the class and assigns
this object to the local variable x.

You might also like