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

UNIT-1python Introduced

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

UNIT-1python Introduced

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Python Programming

Founder:
Guido van Rossum in 1991

Features / Reasons for Popularity:


1. General Purpose Language: It can be used for simple programs like addition of two numbers and used
for programs of machine learning, data mining and data science as well.
2. Interpreter: interpreter is used in place of compiler.
3. Multiple Programming Paradigm like Object Oriented, Imperative, functional, procedural.
4. High Level Language:
5. Easiest: Easier for people who are from Non technical background and school students also
6. Open Source Software

Websites using Python:


Google, drop box, you tube, yahoo, Reddit,etc.

Python versions
1. Python 1.0 – January 1994
2. Python 2.0 – October 2000
3. Python 3.0- December 2008

Python 3.0 doesn’t have backward compatibility with earlier versions.

Software Requirements:
Editor is required to write a program.
Need to install Interpreter (IDLE) and I.D.E (for GUI purpose).Various IDE are available. Ex: pycharm, Atom,
Anaconda, etc.
Latest version is 3.7. It can be downloaded from official website of python.

x = 2, translates to "(generic) name x receives a reference to a separate, dynamically allocated object of


numeric (int) type of value 2." This is termed binding the name to the object. Since the name's storage
location doesn't contain the indicated value, it is improper to call it a variable. Names may be
subsequently rebound at any time to objects of greatly varying types, including strings, procedures,
complex objects with data and methods, etc. Successive assignments of a common value to multiple
names, e.g., x = 2; y = 2; z = 2 result in allocating storage to (at most) three names and one numeric
object, to which all three names are bound. Since a name is a generic reference holder it is unreasonable
to associate a fixed data type with it. However at a given time a name will be bound to some object,
which will have a type; thus there is dynamic typing.

For example:

x=2
print(x)
x=4.5
print(x)
x=’a’

Prof. Zalak Trivedi, CE Dept, ITE, IU


print(x)

The above code is valid in python.

Comments
For single line comment #
For multi line comment “ “ “ line1
Line 2 “““

Variable assignment
X=5
x,y=3,4
x=”a”

Datatypes: No need to specify explicitly.


1. Numeric (integer, float, complex). 2. String. 3. Collection (list, tuple, set, dictionary)

User Input
Syntax: var_name=input()
Default data type is string, so to convert it into other type, we need to do explicit casting.
Ex: var_name=int(input())
var_name=str(input())
x=int(input(“enter value”))
Multiple values in single line:
Ex: x,y=int(input()), int(input())
print(x,y)

x,y,z = map(int, input("enter 3 values").split())


print(x+y+z)

User Output:
print(“ message”)
print(“message”+var_name)

Operators
Same as any other programming languages. New operator in python is Membership operator.
1. in example: x=[“apple”,”banana”]
print(“banana” in x)
output: true
2. not in example: x=[“apple”,”banana”]
print(“banana” not in x)
output: false

Branching Conditions:

#if else #else if ladder


Prof. Zalak Trivedi, CE Dept, ITE, IU
if a>b: If condition:
print (a,"is largest") Statements…
else: elif condition:
print (b,"is largest") Statements…

Looping:
#for loop:
Syntax: for variable_name in range (start value, end value, step size):
Statements
Ex: for i in range(5): Output: 0,1,2,3,4
print(i)
Ex: for i in range(5,10): Output: 5,6,7,8,9
print(i)
Ex: for i in range(10,5,-1): Output: 10,9,8,7,6
print(i)
Ex: for i in range(5,10,2): Output: 5,7,9
print(i)

#while:
Syntax: while condition:
Statements

#else with for loop:


for in range(5):
print(i)
else:
print(“out of loop”)

#Break and Continue Statement: same as other programming languages.

User defined functions:


Syntax: def function_name(arguments if any):
Statements…
Function_name() # calling function

Recursion: Recursion is same as any other programming language.

Function types based on Argument passing methods:


1. Required Arguments: simple argument passing

2. Keyword Arguments: Sequence of argument does not matter here.


Ex: def display(name,age,salary):
print(name+age+salary)
n=”audi”
a=35

Prof. Zalak Trivedi, CE Dept, ITE, IU


s=500000
display(salary=s,name=n,age=a)

