Python

Introduction to Python Programming Language

Created by Ganesh Bhosale in Dwij IT Solutions
Dwij IT Solutions Logo

Your support

Like this Python tutorial, our tutorials are always open-source for learners. Like our facebook page to get more free tutorial updates.




Python

Python is a widely used general-purpose, high-level programming language that lets you work more quickly and integrate your systems more effectively.

Its design philosophy emphasises code readability, and its syntax allows programmers to express concepts in fewer lines of code

History of Python

Python was conceived in the late 1980’s and its implementation was started in December 1989 by Guido van Rossum in the Netherlands.


Guido van Rossum

Features of Python Language

  • Very clear, readable syntax
  • Object orientation
  • Natural expression of procedural code
  • Full modularity, supporting hierarchical packages
  • Exception-based error handling
  • Very high level dynamic data types
  • Extensive standard libraries and third party modules for virtually every task
  • Extensions and modules easily written in C, C++, Java

Core Philosophy

Python facts !!!

  • Open Source
  • Easy to Learn & excel.
  • No need of compilation of code.
  • Error handling in runtime.
  • Take very less time for up & running.
  • Object Oriented Programming + Procedural + Functional
  • Pre-installed with Linux, Unix & Mac OSX

Up & running with Python

Python Installation on Ubuntu

By default python comes pre-installed in Ubuntu distribution. Check simply by command:

python --version

Python Installation on Windows

  1. Donwload Python Installer from https://www.python.org/downloads/windows.
  2. Or use direct Donwload link for python-2.7.5
  3. If python get installed in C:\python27 directory, use command to set path:
    set path=%path%;C:\python27
  4. You will see Python (command line) in Windows Menu.
  5. Make sure it runs and opens Python Shell Window

Python Installation on Macintosh

The latest version of Mac OS X, Yosemite, comes with Python 2.7 out of the box. Check simply by command:

python --version

If not you can install it from https://www.python.org/downloads/mac-osx

Python Interpreter

Simply by putting command python in terminal you can start python interpretor for Ubuntu/Mac. For windows open Python (command line) from Windows Menu.

The interpreter’s line-editing features include interactive editing, history substitution and code completion on systems that support readline.

The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively.

Using Interpreter

Press to get command history.

When commands are read from a tty, the interpreter is said to be in interactive mode. In this mode it prompts for the next command with the secondary prompt which has three dots representation (...), instead of (>>>) which is primary prompt.

To exit interpreter:
Use Ctrl+D in Linux & Mac
Use Ctrl+Z and then Enter in Windows

Using Interpreter

>>>(7+2)*10
90
>>>print “Hello World”
Hello World
>>>i=90
>>>i
90
>>>print i*(i+10)
9000

Running Python Files (.py)

  • Off course you are not going to write all your python codes on interpreter.
  • We use extension .py for saving python files.
  • Command to execute python file:
  • python SimpleProgram.py
  • Let’s see How to write programs in Python !!!

SimpleProgram.py

x = 34 - 23 # Acomment.
y = "Hello" # Another one.
z = 3.45
if z == 3.45 or y == "Hello":
	x = x + 1
	y = y + "World" # String concat.
print x
print y

Basics of 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)
  • Characters not allowed: @, $ and % & other symbols
  • Python is a case sensitive. Thus, Manpower and manpower are two different identifiers.

Comments

  • Comments follow a # Hash
  • No multi-line comments

a = 20 # Single line comment

# This is multiline comment using hash
# and it goes to another line as well
				

Coding Style

  • No braces {} for block of code. We use indentation instead.
  • Indentation with similar number of spaces / tabs.
if True:
	print "Answer"
	print "True"
else:
	print "Answer"
	 print "False" # This line will give Error

Python 2 or 3 ?

  • For beginners there is no real difference.
  • Python 2.x is legacy, Python 3.x is the present and future of the language
  • Python 3.0 was released in 2008. The final 2.x version 2.7 release came out in mid-2010, with a statement of extended support for this end-of-life release.
  • The 2.x branch will see no new major releases after that. 3.x is under active development and has already seen over five years of stable releases, including version 3.3 in 2012 and 3.4 in 2014.

