Created by Ganesh Bhosale in Dwij IT Solutions
Like this Python tutorial, our tutorials are always open-source for learners. Like our facebook page to get more free tutorial updates.
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
Python was conceived in the late 1980’s and its implementation was started in December 1989 by Guido van Rossum in the Netherlands.
By default python comes pre-installed in Ubuntu distribution. Check simply by command:
python --version
set path=%path%;C:\python27
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
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.
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
>>>(7+2)*10
90
>>>print “Hello World”
Hello World
>>>i=90
>>>i
90
>>>print i*(i+10)
9000
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
a = 20 # Single line comment
# This is multiline comment using hash
# and it goes to another line as well
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False" # This line will give Error
>>> a = 4
>>> id(a)
140542751073952
>>> a = "Hello"
>>> id(a)
4370401824
>>> a = 4
>>> type(a)
<type 'int'>
>>> a = "Hello"
>>> type(a)
<type 'str'>
>>> a = 4
>>> a
4
>>> print a
4
>>> a = "Hello"
>>> a
'Hello'
>>> b = []
>>> id(b)
140675605442000 # Object ID
>>> b.append(3)
>>> b
[3]
>>> id(b)
140675605442000 # Object ID SAME !
>>> a = 4
>>> id(a)
6406896
>>> a = a + 1
>>> id(a)
6406872 # DIFFERENT!
a = 4 # Integer
b = 5.6 # Float
c = "hello" # String
a = "4" # rebound to String
>>> 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
>>> 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 | Syntax | Operation |
|---|---|---|
| 1 | ( ... ) | Parentheses |
| 2 | ** | Exponents |
| 3 | * / % // | Multiplication and Division |
| 4 | + - | Addition and Subtraction |
>>> 3/4
0
>>> 3/4. # Either number should be float
0.75
>>> 3./4
0.75
>>> import sys
>>> sys.maxint # Value differs from PC to PC
9223372036854775807
>>> sys.maxint + 1
9223372036854775808L # Long variable
a, b = 0, 1
is same as
a = 0
b = 1
a = True
b = False
if False:
print "Its true" # This will not get printed
if a:
print a # Prints True
c = None
if grade > 90:
print "A"
elif grade > 80:
print "B"
elif grade > 70:
print "C"
else:
print "D"
| 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
>>> x = 5
>>> x < -4 or x > 4
True
>>> if 4 < x < 10: # Chained comparisons ( x > 3 and x < 5 )
... print "Four!"
Four!
>>>
>>> name = 'matt'
>>> with_double_quote = "I ain't gonna"
>>> longer = """This string has
... multiple lines
... in it"""
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"
| 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 |
c-like
>>> "%s %s" %('hello', 'world')
'hello world'
PEP 3101 style
>>> "{0} {1}".format('hello', 'world')
'hello world'
>>> print "Hello" , " " , "World"
Hello World
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'
>>> 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
'.'
To convert any Object to String
>>> s = str(12345)
>>> s
'12345'
>>> s = str(45.89)
>>> s
'45.89'
| 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 |
In String format
>>> a = raw_input() # raw string input
12
>>> a
'12'
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
| Code | Output |
|---|---|
| Normal print with newline | |
|
|
| Without newline | |
|
|
>>> a = 12
>>> str = "Hello"
>>> import sys
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'str', 'sys']
>>>
>>> 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']
>>>
>>> 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.
The sum of 120 and 30 is 150
# 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))
The area of your triangle is 20.90
# 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)
>>> 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']
| 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 |
>>> 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]
>>> 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(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]
>>> 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
>>> colors = ["red", "blue", "purple", "maroon"]
>>> colors[0:1]
['red']
>>> colors[0:3]
['red', 'blue', 'purple']
>>> colors[:2]
['red', 'blue']
>>> colors[2:]
['purple', 'maroon']
>>> 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]
>>> a = "Tiger"
>>> a[:-1]
'Tige'
>>> a[::2]
'Tgr'
>>> a[::-1]
'regiT'
>>> a = [10, 20, 30]
>>> 10 in a
True
>>> 25 in a
False
>>> 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
>>> print age['ford']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'ford'
>>> print age.get('ford', '0')
0
>>> 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
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])
>>> 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
>>> 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
>>> 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'])
| 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() |
| (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) |
|
Output:
|
>>> arr = ["str1", "str2", "str3"]
>>> for i in arr:
... print i
...
str1
str2
str3
>>>
>>> arr = ["str1", "str2", "str3"]
>>> for i in range(len(arr)):
... print i, arr[i]
...
0 str1
1 str2
2 str3
>>>
>>> for index, value in enumerate(arr):
... print index, value
...
0 str1
1 str2
2 str3
>>>
>>> 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.
>>>
>>> for i in reversed(range(1,10,2)):
... print i
...
9
7
5
3
1
>>>
>>> basket = ['apple', 'orange', 'apple', 'pear']
>>> for f in sorted(set(basket)):
... print f
...
apple
orange
pear
>>>
>>> knights = {'gallahad':'the pure','robin':'the brave'}
>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave
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, b = 0, 1
>>> while b < 10:
... print b,
... a,b=b,a+b
...
1 1 2 3 5 8
list1 = [12, 50, 34, 78, 33, 99]
for item in list1:
if item < 50:
continue
print item
Output:
50
78
99
list1 = [12, 34, 78, 99]
for item in list1:
print item
if item > 70:
break
Output:
12
34
78
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
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
for i in range(10):
pass
def fun(arg):
pass
class c:
pass
# 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
def add_2(num):
"""return num by adding
2 into it""" # Function Documentation
return num + 2
b = add_2(3)
print b
Output = 5
def add_n(num, n = 3):
return num + n
five = add_n(2)
ten = add_n(15, -5)
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
------------------------
[1]
[1, 2]
[1, 2, 3]
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]
>>> 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)
>>> 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
>>>
# declare global variable
n = 0
def setup():
global n
n = 100
class Student(object):
def __init__(self, name):
self.name = name
def study(self):
print self.name,"studying..."
stud = Student("Mark Watson")
stud.study()
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()
# 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
>>> 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
>>> 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
# 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
from time import sleep
while True:
print "Hi"
sleep(1)
fin = open("sample.txt")
for line in fin:
print line
fin.close()
fout = open("sample2.txt", "w")
fout.write("hello world")
fout.flush()
fout.close()
>>> with open('sample2.txt') as fin:
... for line in fin:
... print line
...
hello world
>>>
>>> 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()
>>> 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'}
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
Did you liked this tutorial ?
Checkout more such tutorials on: http://dwij.net/tuts