3. Default Arguments:
Ex: def display(name,age,salary=5000):
print(name+age+salary)
n=”audi”
a=35
s=500000
display(salary=s,name=n,age=a)
display(name=n,age=a) #call to default argument of salary

4. Variable length Arguments:


Ex: def func(name, *fav_sub):
print(name,”like to read”)
for subject in fav_sub:
print(subject)
func(“George”,”maths”,”science”)
func(“Mathew”,”arts”,”python”,”c”)

Functions as Objects (book chapter 5.3)

Functions can be treated like objects of any other type, e.g., int or list. They have types, e.g., the
expression type (fact) has the value <type 'function'>; they can appear in expressions, e.g., as the right-
hand side of an assignment statement or as an argument to a function; they can be elements of lists.

Example:

def app(f,l):
for i in range(len(l)):
l[i]=f(l[i])
def fact(n):
if n==1:
return 1
else:
return(n*fact(n-1))
l=[1,-2,3.33,5]
print("list=",l)
app(abs,l)
print("list after abs=",l)
app(int,l)
print("list after int=",l)
print("factorial=",fact(4))
app(fact,l)
print("list after factorial recursion=",l)

Output:
List = [1, -2, 3.33, 5]

Prof. Zalak Trivedi, CE Dept, ITE, IU


list after abs = [1, 2, 3.33, 5]
list after int = [1, 2, 3, 5]
factorial = 24
list after factorial recursion = [1, 2, 6, 120]

Comparison of map() and function as object with factorial example:

def app(l,f): def fact(n):


for i in range(len(l)): if n==1:
l[i]=f(l[i]) return 1
def fact(n): else:
if n==1: return(n*fact(n-1))
return 1
else: l=[1,2,3,4,5,6]
return(n*fact(n-1)) x=map(fact,l)
l=[1,-2,3.33,5] print(list(x))
print("factorial=",fact(4))
app(l,fact)
print("list after factorial recursion=",l)

Lambda /Anonymous function: function without a name.


Lambda keyword is used to create anonymous functions.
Syntax: Variable_name = lambda arguments: expression
Ex: g = lambda y:y*y*y #Output: 21
print(g(7))
Ex: g = lambda a,b,c:a+b+c #Output: 6
print(g(1,2,3))

Properties:
1. Lambda functions can have any numbers of arguments but only one expression, which will be
evaluated.
2. One is free to use lambda functions wherever function objects are required.
3. These functions are syntactically restricted to a single expression.

map()
Syntax: map(function, iterable, ...)

map() Parameter
function : map() passes each item of the iterable to this function.
iterable : iterable which is to be mapped
You can pass more than one iterable to the map() function.

Return Value from map()


The map() function applies to given function which in turn to each item of an iterable and returns a
list of the results.
Prof. Zalak Trivedi, CE Dept, ITE, IU
The returned value from map() (map object) then can be passed to functions like list() (to create a
list), set() (to create a set) and so on.

Example of map with single iterator:


def calculateSquare(n):
return n*n
numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

Example of map and lambda with single iterator:


numbers = (1, 2, 3, 4)
result = map(lambda x : x * x, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare) #(1,4,9,16)

Example of map and lambda with multiple iterator:


numbers = [1, 2, 3, 4]
n1=[5,5,5,5]
result = map(lambda x, y : x*y, numbers, n1)
#print(result) # <map object at 0x0000021AF45E8320>
# converting map object to set
numbersSquare = list(result)
print(numbersSquare) #[6,7,8,9]

filter():
Example: l=[1,4,5,6,2,7,8,34,25]
x=filter(lambda y:y>4,l)
print(list(x)) #output: [5, 6, 7, 8, 34, 25]
Write a program to find out odd numbers from given list.
zip():
Example: l1=[1,2,3,4,5]
l2=['a','b','b','d']
l4=['e','e','e','e']
l3=zip(l1,l2,l4)
print(list(l3)) #Output: [(1, 'a', 'e'), (2, 'b', 'e'), (3, 'b', 'e'), (4, 'd', 'e')]

Example: l1=[1,2,3,4,5]
l2=['a','b','b','d']
l3=zip(l1,l2)
print(dict(l3)) #Output: {1: 'a', 2: 'b', 3: 'b', 4: 'd'}

