0% found this document useful (0 votes)
3 views20 pages

Python Tutorial

Uploaded by

ISURU SANJEEWA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

Python Tutorial

Uploaded by

ISURU SANJEEWA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

History of Python

Python is a fairly old language created by Guido Van Rossum. The design began in the late
1980s and was first released in February 1991.
Why Python was created?
In late 1980s, Guido Van Rossum was working on the Amoeba distributed operating system
group. He wanted to use an interpreted language like ABC (ABC has simple easy-to-
understand syntax) that could access the Amoeba system calls. So, he decided to create a
language that was extensible. This led to design of a new language which was later named
Python.

First Python Program

>>> print "Hello, Python!"

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 naming conventions for Python identifiers −
 Class names start with an uppercase letter. All other identifiers start with a lowercase
letter.
 Starting an identifier with a single leading underscore indicates that the identifier is
private.
 Starting an identifier with two leading underscores indicates a strongly private
identifier.
 If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.

1
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use
them as constant or variable or any other identifier names. All the Python keywords contain
lowercase letters only.

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 are 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."""

Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the #
and up to the end of the physical line are part of the comment and the Python interpreter
ignores them.

# First comment
print "Hello, Python!" # second comment

2
Waiting for the User
The following line of the program displays the prompt, the statement saying “Press the enter
key to exit”, and waits for the user to take action −

raw_input("\n\nPress the enter key to exit.")

Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user
presses the key, the program ends. This is a nice trick to keep a console window open until
the user is done with an application.

Variables
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.
Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable. For example −

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

print counter
print miles
print name

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example −

a=b=c=1

Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables. For
example −

3
a,b,c = 1,2,"john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.

Standard Data Types


The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.
Python has five standard data types −
 Numbers
 String
 List
 Tuple
 Dictionary

Numbers
Number data types store numeric values. Number objects are created when you assign a value
to them. For example −

var1 = 1
var2 = 10

Python supports four different numerical types −


 int (signed integers)
 long (long integers, they can also be represented in octal and hexadecimal)
 float (floating point real values)
 complex (complex numbers)

Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be
taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at the end.

4
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example −

str = 'Hello World!'


print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string

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 ([]). To some extent, lists are similar to
arrays in C. One difference between them is that all the items belonging to a list can be of
different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is
the list concatenation operator, and the asterisk (*) is the repetition operator. For example −

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

5
Python Tuples
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.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists. For example −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print tuple # Prints complete list


print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists

Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]). For example −

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

6
Python Operators
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operator
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators

Python Arithmetic Operators c=a*b


print "Line 3 - Value of c is ", c

c=a/b
print "Line 4 - Value of c is ", c

c=a%b
print "Line 5 - Value of c is ", c

a=2
b=3
c = a**b
a = 21
print "Line 6 - Value of c is ", c
b = 10
c=0
a = 10
b=5
c=a+b
c = a//b
print "Line 1 - Value of c is ", c
print "Line 7 - Value of c is ", c
c=a-b
print "Line 2 - Value of c is ", c

7
Python Comparison Operators

print "Line 3 - a is equal to b"

if ( a < b ):
print "Line 4 - a is less than b"
else:
print "Line 4 - a is not less than b"

if ( a > b ):
print "Line 5 - a is greater than b"
else:
print "Line 5 - a is not greater than b"
a = 21
b = 10
a = 5;
c=0
b = 20;
if ( a <= b ):
if ( a == b ):
print "Line 6 - a is either less than or equal to
print "Line 1 - a is equal to b" b"
else: else:
print "Line 1 - a is not equal to b" print "Line 6 - a is neither less than nor equal
to b"

if ( a != b ):
print "Line 2 - a is not equal to b" if ( b >= a ):
print "Line 7 - b is either greater than or
else:
equal to b"
print "Line 2 - a is equal to b"
else:
print "Line 7 - b is neither greater than nor
if ( a <> b ): equal to b"
print "Line 3 - a is not equal to b"
else:

8
IF ELSE Statement
An else statement can be combined with an if statement. An else statement contains the block
of code that executes if the conditional expression in the if statement resolves to 0 or a
FALSE value.
The else statement is an optional statement and there could be at most only one else statement
following if.
Syntax
The syntax of the if...else statement is −

if expression:
statement(s)
else:
statement(s)

ex:
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1

var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2

print "Good bye!"

9
The elif Statement
The elif statement allows you to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be
at most one statement, there can be an arbitrary number of elif statements following an if.
syntax

if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

Core Python does not provide switch or case statements as in other languages, but we can use
if..elif...statements to simulate switch case as follows −
Example
var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var

print "Good bye!"

10
Loops
A loop statement allows us to execute a statement or group of statements multiple times.
1) While Loop

A while loop statement in Python programming language repeatedly executes a target


statement as long as a given condition is true.
Syntax
The syntax of a while loop in Python programming language is −

while expression:
statement(s)

Example

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"

The Infinite Loop


A loop becomes infinite loop if a condition never becomes FALSE. You must use caution
when using while loops because of the possibility that this condition never resolves to a
FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
print "Good bye!"

Above example goes in an infinite loop and you need to use CTRL+C to exit the program.

Using else Statement with Loops


Python supports to have an else statement associated with a loop statement.
 If the else statement is used with a for loop, the else statement is executed when the
loop has exhausted iterating the list.

11
 If the else statement is used with a while loop, the else statement is executed when the
condition becomes false.

count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"

2) For Loop

It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax

for iterating_var in sequence:


statements(s)

Example

primes = [2, 3, 5, 7]
for prime in primes:
print(prime)

# Program to find the sum of all numbers stored in a list


numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)

The range() function


We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start,stop,step size). step size defaults
to 1 if not provided.

12
This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.

# Output: range(0, 10)


print(range(10))
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))
# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
# Output: [2, 5, 8, 11, 14, 17]
print(list(range(2, 20, 3)))

for loop with else


A for loop can have an optional else block as well. The else part is executed if the items in
the sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.

digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

"break" and "continue" statements


break is used to exit a for loop or a while loop, whereas continue is used to skip the current
block, and return to the "for" or "while" statement.

# Prints out 0,1,2,3,4


count = 0
while True:
print(count)
count += 1
if count >= 5:
break
# Prints out only odd numbers - 1,3,5,7,9

13
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)

# Prints out 0,1,2,3,4 and then it prints "count value reached 5"
count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %(count))

# Prints out 1,2,3,4


for i in range(1, 10):
if(i%5==0):
break
print(i)
else:
print("this is not printed because for loop is terminated because of break but not due to fail
in condition")

3) Nested Loops

Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

14
The syntax for a nested while loop statement in Python programming language is as follows –

while expression:
while expression:
statement(s)
statement(s)

Example

i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1
print "Good bye!"

Functions
A function is a block of organized, reusable code that is used to perform a single, related
action. Allowing us to order our code, make it more readable, reuse it and save some time.
Also functions are a key way to define interfaces so programmers can share their code.
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
 Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).

 Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.

 The statement return [expression] exits a function, optionally passing back an


expression to the caller. A return statement with no arguments is the same as return
None.

def functionname( parameters ):


"function_docstring"

15
function_suite
return [expression]

The following function takes a string as input parameter and prints it on standard screen.

def printme( str ):


"This prints a passed string into this function"
print str
return

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

Return None

def empty_return(x,y):
c=x+y
return
res = empty_return(4,5)
print(res)

Return value

def return_sum(x,y):
c=x+y
return c
res = return_sum(4,5)
print(res)

Calling a Function

def sum( arg1, arg2 ):

16
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total

Module
Simply, a module is a file consisting of Python code. A module can define functions, classes
and variables. A module can also include runnable code.
Get the System time Module

import time; # This is required to include time module.


localtime = time.asctime( time.localtime(time.time()) )
print "Local current time :", localtime

Calendar Module

import calendar
cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal

Calculator Program

def add(x, y):


"""This function adds two numbers"""
return x + y

def subtract(x, y):


"""This function subtracts two numbers"""
return x - y

def multiply(x, y):


"""This function multiplies two numbers"""
return x * y

17
def divide(x, y):
"""This function divides two numbers"""
return x / y

# take input from the user


print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4):")


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':


print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':


print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':


print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

Opening and Closing Files


Python provides basic functions and methods necessary to manipulate files by default. You
can do most of the file manipulation using a file object.
Before you can read or write a file, you have to open it using Python's built-
in open() function. This function creates a file object, which would be utilized to call other
support methods associated with it.

# Open a file
fo = open("foo.txt", "w")

The close() method of a file object flushes any unwritten information and closes the file
object, after which no more writing can be done.

# Open a file

18
fo = open("foo.txt", "w")
print "Name of the file: ", fo.name
# Close opend file
fo.close()

Reading and Writing Files


The file object provides a set of access methods to make our lives easier. We would see how
to use read() and write() methods to read and write files.
The write() Method
The write() method writes any string to an open file. It is important to note that Python strings
can have binary data and not just text.

# Open a file
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n");
# Close opend file
fo.close()

Different modes of opening a file

Modes Description

r Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.

r+ Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.

w Opens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.

w+ Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.

The read() Method


The read() method reads a string from an open file. It is important to note that Python strings
can have binary data. apart from text data.

19
Syntax

fileObject.read([count]);

Here, passed parameter is the number of bytes to be read from the opened file. This method
starts reading from the beginning of the file and if count is missing, then it tries to read as
much as possible, maybe until the end of file.

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()

Split Method
The method split() returns a list of all the words in the string, using str as the separator (splits
on all whitespace if left unspecified), optionally limiting the number of splits to num.

Split by whitespace
By default, split() takes whitespace as the delimiter.

alphabet = "a b c d e f g"


data = alphabet.split() #split string into a list
for temp in data:
print temp

Split + maxsplit
Split by first 2 whitespace only.

alphabet = "a b c d e f g"


data = alphabet.split(" ",2) #maxsplit
for temp in data:
print temp

20

You might also like