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

python (1)

Uploaded by

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

python (1)

Uploaded by

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

UNIT – I

Parts Python Programming Language

Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our
programs. There are certain online interpreters like https://ide.geeksforgeeks.org/,
http://ideone.com/ or http://codepad.org/ that can be used to start Python without installing
an interpreter.
Windows: There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) which is installed when you install the python
software from
http://python.org/downloads/

Identifiers: Any name that is used to define a class, function, variable module, or object is
an identifier.
Rules for Python identifiers:

• A identifiers name must start with a letter or the underscore character

• A identifiers name cannot start with a number

• A identifiers name can only contain alpha-numeric characters and underscores (A-z, 0-
9,and _ )

Keywords : it is a pre-defined word or reserved word is also known as keyword.

Eg:- int, float, class, string, double, long, short, static, if, else, while, for, def……..etc.

Variables:

Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.

Rules for Python variables:


• A variable name must start with a letter or the underscore character

• A variable name cannot start with a number

• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )

• Variable names are case-sensitive (age, Age and AGE are three different variables)

Assigning Values to Variables:

Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.

For example −

a= 100 # An integer assignment

b = 1000.0 # A floating point

c = "John" # A string

print (a)

print (b)

print (c)

This produces the following result −

100

1000.0

John

Multiple Assignment:

Python allows you to assign a single value to several variables simultaneously.

For example :
a=b=c=1

Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.

For example −

a,b,c = 1,2,"PIMS“

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.

Output Variables:

The Python print statement is often used to output variables.

Variables do not need to be declared with any particular type and can even change type after
they have been set.
x=5 # x is of type int
x = "PIMS” # x is now of type str
print(x)

Output: PIMS

To combine text and a variable, Python uses the “+” character:

Example

x = "awesome"
print("Python is " + x)

Output

Python is awesome

You can also use the + character to add a variable to another variable:

Example

x = "Python is "
y = "awesome"
z=x+y
print(z)

Output:
Python is awesome

Statements:

A statement is an instruction that the Python interpreter can execute. We have normally two
basic statements, the assignment statement and the print statement. Some other kinds of
statements that are if statements, while statements, and for statements generally called as
control flows.

Examples:

An assignment statement creates new variables and gives them values:

>>> x=10

>>> college="PIMS"

An print statement is something which is an input from the user, to be printed / displayed on
to the screen (or ) monitor.

>>> print("PIMS colege")

PIMS college

Expressions:

An expression is a combination of values, variables, and operators. An expression is


evaluated using assignment operator.

Examples: Y=x + 17

>>> x=10

>>> z=x+20

>>> z

30

>>> x=10
>>> y=20

>>> c=x+y

>>> c

30

A value all by itself is a simple expression, and so is a variable.

>>> y=20

>>> y

20

Python also defines expressions only contain identifiers, literals, and operators.

Some of the python expressions are:

Generator expression:

Syntax: ( compute(var) for var in iterable )

>>> x = (i for i in 'abc') #tuple comprehension


>>> x
<generator object <genexpr> at 0x033EEC30>

>>> print(x)
<generator object <genexpr> at 0x033EEC30>

You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE.

Conditional expression:

Syntax: true_value if Condition else false_value

>>> x = "1" if True else "2"


>>> x

'1'

Operators: In Python you can implement the following operations using the corresponding
tokens.

Operator Token

addition +

subtraction -

multiplication *

Integer Division /

remainder %

Binary left shift <<

Binary right shift >>

and &

or \

Less than <

Greater than >

Less than or equal to <=


Greater than or equal to >=

Check equality ==

Check not equal !=

Precedence of Operators:

Operator precedence affects how an expression is evaluated.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first multiplies 3*2 and then adds into 7.

Example 1:

>>> 3+4*2

11

Multiplication gets evaluated before the addition operation

>>> (10+10)*2

40

Parentheses () overriding the precedence of the arithmetic operators

Example 2:
a = 20
b = 10
c = 15
d=5
e=0

e = (a + b) * c / d #( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ", e)

e = ((a + b) * c) / d # (30 * 15 ) / 5
print("Value of ((a + b) * c) / d is ", e)

e = (a + b) * (c / d); # (30) * (15/5)