Data

Objects

  • Everything in Python is an object that has:
  • an identity (id)
  • a type
  • a value (mutable or immutable)

Object id


>>> a = 4
>>> id(a)
140542751073952
>>> a = "Hello"
>>> id(a)
4370401824
				

Type


>>> a = 4
>>> type(a)
<type 'int'>
>>> a = "Hello"
>>> type(a)
<type 'str'>
				

Value


>>> a = 4
>>> a
4
>>> print a
4
>>> a = "Hello"
>>> a
'Hello'
				

Two Types of Objects

  • Mutable: When you alter the item, the id is still the same.
    e.g. Dictionary, List
  • Immutable: When you alter the item, the id changes.
    e.g. String, Integer, Tuple

Mutable (Changable)

  • When you alter the item, the id is still the same.
    e.g. Dictionary, List

>>> b = []
>>> id(b)
140675605442000 # Object ID
>>> b.append(3)
>>> b
[3]
>>> id(b)
140675605442000 # Object ID SAME !
				

Immutable

  • When you alter the item, the id changes.
    e.g. String, Integer, Tuple

>>> a = 4
>>> id(a)
6406896
>>> a = a + 1
>>> id(a)
6406872 # DIFFERENT!
				

Variables


a = 4 		# Integer
b = 5.6 	# Float
c = "hello"	# String
a = "4" 	# rebound to String
				

Naming Conventions for variables

PEP

  • Python Enhancement Proposal
  • Similar to JSR(Java Specification Requests) in Java
  • The formal documents that describe proposed specifications and technologies for adding to the platform.
  • In short Standardization

Maths & Variables

Basic Operations

  • + (Addition) - (Substraction) * (Multiplication) / (Division)
  • ** (power)     210 = 1024
    
    >>> 2 ** 10
    1024
    						
  • % (modulo) - this operation finds the remainder after division of one number by another.
    
    >>> 11 % 2
    1
    						

Maths


>>> print round(3.14159265, 2) # round number for 2 decimal places
3.14
>>> abs(-45) 	# absolute value of number
45
>>> 11 // 2 	# floor division
5
>>> int(34.67) 	# parse float to int
34
>>> int("89")	# parse string to int
89
>>> float(89)	# parse int to float
89.0
>>> long(67829) # parse to long
67829L
				

Maths Module


>>> import math 	# Import Math Module
>>> math.sqrt(10) 	# Find Square root of 10
3.1622776601683795
>>> math.factorial(5) 	# Factorial of 5
120
>>> math.log10(20) 	# Return the base-10 logarithm of 20
1.3010299956639813
>>> math.sin(4) 	# Return the sine of 4 radians
-0.7568024953079282
>>> math.pi 		# The mathematical constant π
3.141592653589793


				

Order of Operations

Order Syntax Operation
1 ( ... ) Parentheses
2 ** Exponents
3 * / % // Multiplication and Division
4 + - Addition and Subtraction

Careful with integer division


>>> 3/4
0
>>> 3/4. 	# Either number should be float
0.75
>>> 3./4
0.75
				

Long


>>> import sys
>>> sys.maxint 		# Value differs from PC to PC
9223372036854775807
>>> sys.maxint + 1
9223372036854775808L 	# Long variable
				

New way of defining variables

a, b = 0, 1

is same as


a = 0
b = 1
				

Booleans

  • Values: True / False.
  • First letters should be capital.

a = True
b = False

if False:
	print "Its true"	# This will not get printed
if a:
	print a 		# Prints True
				

None

  • Pythonic way of saying NULL.
  • Evaluates to boolean False.

c = None
				

Conditionals

  • if and else are same as that of any other language
  • elif == else if
  • Colon is used for block. Indentaion matters !!!

if grade > 90:
	print "A"
elif grade > 80:
	print "B"
elif grade > 70:
	print "C"
else:
	print "D"
				