Scope of variables:
Default scope of variable is global.
Prof. Zalak Trivedi, CE Dept, ITE, IU
Variables defined in certain block are having scope local to that block.

Example :

def f(): def f(): def f(): def f():


print(s) s=”me” print(s) global s
s=”any” print(s) s=”me” print(s)
f() s=”any” print(s) s=”me”
f() s=”any” print(s)
print(s) f() s=”any”
print(s) f()
print(s)

Output: any Output: me Output: error Output:


any any
me
me

Modules:
A module is a .py file containing Python definitions and statements. We could create, for example, a
file circle.py containing following code:
pi = 3.14159
def area(radius):
return pi*(radius**2)
def circumference(radius):
return 2*pi*radius
def sphereSurface(radius):
return 4.0*area(radius)
def sphereVolume(radius):
return (4.0/3.0)*pi*(radius**3)

A program gets access to a module through an import statement. for example,

import circle
print circle.pi
print circle.area(3)
print circle.circumference(3)
print circle.sphereSurface(3)
will print
3.14159
28.27431
18.84954
113.09724

Identifiers whose names starts with two underscores (__) are known as private identifiers.

File Management in Python:


open(fn, 'w') fn is a string representing a file name. Creates a file for writing and returns a file handle.

Prof. Zalak Trivedi, CE Dept, ITE, IU


open(fn, 'r') fn is a string representing a file name. Opens an existing file for reading and returns a file
handle.
open(fn, 'a') fn is a string representing a file name. Opens an existing file for appending and returns a
file handle.
fh.read() returns a string containing the contents of the file associated with the file handle fh.
fh.readline() returns the next line in the file associated with the file handle fh.
fh.readlines() returns a list each element of which is one line of the file associated with the file handle
fh.
fh.write(s) write the string s to the end of the file associated with the file handle fh.
fh.writeLines(S) S is a sequence of strings. Writes each element of S to the file associated with the file
handle fh.
fh.close() closes the file associated with the file handle fh.

Syntax to open file:


file handler = open(“file name”,”mode”)
Ex:
file = open(“file1.txt”,”w”)
print(file.read()) #prints on screen

Strings: Strings are immutable and non scalar types.


In-built string functions: upper,lower,replace, etc…
Slice Operation: to find sub string
Ex: 0 1 2 3 4 5 #index from start
P Y T H O N
-6 -5 -4 -3 -2 -1 #index from end

Ex: str = “python”


print(str[1:5]) #ytho
print(str[:5]) #pytho
print(str[1:]) #ython
print(str[:]) #python
print(str[-2:]) #on
print(str[-5:-2]) #yth

Specific stride in slicing operation: In the slice operation,you can specify a third argument as the
stride,which refers to the number of characters to move forward after the first character is retrieved
from the string.
01234567891011121314151617181920212223242526272829
Ex: str = “welcome to the world of python”
Print(“str[2:10]=”,str[2:10]) #lcome to
Print(“str[2:10:1]=”,str[2:10:1]) #lcome to
Print(“str[2:10:2]=”,str[2:10:2]) #loet
Print(“str[2:13:4]=”,str[2:13:4]) #le

Strings, Tuples, Lists and Dictionaries


There are four collection data types in the Python programming language:

1. List is a collection which is ordered and changeable. Allows duplicate members. []


Prof. Zalak Trivedi, CE Dept, ITE, IU
2. Tuple is a collection which is ordered and unchangeable. Allows duplicate members. ()
3. Set is a collection which is unordered and unindexed. No duplicate members. {}
4. Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.

Note: In Default case values are formed in form of tuple.


Ex: 1 init_tuple_a = 'a', 'b' # this will generate tuple of two elements
init_tuple_b = ('a', 'b')
print (init_tuple_a == init_tuple_b) #output: True
Ex: 2 init_tuple_a = 'a', 'b' # this will generate tuple of two elements
init_tuple_b = ['a', 'b']
print (init_tuple_a == init_tuple_b) #output: False

Lists and Mutability

#list type

name=["indus","uni","iite","ahmedabad"]

print (name[2:4])

print (name)

#string functions with .operator

print l.upper()

print l.replace("u","a")

print l.split(" ")

#check existence

x = ["apple", "banana"]

print("banana" in x)

x.append("orange")

print (x)

x.insert(1,"lemon")

print (x)