print("Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d; # 20 + (150/5)
print("Value of a + (b * c) / d is ", e)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/opprec.py
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0

Data types:

The data stored in memory can be of many types. For example, a student roll number is
stored as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them and
the storage method for each of them.

Int:

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited


length.

>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:

>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>

Float:

Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.

Float can also be scientific numbers with an "e" to indicate the power of 10.

>>> y=2.8
>>> y
2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
>>> type(.4)
<class 'float'>
>>> 2.

2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))

Output:

<class 'float'>
<class 'float'>
<class 'float'>

Boolean:

Objects of Boolean type may have one of two values, True or False:

>>> type(True)

<class 'bool'>

>>> type(False)

<class 'bool'>

String:

1. Strings in Python are identified as a contiguous set of characters represented in the


quotation marks. Python allows for either pairs of single or double quotes.

• 'hello' is the same as "hello".

• Strings can be output to screen using the print function. For example: print("hello").

>>> print("PIMS college")

PIMS college

>>> type("PIMS college")

<class 'str'>

>>> print('PIMS college')

PIMS college
>>> " "

''
If you want to include either type of quote character within the string, the simplest way is to
delimit the string with the other type. If a string is to contain a single quote, delimit it with
double quotes and vice versa:

>>> print("PIMS is an autonomous (') college")