Comparison Operators

Syntax Operation
> Greater than
>= Greater than or equal to
< Less than
<= Less than equal to
== Is equal to
!= Is not equal to

>>> 5 > 9
False
>>> 'matt' != 'fred'
True
>>> isinstance('matt', basestring)
True
				

Boolean Operators


>>> x = 5
>>> x < -4 or x > 4
True
>>> if 4 < x < 10: 	# Chained comparisons ( x > 3 and x < 5 )
...	print "Four!"
Four!
>>>
				

String Manipulation

String Definations

  • Either by double ( " ) or single ( ' ) quotes.
  • You can insert single quote ( ' ) within string created by double quotes ( " ) & vice versa.
  • Multiline string need three time single ( ''' ) or double quotes ( """ ).

>>> name = 'matt'
>>> with_double_quote = "I ain't gonna"
>>> longer = """This string has
... multiple lines
... in it"""
				

How to print complex Strings

Using String Escaping


>>> print 'He said, "I\'m sorry"'
He said, "I'm sorry"
>>> print '''He said, "I'm sorry"'''
He said, "I'm sorry"
>>> print """He said, "I'm sorry\""""
He said, "I'm sorry"
				

String Escaping

Escape Sequence Output
\\ Backslash
\' Single Quote
\" Double quote
\b ASCII Backspace
\n Newline
\t Tab
\u12af Unicode 16 bit
\U12af89bc Unicode 32 bit
\o84 Octal character
\xFF Hex character

String formatting

c-like


>>> "%s %s" %('hello', 'world')
'hello world'
				

PEP 3101 style


>>> "{0} {1}".format('hello', 'world')
'hello world'
>>> print "Hello" , " " , "World"
Hello   World
				

String manipulation

Strings can be concatenated (glued together) with the + operator, and repeated with *


>>> 3 * 'un' + 'ium' 	# 3 times 'un', followed by 'ium'
'unununium'
>>> 'Py' 'thon'
'Python'
				

String as a List / Array


>>> text = ('Put several strings within ' 'to have them.')
>>> text
'Put several strings within to have them.'
>>> text[0] # character in position 0
'P'
>>> text[-1] # last character
'.'
				

Conversion to String

To convert any Object to String


>>> s = str(12345)
>>> s
'12345'
>>> s = str(45.89)
>>> s
'45.89'
				

String Methods

Method Description
s.endswith(sub) Returns True if ends with sub
s.find(sub) Returns index of sub or -1 (If not found)
s.format(*args) Places arguments in string. Arguments repalce numbers enclosed with curly brackets.
s.index(sub) Returns index of sub or exception
s.join(list) Returns list items separated by string
s.strip() Removes/Trims whitespace from start/end
s.strip("*") Removes/Trims astrericks from start/end

Input and Output of Data

To take input from keyboard

In String format


>>> a = raw_input() 	# raw string input
12
>>> a
'12'
				

To take input from keyboard

In Specific format


>>> num = input() 		# input of correct data type
12
>>> num
12
>>> num = input() 		# input of correct data type
12d
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    12d
      ^
SyntaxError: unexpected EOF while parsing
				

Print

CodeOutput
Normal print with newline

print "Hello"
print "World"
								

Hello
World
								
Without newline

print "Hello",
print "World",
								

Hello World
								

Help in python

dir() Method

  • Without arguments, dir() lists the variables, methods & modules you have loaded currently

>>> a = 12
>>> str = "Hello"
>>> import sys
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'str', 'sys']
>>> 
				

dir() Method over Object

  • Used to list down attributes & methods of Object
  • built-in function dir() is used to find out which names/methods a module defines. It returns a sorted list of strings

>>> str = "Hello"
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> 
				

Dunder methods

  • dunder (double underscore) or "special/magic" Methods
  • Python way of operator overloading
  • Addition + == __add__
  • Subtraction - == __sub__
  • Division / == __div__

help() method


>>> str = "Hello"
>>> help(str.startswith)

Help on built-in function startswith:

startswith(...)
    S.startswith(prefix[, start[, end]]) -> bool
    
    Return True if S starts with the specified prefix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    prefix can also be a tuple of strings to try.
				

Closing help / documentation

  • Shows full screen documentation
  • Use page-up / page-down to scroll
  • Press q to quit
  • Press h for help

Practice Sessions Basics

Practice Problem 1

  • Take two numbers from command prompt.
  • Do addition.
  • Show result like below:

The sum of 120 and 30 is 150
				

Solution to Problem 1


# This program adds two numbers provided by user

# Store input numbers
num1 = input('Enter number 1: ')
num2 = input('Enter number 2: ')

# Add two numbers
sum = int(num1) + int(num2)

# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
				

Practice Problem 2

Calculate area of a triangle
  • Take length of three sides from user
  • calculate the area
  • Show result like below:

The area of your triangle is 20.90
				

Solution to Problem 2

Area of triangle in Python

Solution to Problem 2


# Program to find area of triangle

a = float(input('First side: '))
b = float(input('Second side: '))
c = float(input('Third side: '))

# calculate the semi-perimeter
peri = (a + b + c) / 2

# calculate the area
area = (peri * (peri-a) * (peri-b) * (peri-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
				

Data Structures

Sequences

  • lists
  • dictionaries
  • tuples
  • sets

1. Lists

  • Hold ordered sequence
  • Use dir([]) to find out the attributes & methods of a list
  • Find method documentation by help([].append)

>>> a = []
>>> a.append(4)
>>> a.append('hello')
>>> a.append(1)
>>> print a
[4, 'hello', 1]
>>> a.sort() 	# Alphabetical Array Sorting
>>> print a
[1, 4, 'hello']
				

List Methods

Syntax Operation
l.append(x) Insert x at end of list
l.insert(i, x) Insert an item at a given position/index
l.extend(list2) Add list2 items to list
l.sort() In place sort (Alphabetical)
l.sort(cmp=None, key=None, reverse=False) Sort the items of the list in place
l.reverse() Reverse list in place
l.remove(item) Remove first item value found
l.pop() Remove & return item at end of list
l.index(x) Return the index of first occurance of x value
l.count(x) number of times x appears in the list

Using Lists as Stacks


>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
				

Nested Lists


>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12]]
>>> matrix
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
				

range method

  • To create number list immediately
  • (start, end) parameters
  • length = end – start

>>> range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = [1, 5]
>>> range(*a) 	# Unpacking Argument List
[1, 2, 3, 4]
				

Array Negative Indexing

  • reinterpret a[ -x ] as a[ len( a ) - x ]

>>> colors = ["red", "blue", "purple", "maroon"]
>>> colors[0]
'red'
>>> colors[-1] 	# Negative Indexing
'maroon'
>>> colors[-4]
'red'
>>> colors[-5] 	# Won't work beyond this
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
				

Array Slicing

  • arr[ start : end ]

>>> colors = ["red", "blue", "purple", "maroon"]
>>> colors[0:1]
['red']
>>> colors[0:3]
['red', 'blue', 'purple']
>>> colors[:2]
['red', 'blue']
>>> colors[2:]
['purple', 'maroon']
				

Array Stride

  • arr[ start : end : step ]

>>> range(0,10)[0:5:2]
[0, 2, 4]
>>> range(0,10)[2:5:2]
[2, 4]
>>> range(0,10)[:5:2]
[0, 2, 4]
>>> range(0,10)[::3]
[0, 3, 6, 9]
				

Array Slicing 2


>>> a = "Tiger"
>>> a[:-1]
'Tige'
>>> a[::2]
'Tgr'
>>> a[::-1]
'regiT'
				

in keyword

  • Checks if value present in sequence
  • Works on all data structures

>>> a = [10, 20, 30]
>>> 10 in a
True
>>> 25 in a
False
				

2. Dictionaries

  • Also called hashmap or associative array elsewhere

>>> age = {}
>>> age['george'] = 10
>>> age['fred'] = 12
>>> age['henry'] = 10
>>> print age['george']
10
>>> age
{'henry': 10, 'george': 10, 'fred': 12}
>>>
>>> 'henry' in age 	# in == __contains__ (dunder method)
True
				

.get Method


>>> print age['ford']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'ford'
>>> print age.get('ford', '0')
0
				

Delete Dictionary Key


>>> del age['fred'] 	# removing fred from age
>>> age
{'henry': 10, 'george': 10}
>>> age.pop('henry')	# removing henry from age
10
>>> age
{'george': 10}
>>> 
				

Note: del() methods is not in dir(age). Its external method

3. Tuples

Unordered, Immutable, Nestable


>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> u = t, (1, 2, 3, 4, 5)      # Tuples may be nested
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> t[0] = 88888 		# Tuples are immutable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> v = ([1, 2, 3], [3, 2, 1]) 	# can contain mutable objects
>>> v
([1, 2, 3], [3, 2, 1])
				

Tuples


>>> empty = () 			# Empty tuple with length 0
>>> singleton = 'hello', 	# Note trailing comma
>>> len(singleton) 		# Length check
1
>>> singleton
('hello',)
>>> singleton = singleton + ('Aditya',) # append to tuple
>>> singleton
('hello', 'Aditya')
>>> singleton = singleton + ('Mahesh') 	# append to tuple failed !
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "str") to tuple
				

4. Set

  • Set is an unordered collection with unique elements
  • Supports mathematical operations like union, intersection, difference, and symmetric difference

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) 	# create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit
True
				

Set Operations


>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a 		# unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b 		# letters in a but not in b. relative complement
set(['r', 'b', 'd'])
>>> a | b 		# letters in either a or b. union
set(['a', 'c', 'b', 'd', 'm', 'l', 'r', 'z'])
>>> a & b 		# letters in both a and b intersection
set(['a', 'c'])
>>> a ^ b 		# letters in a or b but not both (union- intersection)
set(['b', 'd', 'm', 'l', 'r', 'z'])
				

In Short

Type Defination Append Access Deletion
List list = []
list = [1, 2, 3]
list.append(123)
list.insert(0, 456)
list.extend([789])
list[0] list.pop()
list.remove(789)
del list[0]
Dictionary d = {}
d = {'a':10,'b':20}
d['elem'] = 123 d['elem']
d.get('elem',0)
d.pop('elem')
d.popitem()
del d['elem']
Tuple t = ()
t = (1, 2, 3)
s = (1,)
s = 'hello',
t = t + (123,) t[0] Cannot be done
Set s = set(['a', 'b'])
s = set('abcd')
s.add('elem') next(iter(s))
s.pop()
s.remove(x)
s.discard(x)
s.pop()
s.clear()

Comparing Sequences

(1, 2, 3) < (1, 2, 4)
[1, 2, 3] < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4) < (1, 2, 4)
(1, 2) < (1, 2, -1)
(1, 2, 3) == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)

Iterations / Loops / Traversing

Simple Iteration


arr = [1,2,3,4,5]
for i in arr:
    print i
							
is same as

for i in [1,2,3,4,5]:
    print i
							
is same as

for i in range(1, 6):
    print i
							
Output:

1
2
3
4
5
							

Iteration without index


>>> arr = ["str1", "str2", "str3"]
>>> for i in arr:
...     print i
... 
str1
str2
str3
>>> 
				

Iteration with index


>>> arr = ["str1", "str2", "str3"]
>>> for i in range(len(arr)):
...     print i, arr[i]
... 
0 str1
1 str2
2 str3
>>> 
				

Iteration using enumerate


>>> for index, value in enumerate(arr):
...     print index, value
... 
0 str1
1 str2
2 str3
>>> 
				

Using Zip Method


>>> arr1 = ['a', 'b', 'c']
>>> arr2 = [20, 45, 78]
>>> for i, v in zip(arr1, arr2):
...     print "Value of {0} is {1}.".format(i, v)
... 
Value of a is 20.
Value of b is 45.
Value of c is 78.
>>> 
				

Reverse Iteration


>>> for i in reversed(range(1,10,2)):
...     print i
... 
9
7
5
3
1
>>>
				

Iteration of sorted set


>>> basket = ['apple', 'orange', 'apple', 'pear']
>>> for f in sorted(set(basket)):
...     print f
... 
apple
orange
pear
>>> 
				

Iterating dictionary 1


>>> knights = {'gallahad':'the pure','robin':'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
... 
gallahad the pure
robin the brave
				

Iterating dictionary 2


d1 = { "john": 66, "mike": 81, "rock": 77}
print "-----Key list-----"
for key in d1.keys():
	print key

print "-----Value list-----"
for value in d1.values():
	print value

print "-----Key Value pairs-----"
for key, value in d1.items():
	print "[",key," : ",value,"]"

				

A Fibonacci Series

Using while

>>> a, b = 0, 1
>>> while b < 10:
...     print b,
...     a,b=b,a+b
... 
1 1 2 3 5 8
				

continue


list1 = [12, 50, 34, 78, 33, 99]
for item in list1:
	if item < 50:
		continue
	print item
				
Output:

50
78
99
				

break


list1 = [12, 34, 78, 99]
for item in list1:
	print item
	if item > 70:
		break
				
Output:

12
34
78
				

Finding Even & Odd numbers

Using continue

for num in range(2, 10):
	if num % 2 == 0:
		print num, "Even"
		continue
	print num, "Odd"
				
Output:

2 Even
3 Odd
4 Even
5 Odd
6 Even
7 Odd
8 Even
9 Odd
				

Finding Prime numbers

A prime or prime number is a natural number that has exactly two distinct natural number divisors: 1 and itself


for n in range(2, 10): 		# total range of numbers
	isDiv = False
	for x in range(2, n): 	# get numbers less than n
		if n % x == 0: 	# check modulo
			print n, '=', x, '*', n/x
			isDiv = True
			break
	# Check whether isDiv is True or False
	if not isDiv:
		print n, 'Prime number'
				

Output:


2 Prime number
3 Prime number
4 = 2 * 2
5 Prime number
6 = 2 * 3
7 Prime number
8 = 2 * 4
9 = 3 * 3
				

pass keyword

  • Pass is null operation
  • Used as placeholder for syntactical needs

for i in range(10):
	pass

def fun(arg):
	pass

class c:
	pass
				

A suggestion

  • Do not modify list or dictionary contents while looping them.

Practice Problem

Program to Display the multiplication Table
  • Ask which multiplication table of :
  • Print Multiplication table.

Solution to Problem


# take input from user
num = int(input("Display multiplication table of : "))

# iterate 10 times
for i in range(1,11):
   print num, 'x' , i, '=', num * i
				

Methods / Functions

Method

  • Keyword def is used
  • Documnetation is on first line of method block
  • No return type required

def add_2(num):
	"""return num by adding
	2 into it"""	# Function Documentation
	return num + 2

b = add_2(3)

print b
				
Output = 5

Method

  • def
  • function name
  • (parameters)
  • :
  • indent
  • optional documentation
  • body
  • return

Default parameter values

  • In case if we dont have any value to pass
  • Also called Named parameter

def add_n(num, n = 3):
	return num + n
five = add_n(2)
ten  = add_n(15, -5)
				

Default parameters can be mutable

  • When the default parameter is a mutable object such as list, dictionary, or instances of most classes

def f(a, L=[]):
	L.append(a)
	return L
print f(1)
print f(2)
print f(3)
------------------------
[1]
[1, 2]
[1, 2, 3]
				

To change to default behavior

  • If you don’t want the default to be shared between subsequent calls

def f(a, L=None):
	if L is None:
		L = []
	L.append(a)
	return L
print f(1)
print f(2)
print f(3)
------------------------
[1]
[2]
[3]
				

__doc__

  • Functions have docstrings. Accessible via .__doc__ or help

>>> def echo(txt):
...     "echo back txt" # Function/Method Documentation
...     return txt
... 
>>> help(echo)

Help on function echo in module __main__:

echo(txt)
    echo back txt

(END)
				

Method Naming

  • lowercase
  • underscore_between_words
  • don't start with numbers
  • verb
  • See PEP 8 for more info

Function Properties

  • Function refers to another function variable

>>> def addition(a, b=0):
...     "This method adds two numbers"
...     return a+b
... 
>>> addition(10,20)
30
>>> addition(10)
10
>>> addition
<function addition at 0x10aa55c80>
>>> add = addition # Function refers to another function variable
>>> add(10, 30)
40
>>> 
				

Global Variable

  • Need to define global in order to use inside functions.

# declare global variable
n = 0
def setup():
    global n
    n = 100
				

Classes / OOPS

Classes


class Student(object):
    def __init__(self, name):
        self.name = name
    def study(self):
        print self.name,"studying..."

stud = Student("Mark Watson")
stud.study()
				

Classes

  • object (as base class)
  • dunder __init__ (constructor)
  • all methods take self as first parameter

self

  • Always represent current object

Subclass


class Student(object):
    def __init__(self, name):
        self.name = name
    def study(self):
        print self.name,"studying..."

class Geek(Student):
    "classes can have documentation"
    def study(self):
        print "%s Programming..." % self.name

g = Geek("Mark Watson")
g.study()
				

Class Naming

  • Cannot start with numbers
  • Nouns
  • CamelCase – first the letter in a word within name should be written in capitals

Modules / Libraries

Modules

  • Put definitions in a file and use them in a script or in an the interpreter. Such a file is called a module
  • A module is a file containing Python definitions and statements.
  • Extension is .py only

Craeting Module: fibo.py


# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print b,
        a, b = b, a+b

def fib2(n): # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result
				

Using Module


>>> import fibo
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
				

Using Module 2


>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

>>> import fibo as f
>>> f.fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

				

Executing module as script


# Add this code in fibo.py

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1])) # Accessing arguments via system library
--------------------------------------------------------------------
$ python fibo.py <arguments>

$ python fibo.py 50
1 1 2 3 5 8 13 21 34

				

Time Module

  • Sleep function pauses the execution for given number of seconds

from time import sleep

while True:
	print "Hi"
	sleep(1)
				

File I/O

File Reading

  • Open a file to read from it.

fin = open("sample.txt")
for line in fin:
    print line
fin.close()
				

File Writing

  • Open a file using 'w' to write to a file:

fout = open("sample2.txt", "w")
fout.write("hello world")
fout.flush()
fout.close()
				

A suggestion

  • Don’t forget to close file after use.

Closing files using with

  • Also called as implicit close (Only ver. 2.5+)

>>> with open('sample2.txt') as fin:
...     for line in fin:
...             print line
... 
hello world
>>>
				

Saving Data in File (JSON)

>>> list = []
>>> list.append({"name":"Ramesh", "age": 21, "class": "BE"})
>>> list.append({"name":"Punit", "age": 20, "class": "TE"})
>>> 
>>> import json
>>> jsonData = json.dumps(list)
>>> fout = open("studs.txt", "w")
>>> fout.write(jsonData)
>>> fout.flush()
>>> fout.close()
				

Get Saved Data from File (JSON)

>>> fin = open("studs.txt")
>>> line  = fin.readline()
>>> 
>>> import json
>>> list = json.loads(line)
>>> for stud in list:
...     print stud
... 
{u'age': 21, u'name': u'Ramesh', u'class': u'BE'}
{u'age': 20, u'name': u'Punit', u'class': u'TE'}
				

Practice Problem

Student Management Program


Menu for system:
1. Display List of students
2. Add Student
2. Edit Student by Name
3. Delete Student
4. Exit
Choise: [Take input from user]

Take following information from students:
1. roll_num
2. name
3. class_name
				

References

Thank you

- Dwij IT Solutions

Did you liked this tutorial ?

Checkout more such tutorials on: http://dwij.net/tuts

Powered by Dwij IT Solutions