Python Programming Unit i
Python Programming Unit i
Simple
Reading a program written in python feels almost like
reading English.
Easy to Learn
The structure of the program is very simple.
Versatile
Python supports development of a wide range of
application ranging from simple text processing to web
applications.
Free and Open Source
Any one can freely distribute it, read the source code, edit
Features of Python
High Level Language
Programmer don’t worry about low level details like
managing memory user by the program. They need to
concentrate on writing solutions of the problem.
Interactive
Programs in python work in interactive mode which allows
interactive testing and debugging of pieces of code.
Portable
The programs work on any of the operating system linux, win.
Object Oriented
Python supports object oriented as well as procedure
oriented style of programming.
Features of Python
Interpreted
No need to compile a program before executing it, You can simply run the
program
Dynamic
Programs written in python can be copied and used for flexible
development of applications.
Extensible
Any one can add low level module to the python interpreter. . These
modules enable programmers to add to or customize their tools to work
more efficiently.
Embeddable
Programmers can embed python within their C,C++,Java
Extensive Libraries
Python has huge library that is easily portable across different platforms.
Features of Python
Easy Maintenance
Code written in python is easy to maintain
Secure
The python language environment is secure from tampering. Modules can
be distributed to prevent altering the source code.
Robust
Python programmers cannot manipulate memory directly. Moreover
errors are raised and exception that can be catch and handle by the
program code.
Multi-threaded
Executing more than one process of a program simultaneously.
Garbage Collection
reference counter is maintained to ensure that no object that is currently in
use is deleted.
Python Data Types
Variable can hold values of different types called data types.
Python supports 5 standard data types.
Numbers
Stings
List
Tuple
Dictionary
Ex: num=7
amt=123.45
code=‘A’
pi=3.1415926536
msg=“HI”
population_of_India=10000000000
Python Operators
Arithmetic Operators
+ - * / % ** //
Comparison Operators
== != > < >= <=
Assignment Operator
= += -= *= /= %= //= **=
Unary Operator A=-(b)
Bitwise Operators & | ^ ~
Shift Operators << >>
Logical Operators && || !
Membership Operators in not in
Identity Operator is is not
Python Expressions
An expression is any legal combination of symbols like variables,
constants and operators that represents a value.
Operand is the value on which operator is applied.
These operators use constants and variables to form an expression.
Example: A * B + C - 5
Types of Expressions:
Based on position of operators in an expression:
Infix Expression: a=b-c
Prefix Expression: a=-bc
Postfix Expression: a=bc-
Python Expressions
Based on the data type of the result obtained on evaluating an expression:
Constant Expression: 8+9-2
Integral Expression: a=10
b=5
c=a*b
Floating Point Expression: a*b/2
Relational Expression: c=a>b
Logical Expression: a>b && y!=0
Bitwise Expression: x=y&z
Assignment Expression: c=a+b or c=10
Python Control Statements
if statement
if test_expression:
statement 1
…………………
statement n
Statement x
Example:
X=10
if(x>0):
x=x+1
print(x)
Output:
X=11
Python Control Statements
if-else statement
if (test_expression):
statement block 1
else:
statement block 2
Statement x
Example:
age=int(input(“Enter the age:”))
If(age>=18):
print(“You are eligible to vote”)
else:
yrs=18-age
print(“You have to wait for another “+str(yrs)+”years to cast your
vote”)
Python Control Statements
if-elif-else statement
if (test_expression 1):
statement block 1
elif (test_expression 2):
statement block 2
Elif (test_expression N):
statement block N
else:
statement block X
Statement Y
Python Control Statements
if-elif-else statement
Example
num=int(input(“Enter any Number:”))
if(num==0):
print(“The value is equal to zero”)
elif(num>0):
print(“The number is positive”)
else:
print(“The number is negative”)
Output:
Enter any number: -10
The number is negative
Python Control Statements
while loop
Example:
statement x
while(condition):
statement block
statement y
Example:
i=0
while(i<=9):
print(i,end=“ “)
i=i+1
Output:
0 1 2 3 4 5 6 7 8 9
Python Control Statements
for loop
for loop_control_var in sequence:
statement block
Example:
for i in range(1, 5):
print(i, end=“ “)
Output:
1 2 3 4
Python Functions
function
A function, f that uses another function g is known as the calling function
and g is known as the called function.
The inputs that the function takes are known are known as
arguments/parameters.
When a called function returns some result back to the calling function, it
is said to return that result.
The calling function may or may not pass parameters to the called
function. If the called function accepts arguments, the calling function will
pass parameters, else not.
Function declaration is a declaration statement that identifies a function
with its name, a list of arguments that is accepts, and the type of data it
returns.
Function definition consists of a function header that identifies the
function, followed by the body of the function containing the executable
code for the function
Python Functions
function
Function blocks starts with the keyword def.
The keyword is followed by the function name and parentheses(). The
function name is used to uniquely identify the function.
After the parentheses a colon(:) is place.
Parameters or arguments that the function accepts are placed within
parentheses. Through these parameters values are passed to the function.
They are optional. In case no values are to be passed, nothing is placed
within the parenthesis.
the code block within the function is properly indented to form the block
code.
A function may have a return[expression] statement. That is, the return
statement is optional. If it exists, it passed back an expression to the caller.
A return statement with no arguments is the same as return none.
You can assign the function name to a variable. Doing this will allow you
to call the same function using the name of that variable.
Function
Python Functions
def Function_name(variable1, variable2, ..):
documentation string
statement block
return[expression]
Example:
def diff(x,y): def func():
return x-y for I in range(4):
a=20 print(“Hello world”)
b=10 func()
operation=diff Output: Hello World
print(operation(a,b)) Hello World
Output: Hello World
10 Hello World
Function
Python Functions
def Function_name(variable1, variable2, ..)
documentation string
statement block
return[expression]
Example:
def diff(x,y): def func():
return x-y for I in range(5):
a=20 print(“Hello world”)
b=10 func()
operation=diff Output: Hello World
print(operation(a,b)) Hello World
Output: Hello World
10 Hello World
Python
Required Arguments
Defining Functions
The arguments are passed to a function in correct positional order.
The number of arguments in the function call should exactly match with
the number of arguments specified in the function definition.
def display(): def display(str): def display(str):
print(“Hello”) print(str) print(str)
display(“Hi”) disaplay() str=“Hello”
display(str)
OUTPUT OUTPUT OUTPUT
TypeError: TypeError Hello
Python
Keyword Arguments
Defining Functions
The values are not assigned to arguments according to their position but
based on their name(or keyword.
Keyword arguments when used in function calls, helps the function to
identify the arguments by the parameter name.
First, if you skip arguments.
Second, if in the function call you change the order of parameters.
That is, in any order different from that specified in the function
definition.
def display(str, int_x, float_y):
print(“The string is : “,str)
print(“The Integer value is : “, int_x)
print(“The floating point value is : “, float_y)
display(floaat_y=56789,045, str=“Hello”, int_x=1234)
Python
Keyword Arguments
Defining Functions
def display(name, age, salary):
print(“Name: “, name)
print(“Age: “, age)
print(“Salary: “, salary)
Nn= “Aadi”
a=35
S=123456
Display(salary=s, name=n, age=a)
OUTPUT
Name: Aadi
Age: 35
Salary: 123456
Python
Default Arguments
Defining Functions
A default argument assumes a default value if a value is not provided in
the function call for that argument.
def display(name, course = “Btech”):
print(“Name : “ + name)
print(“Course : “, course)
display(course = “BCA”, name= “Arav”)
display(name=“Reyansh”)
OUTPUT
Name: Arav
Course: BCA
Name: Reyansh
Course: BTech
Python
Default Arguments
Defining Functions
A positional argument is assigned based on its position in the argument
list but a keyword argument is assigned based on parameter name.
def display(name, course = “BTech”, marks):
print(“Name : “ + name)
print(“Course : “, course)
print(“Marks :”, marks)
display(name=“Reyansh”, 90)
OUTPUT
Name: Arav
Course: BCA
Name: Reyansh
Course: BTech
Python
Variable-length Arguments
Defining Functions
The arbitrary number of arguments passed to the function basically forms
a tuple before being passed into the function.
Inside the called function, for loop is used to access the arguments.
The variable-length arguments if present in the function definition should
be the last in list of formal parameters.
Any formal parameters written after the variable-length arguments must
be keyword-only arguments.
def func(name, *fav_subjects):
print(“\n“, name, “likes to read “)
for subject in fav_subjects:
print(subject)
func(“Goransh”, “Mathematics”, “Android Programming”
Func(“Richa”, “C”, “Data Structures”, “Design and Analysis of Algorithms”)
Krish likes to read
Module
Python Modules
Modules are pre-written pieces of code that are use to perform common
tasks like generating random number, performing mathematical
operation, etc.
Module is a file with a .py extension that has definitions of all functions
and variables that you would like to use even in other programs.
The program in which you want to use function or variables defined in the
module will simply import that particular module.
The basic way to use a module is to add import module_name as the first
line of your program and then writing module_name.var to access
functions and values with the name var in the module.
Example:
import sys
print(“\n PYTHONPATH = \n ”,sys.path)
OUTPUT: PYTHONPATH=C:\\python34
Module
Python Modules
from math import pi
print(“Pi=“,+pi)
OUTPUT:
Pi=30141592653589793
To import more than one item from a module, use a comma separated
list.
from math import pi,sprt
You can also import a module with a different name using the as
keyword. This is particularly more important when a module either has a
long or confusing name.
from math import sqrt as square_root
print(square_root(81))
OUTPUT:
9.0
Module
Python Modules
Python also allows you to pass command line arguments to your
program. This an be done using the sys module. The argv variable in this
modules keeps a track of command line arguments passed to the .py
script.
Import sys
Print(sys.argv)
To execute this program code, go to command prompt and write
C:\Python34>python main.py Hello World
OUTPUT:
[‘main,py’,’Hello’,’World’]
Module
Python Modules
import sys
a=int(sys.argv[1])
b=int(sys.argv[2])
sum=a+b
print(“Sum=“,sum)
C:\Python34>python sum.py 3 4
OUTPUT:
Sum=7
MyModule.py
Python Modules
def display():
print(“Hello”)
print(“Name of called module is:”,__name__)
str=“Welcome to the world of Python!!!”
main.py
import MyModule
print(“MyModule str=“,MyModule.str)
MyModule.display()
print(“Name of calling module is:”,__name__)
OUTPUT:
MyModule str=Welcome to the world of Python!!!
Hello
Name of called module is: MyModule
Name of calling module is: __main__
MyModule.py
Python Modules
def large(a,b):
if(a>b):
return a
else:
return b
find.py
import MyModule
print(“Large(50,100)=“,MyModule.large(50,100))
print(“Large(‘B’,’C’)=“,MyModule.large(‘B’,’C’))
Print(“Large(‘HI’,’BI’)=“,MyModule.large(‘HI’,’BI’))
OUTPUT:
Large(50,100)=100
Large(‘B’,”C’)=C
Large(‘HI’,’BI’)=HI
Advantage:
Python Modules
Python modules provide all the benefits of modular software design.
These modules provide services and functionality that can be resued in
other program.
Even the standard liabraby of python contains a set of modules.
It allows you to logically organize the code so that it becomes easier to
understand and use.
Key points to remember:
A modules can import other modules
It is customary but not mandatory to place all import statements at the
beginning of a module.
A module is loaded only once, irrespective of the number of times it is
imported.
Python
Modules and Namespaces:
Modules
module1.py:
def repeat_x(x):
return x*2
module1.py:
def repeat_x(x):
return X**2
import module1
import module2
result-=repeat_x(10)
Import module1
Import module2
Result1=module1.repeat_x(10)
Result2=module2.repeat_x(10)
Python
Modules and Namespaces:
Modules
module1.py:
import math
def cube(x):
return x**3
a=-100
print(“a=“,a)
a=abs(a)
print(“abs(a)=“,a)
print(“Square root of a”,a,”=“,math.sqrt(a))
print(“Cube of”,a,”=“,cube(a))
OUTPUT
a=-100
abs(a)=100
Square root of 100=10.0 Cube of 100=1000000
Packages:
Python Packages
A package is ahierarchical file directory structure that has modules and
other packages within it.
Every package in python is a directory which must have a special file
called __init__.py.
This file may not even have a single line of code. It is siimply added to
indicate that this package in the same way as you import any module.
To create a package called MyPackage, create a directory called
MyPackage having the module MuModule and the __init__.py file.
To use MyModule in a program, you must first import it. This can be
done in two ways.
import MyPackage.MyModule
or
from MyPackage import MyModule
Python
Packages:
Documentation Strings
Docstrings serve the same purpose as that of comments, as they are
designed to explain code.
They are created by putting a multiline string to explain the function.
The first statement of the function body can optionally be a string literal
which is alos known as documentation string, or docsting.
Docstrings are important as they help tools to automatically generate
online or printed documentation.
It also helps users and readers of the code to interactively browse
through code.
def func():
“””The program just prints a message.
It will display Hello world !!!”””
print(“Hello World!!!”)
print(func.__doc__)