PIMS is an autonomous (') college

>>> print('PIMS is an autonomous (") college')

PIMS is an autonomous (") college

Suppressing Special Character:

Specifying a backslash (\) in front of the quote character in a string “escapes” it and causes
Python to suppress its usual special meaning. It is then interpreted simply as a literal single
quote character:

>>> print("PIMS is an autonomous (\') college")

PIMS is an autonomous (') college

>>> print('PIMS is an autonomous (\") college')

PIMS is an autonomous (") college

The following is a table of escape sequences which cause Python to suppress the usual
special interpretation of a character in a string:

>>> print('a\
....b')
a... b
>>> print('a\
b\
c')

abc
>>> print('a \n b')
a
b
>>> print("PIMS \n college")
PIMS
college

Escape Usual Interpretation of


Sequence Character(s) After Backslash “Escaped” Interpretation
\' Terminates string with single quote opening delimiter Literal single quote (') character
\" Terminates string with double quote opening delimiter Literal double quote (") character
\newline Terminates input line Newline is ignored
\\ Introduces escape sequence Literal backslash (\) character

In Python (and almost all other common computer languages), a tab character can be
specified by the escape sequence \t:

>>> print("a\tb")
a b
List:

• It is a general purpose most widely used in data structures


• List is a collection which is ordered and changeable and allows duplicate members.
(Grow and shrink as needed, sequence type, sortable).
• To use a list, you must declare it first. Do this using square brackets and separate
values with commas.
• We can construct / create list in many ways.
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

>>> x=list()
>>> x
[]
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]

Indentation
Indentation is one of the greatest features in python

Comments:

Single-line comments begins with a hash(#) symbol and is useful in mentioning that the
whole line should be considered as a comment until the end of line.

A Multi line comment is useful when we need to comment on many lines. In python, triple
double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.

Example:

Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/comm.py 30

Reading input and print output:


#reading input:
x=int(input(“enter the value for x”))
y=int(input(“enter the value for y”))
#print output
print(the value of x=”,x)
print(the value of y=”,y)

type() function: it is used to find type of a variable


eg:a=10
type(a)
<class ‘int’>

Control Flow, Loops:

Boolean Values and Operators:


A boolean expression is an expression that is either true or false. The following examples
use the operator ==, which compares two operands and produces True if they are equal and
False otherwise:

>>> 5 == 5

True

>>> 5 == 6

False

True and False are special values that belong to the type bool; they are not strings:

>>> type(True)

<class 'bool'>

>>> type(False)

<class 'bool'>

The == operator is one of the relational operators; the others are: x != y # x is not equal to y

x > y # x is greater than y x < y # x is less than y


x >= y # x is greater than or equal to y x <= y # x is less than or equal to y

Note:

All expressions involving relational and logical operators will evaluate to either true or false

Conditional (if):

The if statement contains a logical expression using which data is compared and a decision
is made based on the result of the comparison.

Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of
code after the end of the if statement(s) is executed.

if Statement Flowchart:

Fig: Operation of if statement

Example: Python if Statement

a=int(input(“enter the value of a”))

b=int(input(“enter the value of b”))

c=int(input(“enter the value of c”))


large=a

if(b>large):

large=b

if(c>large):

large=c

print(“the largest of a, b, c is”, large)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python310/if.py
Enter the value for a
5
Enter the value for b
8
Enter the value for c
10
The Largest of a, b, c is 10.

Alternative if (If-Else):

An else statement can be combined with an if statement. An else statement contains the
block of code (false block) that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at most only one else
Statement following if.

Syntax of if - else :

if test expression:
Body of if statements
else:
Body of else statements

If - else Flowchart :
Fig: Operation of if – else statement

Example of if - else:

n=int(input(“enter the value for n”))

if(n%2==0):

print(“the given number is even”)

else:

print(“the given number is odd”)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python310/ifelse.py
enter the value for n
2
The given number is even

Chained Conditional: (If-elif-else):

The elif statement allows us to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE. Similar to the else,
the elif statement is optional. However, unlike else, for which there can be at most one
statement, there can be an arbitrary number of elif statements following an if.
Syntax of if – elif - else :

If test expression:
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts

Flowchart of if – elif - else:

Fig: Operation of if – elif - else statement

Example of if - elif – else:

p=float(input(“enter your percentage”))

if(p>85):

print(“the result is distinction”)

elif(p>60):

print(“the result is first class”)

elif(p>50):

print(“the result is second class”)

elif(p>40):
print(“the result is pass”)

else:

print(“the result is fail”)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python310/ifelif.py
enter your percentage
89
The result is distinction

Iteration:
A loop statement allows us to execute a statement or group of statements multiple times as
long as the condition is true. Repeated execution of a set of statements with the help of loops
is called iteration.
Loops statements are used when we need to run same code again and again, each time with a
different value.

Statements:
In Python Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
3. Nested For Loops
While loop:

• Loops are either infinite or conditional. Python while loop keeps reiterating a block of
code defined inside it until the desired condition is met.
• The while loop contains a boolean expression and the code inside the loop is
repeatedly executed as long as the boolean expression is true.
• The statements that are executed inside while can be a single line of code or a block of
multiple statements.
Syntax:

while(expression):
Statement(s)
Flowchart:

Example Programs:

n=int(input(“enter the value of n”))


sum=0
i=1
while(i<=n):
sum=sum+i
i=i+1
print(“the sum of natural number=”,sum)

output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python310/whi.py
Enter the value of n 5
15

For loop:

Python for loop is used for repeated execution of a group of statements for the desired
number of times. It iterates over the items of lists, tuples, strings, the dictionaries and other
iterable objects

Syntax: for var in sequence:


Statement(s) A sequence of values assigned to var in each iteration
Holds the value of item
in sequence in each iteration
Sample Program:

numbers = [1, 2, 4, 6, 11, 20]


seq=0
for val in numbers:
seq=val*val
print(seq)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python310/fr.py
1
4
16
36
121
400

Flowchart:
Iterating over a list:

#list of items
list = ['M','R','C','E','T']
i=1

#Iterating over the list


for item in list:
print ('college ',i,' is ',item)
i = i+1

Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/lis.py
college 1 is M
college 2 is R
college 3 is C
college 4 is E
college 5 is T

Iterating over a Tuple:

tuple = (2,3,5,7)
print ('These are the first four prime numbers ')
#Iterating over the tuple
for a in tuple:
print (a)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fr3.py
These are the first four prime numbers
2
3
5
7

Iterating over a dictionary:

#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}

#Iterating over the dictionary to print keys


print ('Keys are:')
for keys in college:
print (keys)

#Iterating over the dictionary to print values


print ('Values are:')
for blocks in college.values():
print(blocks)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/dic.py
Keys are:
ces
it
ece
Values are:
block1
block2
block3

Iterating over a String:

#declare a string to iterate over


college = 'PIMS'

#Iterating over the string


for name in college:
print (name)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/strr.py M
R
C
E
T

Nested For loop:


When one Loop defined within another Loop is called Nested Loops.
Syntax:
for val in sequence:
for val in sequence:
statements
statements

# Example 1 of Nested For Loops (Pattern Programs)


for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')
Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/nesforr.py

1
22
333
4444
55555

# Example 2 of Nested For Loops (Pattern Programs)

for i in range(1,6):

for j in range(5,i-1,-1):

print(i, end=" ")

print('')

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/nesforr.py

Output:
11111

2222

333

44
Break and continue:

In Python, break and continue statements can alter the flow of a normal loop. Sometimes
we wish to terminate the current iteration or even the whole loop without checking test
expression. The break and continue statements are used in these cases.

Break:

The break statement terminates the loop containing it and control of the program flows to
the statement immediately after the body of the loop. If break statement is inside a nested
loop (loop inside another loop), break will terminate the innermost loop.

Flowchart:

The following shows the working of break statement in for and while loop:

for var in sequence:


# code inside for loop
If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop
while test expression

# code inside while loop


If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop

Example:

for val in "PIMS COLLEGE": if


val == " ":
break
print(val)

print("The end")

Output:

M
R
C
E
T
The end

# Program to display all the elements before number 88

for num in [11, 9, 88, 10, 90, 3, 19]:


print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break

Output:
11
9
88
The number 88 is found
Terminating the loop

#
for letter in "Python": # First Example
if letter == "h":
break
print("Current Letter :", letter )

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/br.py =Current

Letter : P

Current Letter : y

Current Letter : t

Continue:

The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Flowchart:

The following shows the working of break statement in for and while loop:
for var in sequence:
# code inside for loop
If condition:
continue (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop

while test expression

# code inside while loop


If condition:
continue(if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop

Example:

# Program to show the use of continue statement inside loops

for val in "string":


if val == "i":
continue
print(val)

print("The end")

Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/cont.py
s
t
r
n
g
The end

# program to display only odd numbers

for num in [20, 11, 9, 66, 4, 89, 44]:


# Skipping the iteration when number is even
if num%2 == 0:
continue
# This statement will be skipped for all even numbers
print(num)

Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/cont2.py 11
9
89

#
for letter in "Python": # First Example
if letter == "h":
continue
print("Current Letter :", letter)
Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/con1.py
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n

Functions:

Functions and its use: Function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable. It avoids repetition and
makes code reusable.

Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.

Ex: abs(),all().ascii(),bool()………so on….


integer = -20

print('Absolute value of -20 is:', abs(integer))

Output:

Absolute value of -20 is: 20

2. User-defined functions - Functions defined by the users themselves.

def add_numbers(x,y):
sum = x + y
return sum

print("The sum is", add_numbers(5, 20))

Output:

The sum is 25

Modules:

Modules: Python module can be defined as a python program file which contains a python
code including python functions, class, or variables. In other words, we can say that our
python code file saved with the extension (.py) is treated as the module. We may have a
runnable code inside the python module. A module in Python provides us the flexibility to
organize the code in a logical way. To use the functionality of one module into another, we
must have to import the specific module.

Syntax:

import <module-name>

Every module has its own functions, those can be accessed with . (dot)

Note: In python we have help ()

Enter the name of any module, keyword, or topic to get help on writing Python programs
and using Python modules. To quit this help utility and return to the interpreter, just type
"quit".

Some of the modules like os, date, and calendar so on……

>>> import sys


>>> print(sys.version)
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
>>> print(sys.version_info)
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
>>> print(calendar.month(2021,5))

>>> print(calendar.isleap(2020))
True
>>> print(calendar.isleap(2017))
False
Parameters:

Parameters are passed during the definition of function while Arguments are passed during
the function call.

Example:
#here a and b are parameters

def add(a,b): #//function definition


return a+b

#12 and 13 are arguments


#function call
result=add(12,13)
print(result)

Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/paraarg.py 25

Some examples on functions:

# To display vandemataram by using function use no args no return type


#function defination
def display():
print("vandemataram")
print("i am in main")

#function call
display()
print("i am in main")

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py i
am in main
vandemataram
i am in main

#Type1 : No parameters and no return type

def Fun1() :
print("function 1")
Fun1()

Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py

function 1

#Type 2: with param with out return type

def fun2(a) :
print(a)
fun2("hello")

Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py

Hello

#Type 3: without param with return type


def fun3():
return "welcome to python"
print(fun3())
Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py

welcome to python

#Type 4: with param with return type

def fun4(a):
return a
print(fun4("python is better then c"))

Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py

python is better then c

Arguments:

There are three types of Python function arguments using which we can call a function.

1. Default Arguments
2. Keyword Arguments
3. Variable-length Arguments

Syntax:
def functionname():
statements
.
.
.
functionname()

Function definition consists of following components:

1. Keyword def indicates the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules of writing
identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must have
same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Example:

def hf():

hello world

hf()

In the above example we are just trying to execute the program by calling the function. So it
will not display any error and no output on to the screen but gets executed.

To get the statements of function need to be use print().

#calling function in python:

def hf():

print("hello world")

hf()

Output:

hello world

def hf():

print("hw")

print("gh kfjg 66666")

hf()

hf()
hf()

Output:

hw
gh kfjg 66666
hw
gh kfjg 66666
hw
gh kfjg 66666

def add(x,y):

c=x+y

print(c)

add(5,4)

Output:

def add(x,y):

c=x+y

return c

print(add(5,4))

Output:

def add_sub(x,y):

c=x+y

d=x-y

return c,d

print(add_sub(10,5))
Output:

(15, 5)

The return statement is used to exit a function and go back to the place from where it was
called. This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.

def hf():

return "hw"

print(hf())

Output:
hw

def hf():

return "hw"

hf()

Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu.py

>>>

def hello_f():

return "hellocollege"

print(hello_f().upper())

Output:

HELLOCOLLEGE

# Passing Arguments
def hello(wish):

return '{}'.format(wish)

print(hello("PIMS"))

Output:

PIMS

Here, the function wish() has two parameters. Since, we have called this function with two
arguments, it runs smoothly and we do not get any error. If we call it with different number
of arguments, the interpreter will give errors.

def wish(name,msg):

"""This function greets to

the person with the provided message"""

print("Hello",name + ' ' + msg)

wish("PIMS","Good morning!")

Output:

Hello PIMS Good morning!


Below is a call to this function with one and no arguments along with their respective error
messages.

>>> wish("PIMS") # only one argument


TypeError: wish() missing 1 required positional argument: 'msg'
>>> wish() # no arguments
TypeError: wish() missing 2 required positional arguments: 'name' and 'msg'

def hello(wish,hello):

return “hi” '{},{}'.format(wish,hello)

print(hello("PIMS","college"))
Output:

hiPIMS,college

#Keyword Arguments

When we call a function with some values, these values get assigned to the arguments
according to their position.

Python allows functions to be called using keyword arguments. When we call functions in
this way, the order (position) of the arguments can be changed.

(Or)

If you have some functions with many parameters and you want to specify only some
of them, then you can give values for such parameters by naming them - this is
called keyword arguments - we use the name (keyword) instead of the position
(which we have been using all along) to specify the arguments to the function.

There are two advantages - one, using the function is easier since we do not need to
worry about the order of the arguments. Two, we can give values to only those
parameters which we want, provided that the other parameters have default argument
values.

def func(a, b=5, c=10):


print 'a is', a, 'and b is', b, 'and c is', c

func(3, 7)
func(25, c=24)
func(c=50, a=100)

Output:

a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

Note:

The function named func has one parameter without default argument values,
followed by two parameters with default argument values.
In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the
value 5 and c gets the default value of 10.

In the second usage func(25, c=24), the variable a gets the value of 25 due to the
position of the argument. Then, the parameter c gets the value of 24 due to naming i.e.
keyword arguments. The variable b gets the default value of 5.

In the third usage func(c=50, a=100), we use keyword arguments completely to


specify the values. Notice, that we are specifying value for parameter c before that
for a even though a is defined before c in the function definition.

For example: if you define the function like below

def func(b=5, c=10,a): # shows error : non-default argument follows default argument

def print_name(name1, name2):

""" This function prints the name """

print (name1 + " and " + name2 + " are friends")

#calling the function

print_name(name2 = 'A',name1 = 'B')


Output:

B and A are friends

#Default Arguments

Function arguments can have default values in Python.

We can provide a default value to an argument by using the assignment operator (=)

def hello(wish,name='you'):

return '{},{}'.format(wish,name)

print(hello("good morning"))

Output:
good morning,you
def hello(wish,name='you'):

return '{},{}'.format(wish,name) //print(wish + ‘ ‘ + name)

print(hello("good morning","nirosha")) // hello("good morning","nirosha")

Output:
good morning,nirosha // good morning nirosha

Note: Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.

This means to say, non-default arguments cannot follow default arguments. For example, if
we had defined the function header above as:

def hello(name='you', wish):

Syntax Error: non-default argument follows default argument

def sum(a=4, b=2): #2 is supplied as default argument


""" This function will print sum of two numbers

if the arguments are not supplied

it will add the default value """

print (a+b)

sum(1,2) #calling with arguments

sum( ) #calling without arguments

Output:

Variable-length arguments
Sometimes you may need more arguments to process function then you mentioned in the
definition. If we don’t know in advance about the arguments needed in function, we can use
variable-length arguments also called arbitrary arguments.

For this an asterisk (*) is placed before a parameter in function definition which can hold
non-keyworded variable-length arguments and a double asterisk (**) is placed before a
parameter in function which can hold keyworded variable-length arguments.

If we use one asterisk (*) like *var, then all the positional arguments from that point till the
end are collected as a tuple called ‘var’ and if we use two asterisks (**) before a variable like
**var, then all the positional arguments from that point till the end are collected as
a dictionary called ‘var’.

def wish(*names):
"""This function greets all
the person in the names tuple."""

# names is a tuple with arguments


for name in names:
print("Hello",name)

wish("PIMS","CSE","SIR","MADAM")

Output:

Hello PIMS
Hello CSE
Hello SIR
Hello MADAM

#Program to find area of a circle using function use single return value function with
argument.

pi=3.14
def areaOfCircle(r):

return pi*r*r
r=int(input("Enter radius of circle"))
print(areaOfCircle(r))

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter radius of circle 3
28.259999999999998

#Program to write sum different product and using arguments with return value
function.

def calculete(a,b):

total=a+b

diff=a-b

prod=a*b

div=a/b

mod=a%b

return total,diff,prod,div,mod

a=int(input("Enter a value"))

b=int(input("Enter b value"))

#function call

s,d,p,q,m = calculete(a,b)

print("Sum= ",s,"diff= ",d,"mul= ",p,"div= ",q,"mod= ",m)

#print("diff= ",d)

#print("mul= ",p)

#print("div= ",q)

#print("mod= ",m)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value 6
Sum= 11 diff= -1 mul= 30 div= 0.8333333333333334 mod= 5

#program to find biggest of two numbers using functions.

def biggest(a,b):
if a>b :
return a
else :
return b

a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
big= biggest(a,b)
print("big number= ",big)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value-2
big number= 5

Local and Global scope:

Local Scope:

A variable which is defined inside a function is local to that function. It is accessible from
the point at which it is defined until the end of the function, and exists for as long as the
function is executing

Global Scope:

A variable which is defined in the main body of a file is called a global variable. It will be
visible throughout the file, and also inside any file which imports that file.

• The variable defined inside a function can also be made global by using the global
statement.

def function_name(args):
.............
global x #declaring global variable inside a function
..............

# create a global variable


x = "global"

def f():
print("x inside :", x)

f()
print("x outside:", x)

Output:

C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py x

inside : global

x outside: global

# create a local variable

def f1():

y = "local"

print(y)

f1()

Output:
local

• If we try to access the local variable outside the scope for example,

def f2():
y = "local"

f2()
print(y)
Then when we try to run it shows an error,

Traceback (most recent call last):


File "C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py", line6,
in <module>
print(y)
NameError: name 'y' is not defined

The output shows an error, because we are trying to access a local variable y in a global
scope whereas the local variable only works inside f2() or local scope.

# use local and global variables in same code

x = "global"

def f3():
global x
y = "local"
x=x*2
print(x)
print(y)

f3()

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
globalglobal
local

• In the above code, we declare x as a global and y as a local variable in the f3(). Then,
we use multiplication operator * to modify the global variable x and we print
both x and y.
• After calling the f3(), the value of x becomes global global because we used the x *
2 to print two times global. After that, we print the value of local variable y i.e local.

# use Global variable and Local variable with same name

x=5

def f4():
x = 10
print("local x:", x)

f4()
print("global x:", x)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
local x: 10
global x: 5

Command line arguments:

The command line arguments must be given whenever we want to give the input before the
start of the script, while on the other hand, raw_input() is used to get the input while the
python program / script is running.

The command line arguments in python can be processed by using either ‘sys’ module,
‘argparse’ module and ‘getopt’ module.

‘sys’ module :

Python sys module stores the command line arguments into a list, we can access it
using sys.argv. This is very useful and simple way to read command line arguments as
String.
sys.argv is the list of commandline arguments passed to the Python program. argv represents
all the items that come along via the command line input, it's basically an array holding the
command line arguments of our program

>>> sys.modules.keys() -- this prints so many dict elements in the form of list.

# Python code to demonstrate the use of 'sys' module for command line arguments

import sys

# command line arguments are stored in the form


# of list in sys.argv
argumentList = sys.argv
print(argumentList)

# Print the name of file


print(sys.argv[0])
# Print the first argument after the name of file
#print(sys.argv[1])

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py

['C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py']
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py
Note: Since my list consist of only one element at ‘0’ index so it prints only that list
element, if we try to access at index position ‘1’ then it shows the error like,

IndexError: list index out of range

import sys

print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/symod.py ==
<class 'list'>
The command line arguments are:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/symod.py

# write a python program to get python version.


import sys
print("System version is:")
print(sys.version)
print("Version Information is:")
print(sys.version_info)

Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/pyyy/s1.py =System
version is:
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
Version Information is:
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)

‘argparse’ module :
Python getopt module is very similar in working as the C getopt() function for parsing
command-line parameters. Python getopt module is useful in parsing command line
arguments where we want user to enter some options too.

>>> parser = argparse.ArgumentParser(description='Process some integers.')

#
import argparse

parser = argparse.ArgumentParser()
print(parser.parse_args())

‘getopt’ module :

Python argparse module is the preferred way to parse command line arguments. It provides a
lot of option such as positional arguments, default value for arguments, help message,
specifying data type of argument etc

It parses the command line options and parameter list. The signature of this function is
mentioned below:

getopt.getopt(args, shortopts, longopts=[ ])

• args are the arguments to be passed.


• shortopts is the options this script accepts.
• Optional parameter, longopts is the list of String parameters this function accepts
which should be supported. Note that the -- should not be prepended with option
names.

-h ------------ print help and usage message


-m ----------- accept custom option value
-d ------------ run the script in debug mode

import getopt
import sys

argv = sys.argv[0:]
try:
opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
#print(opts)
print(args)
except getopt.GetoptError:
# Print a message or do something useful
print('Something went wrong!')
sys.exit(2)
Output:
C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/gtopt.py ==

['C:/Users/PIMS/AppData/Local/Programs/Python/Python38-32/gtopt.py']

Strings:
A string is a group/ a sequence of characters. Since Python has no provision for arrays,
we simply use strings. This is how we declare a string. We can use a pair of single or
double quotes. Every string object is of the type ‘str’.

>>> type("name")
<class 'str'>
>>> name=str()
>>> name
''
>>> a=str('PIMS')
>>> a
'PIMS'
>>> a=str(PIMS)
>>> a[2]
'c'
>>> fruit = 'banana'
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter. The
expression in brackets is called an index. The index indicates which character in the
sequence we want

String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0
in the beginning of the string and working their way from -1 at the end.

Slice out substrings, sub lists, sub Tuples using index.

Syntax:[Start: stop: steps]

• Slicing will start from index and will go up to stop in step of steps.
• Default value of start is 0,
• Stop is last index of list
• And for step default is 1

For example 1−

str = 'Hello World!'

print str # Prints complete string

print str[0] # Prints first character of the string

print str[2:5] # Prints characters starting from 3rd to 5th

print str[2:] # Prints string starting from 3rd character print

str * 2 # Prints string two times

print str + "TEST" # Prints concatenated string

Output:

Hello World!

H
llo

llo World!

Hello World!Hello World!

Hello World!TEST

Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'

String functions and methods:

There are many methods to operate on String.

S.no Method name Description


1. isalnum() Returns true if string has at least 1 character and all
characters are alphanumeric and false otherwise.
2. isalpha() Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise.
3. isdigit() Returns true if string contains only digits and false
otherwise.
4. islower() Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false
otherwise.
5. isnumeric() Returns true if a string contains only numeric
characters and false otherwise.
6. isspace() Returns true if string contains only whitespace
characters and false otherwise.
7. istitle() Returns true if string is properly “titlecased” and
false otherwise.
8. isupper() Returns true if string has at least one cased character and all
cased characters are in uppercase
and false otherwise.
9. replace(old, new Replaces all occurrences of old in string with new
[, max]) or at most max occurrences if max given.
10. split() Splits string according to delimiter str (space if not
provided) and returns list of substrings;
11. count() Occurrence of a string in another string
12. find() Finding the index of the first occurrence of a string
in another string
13. swapcase() Converts lowercase letters in a string to uppercase
and viceversa
14. startswith(str, Determines if string or a substring of string (if starting index
beg=0,end=le beg and ending index end are given) starts with substring str;
n(string)) returns true if so and false
otherwise.

Note:
All the string methods will be returning either true or false as the result

1. isalnum():
Isalnum() method returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

Syntax:
String.isalnum()

Example:
>>> string="123alpha"
>>> string.isalnum() True

2. isalpha():
isalpha() method returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.

Syntax:
String.isalpha()

Example:
>>> string="nikhil"
>>> string.isalpha()
True

3. isdigit():
isdigit() returns true if string contains only digits and false otherwise.

Syntax:
String.isdigit()

Example:
>>> string="123456789"
>>> string.isdigit()
True

4. islower():
Islower() returns true if string has characters that are in lowercase and false otherwise.

Syntax:
String.islower()

Example:
>>> string="nikhil"
>>> string.islower()
True

5. isnumeric():
isnumeric() method returns true if a string contains only numeric characters and false
otherwise.

Syntax:
String.isnumeric()

Example:
>>> string="123456789"
>>> string.isnumeric()
True

6. isspace():
isspace() returns true if string contains only whitespace characters and false otherwise.

Syntax:
String.isspace()

Example:
>>> string=" "
>>> string.isspace()
True

7. istitle()
istitle() method returns true if string is properly “titlecased”(starting letter of each word is
capital) and false otherwise

Syntax:
String.istitle()

Example:
>>> string="Nikhil Is Learning"
>>> string.istitle()
True

8. isupper()
isupper() returns true if string has characters that are in uppercase and false otherwise.

Syntax:
String.isupper()

Example:
>>> string="HELLO"
>>> string.isupper()
True

9. replace()
replace() method replaces all occurrences of old in string with new or at most max
occurrences if max given.

Syntax:
String.replace()

Example:
>>> string="Nikhil Is Learning"
>>> string.replace('Nikhil','Neha')
'Neha Is Learning'

10. split()
split() method splits the string according to delimiter str (space if not provided)

Syntax:
String.split()

Example:
>>> string="Nikhil Is Learning"
>>> string.split()
['Nikhil', 'Is', 'Learning']

11. count()
count() method counts the occurrence of a string in another string Syntax:
String.count()

Example:
>>> string='Nikhil Is Learning'
>>> string.count('i')
3

12. find()
Find() method is used for finding the index of the first occurrence of a string in another
string

Syntax:
String.find(„string‟)

Example:
>>> string="Nikhil Is Learning"
>>> string.find('k')
2
13. swapcase()
converts lowercase letters in a string to uppercase and viceversa

Syntax:
String.find(„string‟)

Example:
>>> string="HELLO"
>>> string.swapcase()
'hello'

14. startswith()
Determines if string or a substring of string (if starting index beg and ending index end are
given) starts with substring str; returns true if so and false otherwise.

Syntax:
String.startswith(„string‟)

Example:
>>> string="Nikhil Is Learning"
>>> string.startswith('N')
True

15. endswith()
Determines if string or a substring of string (if starting index beg and ending index end are
given) ends with substring str; returns true if so and false otherwise.
Syntax:
String.endswith(„string‟)

Example:
>>> string="Nikhil Is Learning"
>>> string.startswith('g')
True
PYTHON PROGRAMMING III YEAR/II SEM PIMS

58

You might also like