Introduction to Python 3.5 - Rajeev Vashisht
Introduction to Python 3.5 - Rajeev Vashisht
Foreward
Python is a dynamic language like Ruby. Types are dynamic & polymorphic. There is no
need to declare type of variable while declaring. Also programs need to be indented for
compiler compliance & compulsory readability & clarity of programs. Python is a modern
language used in web scraping, big data & cloud. If you are thinking of learning a new
language, you should certainly learn the Python language.
Ex. Internal Functions
def addfour(a,b,c,d):
def addtwo(a,b):
return a+b
return addtwo(a,b)+addtwo(c,d)
Ex. Finding factorial of a number
def factorial(n):
result=1
for i in range(1,n+1):
result=result*i
return result
Ex.Factorial using recursion
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
Ex. How to traverse a string using for statement
def showstr(s):
for char in s:
print(char)
Ex. Use of input function
def addtwo():
a=int(input(“Enter first number:”))
b=int(input(“Enter Second number:”))
return a+b
Ex.Find maximum of three numbers
def maxthree(a,b,c):
if a>=b and a>=c:
return a
elif b>=a and b>=c:
return b
else:
return c
Ex. Prune a list greater than n members
def prune(aList,n):
result=[]
for i in aList:
if i>n:
result.append(i)
return result
>>>aList=[10,20,30,40]
>>>prune(aList,10)
[20,30,40]
Ex. Using while loop to print Fibonacci Numbers upto n
def fibonacci(n):
a=0
b=1
print(a,b)
while a+b<=n:
c=a+b
print(c)
a=b
b=c
Output
>>> fibonacci(30)
01
1
2
3
5
8
13
21
Ex:Example of Classes
>>> class a:
def __init__(self):
self.aList=[1,2,3,4,5]
print(self.aList)
def add(self,a):
self.aList.append(a)
print(self.aList)
class a:
def __init__(self):
self.aList=[1,2,3,4,5]
print(self.aList)
def add(self,a):
self.aList.append(a)
print(self.aList)
def remove(self,a):
self.aList.remove(a)
print(self.aList)
>>> A=a()
[1, 2, 3, 4, 5]
>>> A.add(10)
[1, 2, 3, 4, 5, 10]
>>> A.add(20)
[1, 2, 3, 4, 5, 10, 20]
>>> A.remove(1)
[2, 3, 4, 5, 10, 20]
>>> A.remove(2)
[3, 4, 5, 10, 20]
>>>
About the Author
A short book which gives introduction to the basics of Python language, including and up
to class concepts & recursion & Internal Functions
A really short book of compiled examples in Python 3.5