#tupples:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

output: apple banana cherry

Prof. Zalak Trivedi, CE Dept, ITE, IU


#Access Tuple Items
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

output : banana

#Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable.

thistuple = ("apple", "banana", "cherry")


thistuple[1] = "blackcurrant"
# The values will remain the same:
print(thistuple)

output: apple banana cherry

#Loop Through a Tuple


thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)

#Check if item Exists


thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

#Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)

#Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:

The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
#The tuple() Constructor
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)

Prof. Zalak Trivedi, CE Dept, ITE, IU


#Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
#Add Items
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
output: orange apple banana cherry
#update items
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
output: {‘grapes’,‘orange‘,’mango’,’apple’,’banana’,’cherry’}
#Remove Item

To remove an item in a set, use the remove(), or the discard() method.

If the item to remove does not exist, remove() will raise an error, where as discard() doesn’t.

thisset = {"apple", "banana", "cherry"}


thisset.remove("orange") # will give error.
print(thisset)

#clear() The clear() method empties the set:

thisset = {"apple", "banana", "cherry"}


thisset.clear()
print(thisset) # output: set()

#del : The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}


del thisset
print(thisset) #set no longer exist.

#The set() Constructor

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets


print(thisset)

Prof. Zalak Trivedi, CE Dept, ITE, IU


#Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are
written with curly brackets, and they have keys and values.

thisdict = {"brand": "Ford","model": "Mustang",


"year": 1964}
print(thisdict)

Out put: {‘brand’:’ford’ , ‘model’:’mustang’,’year’:1964}

#Accessing Items
x = thisdict ["model"]
output: mustang

There is also a method called get() that will give you the same result:

x = thisdict.get("model")

Testing:
Purpose of testing is to show that bugs exist, not to show that a program is bug-free.
Test case/ Test suite:
The key to testing is finding a collection of inputs, called a test suite, that has a high likelihood of
revealing bugs, yet does not take too long to run. The key to doing this is partitioning the space of
all possible inputs into subsets that provide equivalent information about the correctness of the
program, and then constructing a test suite that contains one input from each partition.

Types: Black box, Glass box/White box, Unit testing, integrated testing.

Black box: Heuristics based on exploring paths through the specification fall into a class called black-
box testing.

Glass box/White box: Heuristics based on exploring paths through the code fall into a class called
glass-box testing.

Unit Test: During this phase testers construct and run tests designed to ascertain whether individual
units of code (e.g., functions) work properly.

Integrated test: integration testing, which is designed to ascertain whether the program as a whole
behaves as intended.

Drivers and Stub

During unit testing, we need to build Stubs as well as Drivers.

Drivers simulate parts of the program that use the unit being tested,

Stubs simulate parts of the program used by the unit being tested.

Prof. Zalak Trivedi, CE Dept, ITE, IU


Ideally, a stub should

• Check the reasonableness of the environment and arguments supplied by the caller (calling a function
with inappropriate arguments are a common error),

• Modify arguments and global variables in a manner consistent with the specification, and

• Return values consistent with the specification.

In industry, the testing process is often highly automated. Testers do not sit at terminals typing
inputs and checking outputs. Instead, they use test drivers that autonomously

• Set up the environment needed to invoke the program (or unit) to be tested,

• Invoke the program (or unit) to be tested with a predefined or automatically generated sequence of
inputs,

• Save the results of these invocations,

• Check the acceptability of the results of the tests, and

• Prepare an appropriate report.

Run time bugs can be categorized along two dimensions:

1. Overt → covert:

An overt bug has an obvious manifestation, e.g., the program crashes or takes far longer
(maybe forever) to run than it should.

A covert bug has no obvious manifestation. The program may run to conclusion with no
problem—other than providing an incorrect answer.

Many bugs fall between the two extremes, and whether or not the bug is overt can depend upon how
carefully one examines the behavior of the program.

2. Persistent → intermittent:

A persistent bug occurs every time the program is run with the same inputs.

An intermittent bug occurs only some of the time, even when the program is run on the same inputs
and Seemingly under the same conditions.

Defensive Programming: Good programmers try to write their programs in such a way that
programming mistakes lead to bugs that are both overt and persistent. This is often called
defensive programming.

Prof. Zalak Trivedi, CE Dept, ITE, IU

You might also like