Python Basics (Notes)
Python Basics (Notes)
Python Basics (Notes)
(c) In this type of approach there is no straight forward defined path which we can
follow to solve a problem.
(d) We need to build that path based on trial and error.
(e) In this approach experience and knowledge is very important.
Problem Definition:
Before a program is written for solving a problem, it is important to define the
problem clearly.
Define problem: Problem is defined as a situation or issue or condition
which needs to solve to achieve the goal.
For most of the software projects, the system analyst approach system
users to collect user requirements and define the problem that the system
aims to solve.
System analyst typically looks at following issues:
o What input is required for achieving expected output?
o Expected output of the problem.
o Current method of solving the problem.
o Can the problem or part of the problem be more effectively solved by a
software solution?
o Computers are built to deal with algorithmic solutions, which are often
difficult or very time consuming for humans.
3
PPS Unit-I DIT,Pimpri
Solution:
o Solution means the instructions listed during problem solving – the instructions
that must be followed to produce the best results.
o The result may be: More efficient, faster, more understandable or reusable.
Results:
o The result is outcome or the completed computer assisted answer.
o May take any form: Printout, updated files, output to monitor speakers, etc.
Program:
o Program is the set of instructions that make up the solution after they have been
coded into a particular computer language.
4
PPS Unit-I DIT,Pimpri
5
PPS Unit-I DIT,Pimpri
Divides a problem into smaller units and then Starts from solving small modules and
solve it. adding them up together.
Structured programming languages such as C use OOP languages like C++ and Java,
top-down approach. etc. uses bottom-up mechanism.
6
PPS Unit-I DIT,Pimpri
7
PPS Unit-I DIT,Pimpri
Requirement Analysis: In this phase, the user’s expectations are gathered to know
why the software has to be built. The gathered requirements are analyzed to
decide scope of software. The last activity in this phase includes documenting
every identified requirement of the users in order to avoid any doubts regarding
functionality of software. The functionality, capability, performance and
availability of hardware and software components are all analyzed in this phase.
Testing: In this phase all modules are tested together to ensure that the overall
system works well as a whole product. In this phase the software is tested using a
large number of varied inputs, also known as test data, to ensure the software is
working as expected by user’s requirements.
Software development, training and support: After the code is tested and the
software or the program has been approved by the users, it is installed or
deployed in the production environment. In this phase it becomes very crucial to
have training classes for users of software.
8
PPS Unit-I DIT,Pimpri
Maintenance: Maintenance and enhancement are ongoing activities that are done
to cope with newly discovered problems or new requirements. Such activities
may take a long time to complete as the requirement may call for the addition of
new code that does not fit original design or an extra piece of code, required to fix
an unforeseen problem.
1. Algorithm
2. Flowchart
3. Pseudocode
Q.7. Discuss algorithm with example. Also enlist characteristics of good algorithm.
Ans:
Definition of algorithm
o An algorithm is precise, step-by-step set of instructions for solving a
computational problem.
o It is a set of ordered instructions which are written in simple English
language.
o In this type of problem solving the required input and expected outputs
are identified and according to that the processing will be done.
o Algorithms helps the programmer to write actual logic of a problem on
paper and validate it with the help of paper and pencil, and correct it if
any fault is noticed.
Characteristics of algorithms:
Precision: The instructions should be written in a precise manner.
Uniqueness: The outputs of each step should be unambiguous, i.e., they
should be unique and only depend on the input and the output of the
preceding steps.
Finiteness: Not even a single instruction must be repeated infinitely.
9
PPS Unit-I DIT,Pimpri
Algorithm has finite number of steps and some steps may involve in decision making and
repetition. Broadly algorithm may apply three decision making structures
1. Sequence:
In sequence control structure each step of the algorithm is executed in the
specific order.
Algorithm performs the steps in a purely sequential order.
Example:
Step 1: Start
Step 2: Input first number as A
Step 3: Input Second number as B
Step 4: Perform sum=A+B
Step 5: Display sum
Step 6: Stop
10
PPS Unit-I DIT,Pimpri
2. Decision:
Decision control structures can be used for making decisions and
branching of statements, where the outcome of the process depends on
some condition.
A condition in this context is any statement that may evaluate either to a
TRUE or FALSE value.
This form is commonly known as the if—else construct.
Example:
Step 1: Start
Step 2: Input first number as A
Step 3: Input Second number as B
Step 4: IF A==B
Print Equal
ELSE
Print Not Equal
Step 5: Stop
3. Repetition:
These control structures are used for executing one or more steps for a
number of times.
It can be implemented using constructs such as for loop, while loop etc.
Example:
Step 1: Start
Step 2: Initialize I=1, N=10
Step 3: Repeat Steps 3 and 4 while I<=N
Step 4: Print I
Step 5: Set I=I+1
Step: Stop
11
PPS Unit-I DIT,Pimpri
12
PPS Unit-I DIT,Pimpri
13
PPS Unit-I DIT,Pimpri
Flowchart:
Definition: Flowchart is graphical representation of computation and
provides visual description of solution/algorithm step by step.
Example:
Flowchart for calculating area of circle
Pseudocode:
Definition: It is compact informal representation of algorithm. It is written in
natural language with description of the details and compact mathematical
notations.
Example:
Student is Pass or Fail
If student’s grade is greater than or equal
to 60 Print ”Passes”
14
PPS Unit-I DIT,Pimpri
Else
Print “Failed”
Python is a general purpose interpreted interactive object oriented and high level
programming language.
It was first introduced in 1991 by Guido van Rossum, a Dutch computer
programmer.
The language places strong emphasis on code reliability and simplicity so that the
15
PPS Unit-I DIT,Pimpri
History of Python:
Future of Python:
Python’s userbase is vast and growing – it’s not going away any time soon.
Utilized by the likes of Nokia, Google, and even NASA for it’s easy syntax, it looks
to have a bright future ahead of it supported by a huge community of OS developers.
Its support of multiple programming paradigms, including object-oriented Python
programming, functional Python programming, and parallel programming models
makes it a highly adaptive choice – and its uptake keeps growing.
Open IDLE.
Go to File > New.
Write Python code in the file.
16
PPS Unit-I DIT,Pimpri
Then save the file with .py extension. For example, hello.py, example.py etc.
You can give any name to the file. However, the file name should end with .py
Run the program.
4.1) Numbers:
Numbers as a name suggest, refers to a numeric value.
You can use three types of numbers in a python program. These include integers
floating point, and complex numbers.
int- Number like 5 or other whole numbers are represented as integers.
float- numbers like 3.23, 8.73 are termed as floating point numbers.
Complex- numbers like a+bj form ( like 3+2j) are complex numbers
Remember that commas are never used in numeric literals or numeric values.
Although there is no limit to the size of integers that can be represented in python,
floating point numbers do have a limited range and limited precision. In python you
can have a floating point numbers in a range 10-308 to 10308 with 16 to 17 digits of
precision. In fact, large floating point numbers are efficiently represented in scientific
notation. For ex, 5.0012304*106 (6 digits of precision) can be written as
5.0012304e+6
Built-in format( ) function
Any floating point value may contain an arbitrary number of decimal places, so it is
always recommended to use the built-in format( ) function to produce a string version
of a number with a specific number of decimal places. Observe the difference
between the following outputs.
17
PPS Unit-I DIT,Pimpri
Here .2f in the format() function round the result to two decimal places of accuracy in
the string produced.
For very large (or very small ) values, ‘e’ can be used as a format specifier.
The format() function can also be used to format floating point numbers in scientific
notation. Look at the result of the expression given below:
>>> format(3**50, '.5e')
'7.17898e+23'
18
PPS Unit-I DIT,Pimpri
There are two kinds of strings supported in Python, single line and multiline string
literals.
Example:
str1 = ‘Amit’
str2 = "Ricky Ponting"
str3 = '''Welcome to python '''
Escape Sequences:
Some characters (like “ ‘ \ ) cannot be directly included in string. Such characters must
be escaped by placing a backslash before them.
For example,
>>> print( 'What's your name?' )
SyntaxError: invalid syntax
We got this error, as python got confused where the string starts and ends. So, we need to
clearly specify that this single quote does not indicate the end of the string . This
indication can be given with the help of escape sequence.
For example,
>>> print('What\'s your name?')
What's your name?
19
PPS Unit-I DIT,Pimpri
You can use the escape sequence for the newline character (\n). Character following the
\n are moved to the next line.
>>> print("Today is 15th August. \n India became independent on this day.")
Today is 15th August.
India became independent on this day.
Note that when specifying a string, if a single backslash ( \ ) at the end of the line is
added , then it indicates that the string is continued in the next line, but no new line is
added otherwise.
For example,
>>> print("I have studied many programming languages. \
But my favorite language is python")
I have studied many programming languages. But my favorite language is
python
20
PPS Unit-I DIT,Pimpri
Variables:
print counter
print miles
print name
Identifiers:
21
PPS Unit-I DIT,Pimpri
2. String
String is sequence of Unicode characters.
We can use single quotes or double quotes to represent strings.
Multi-line strings can be denoted using triple quotes, ''' or """.
4. Python Tuple
Tuple is an ordered sequence of items same as list.The only difference is that
tuples are immutable. Tuples once created cannot be modified.
It is defined within parentheses () where items are separated by commas.
Ex: t = (5,'program', 1+3j)
5. Dictionary
Dictionary is an unordered collection of items in key:value pair of any type. In
dictionary values are separated by comma inside braces { }. ·
In dictionary, key should be unique.
Ex: a = {‘name’:’Bob’,’Age’: 21}
1.input()
To allow flexibility we might want to take the input from the user. In Python, we have
the input() function to allow this.
Syntax:
input (expression)
2.print()
We use the print() function to output data to the standard output device (screen).
print() evaluates the expression before printing it on the monitor. Print statement outputs
an entire (complete) line and then goes to next line for subsequent output (s). To print
more than one item on a single line, comma (,) may be used.
Syntax:
print (expression/constant/variable)
23
PPS Unit-I DIT,Pimpri
Example:
1.10 Comments
Example:1
#This is first Python Program
print(“Hello World”) # prints Hello World
Example: 2
''' program is written for addition
Of two numberd '''
x=10
y=20;
Print(x+y)
1.11Reserved Words
Q. Explain keywords (reserved words) in python.
In python there are certain words which have predefined meaning. They are
called as reserved words.
Reserved words are also called as keywords.
Reserved words cannot be used for naming an identifier.
Example:
for, int, while etc.
1.12Indentation
25
PPS Unit-I DIT,Pimpri
Arithmetic Operators
+, -, *, /, %, /,**
Example:
x = 15
y=4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
Output:
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
Example:
x = 10
y = 12
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
Output:
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
26
PPS Unit-I DIT,Pimpri
Assignment Operators
= ,+=, -=, *=, /= , //=, %=
Example:
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
Logical Operators
and , or, not
non zero numbers are evaluated as true while zero as false.
Operates number as whole no binary conversion is required.
Example:
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Output:
x and y is False
x or y is True
not x is False
Bitwise operators
&, |, ^, ~, >>, <<
Bitwise operators process individual bits of data.
Numbers are converted into binary form and then processed by bitwise operators.
Example:
27
PPS Unit-I DIT,Pimpri
Identity Operators
is, is not
These operators checks if given items are identical and equal.
In python following identity operators are used
(a) is – returns true if given elements are equal and identical (identical means
both objects are having same reference location or memory location).
(b) is not – returns true if given elements are neither equal nor identical.
Example:
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1)
print(x2 is y2)
print(x3 is y3)
Output:
False
True
False
Membership operators
in, not in
These operators are used to check presence of any value or data in given range.
(a) in – returns true if that item exists in a list or a range.
(b) not in – returns true if that item does not exists in given list or a range.
Example:
x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x)
print('hello' not in x)
print(1 in y)
print('a' in y)
28
PPS Unit-I DIT,Pimpri
Output:
True
True
True
False
Operators Meaning
() Parentheses
** Exponent
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not
in Comparisions, Identity, Membership operators
or Logical OR
29
PPS Unit-I DIT,Pimpri
1.13Expressions in Python
An expression is any valid combination of symbols like variables, constants and
operators that represents a value.
In python, an expression must have at least one operand and can have one or more
operators.
30
PPS Unit-II DIT,Pimpri
• The selection control statements usually jump from one part of code to another
depending on whether a particular condition is satisfied or not.
• It allow us to execute statements selectively (branch wise) based on certain
decisions.
• Python language supports different types of selection/conditional/branching
statements.
1. If statements
2. If....else statements
3. If…elif….else statements
4. Nested if
2.1.1 if
1. If statements:
• If statement is a simplest form of decision control statements that is frequently
used in decision making.
• If statements may include one statement or N statements enclosed within the if
block
• If the expression is true the statements of if block get executed, otherwise these
statements will be skipped and the execution will be jump to statement just
outside if block.
• Syntax:
if (expression/condition):
Block of statements
Statements ouside if
1
PPS Unit-II DIT,Pimpri
• Flowchart:
✓ Example:
a=2
if (a<3):
print(a);
if (a>3):
print('Hi')
Output: 2
2.1.2 if-else
• In simple if statement, test expression is evaluated and if it is true the statements
in if block get executed, But if we want a separate statements to be get executed
if it returns false in this case we have to use if..else control statement.
• if else statement has two blocks of codes, each for if and else.
• The block of code inside if statement is executed if the expression in if statement
is TRUE, else the block of code inside else is executed.
• Syntax:
if (expression/condition):
Block of statements
else:
Block of statements
2
PPS Unit-II DIT,Pimpri
• Flowchart:
✓ Example:
x=5
if (x<10):
print (“Condition is TRUE”)
else:
print (“Condition is FALSE”)
output:
Condition is TRUE'
2.1.3 if-elif-else
• Python supports if..elif..else to test additional conditions apart from the initial test
expression.
• It work just like a if…else statement.
• The programmer can have as many elif statements/branches as he wants depending
on the expressions that have to be tested.
• A series of if..elif statements can have a final else block, which is called if none of
the if or elif expression is true.
• Syntax:
if (expression/condition):
Block of statements
3
PPS Unit-II DIT,Pimpri
elif (expression/condition):
Block of statements
elif (expression/condition):
Block of statements
else:
Block of statements
• Flowchart:
Example:
x=5
if (x == 2):
print (“x is equal to 2”)
elif (x < 2):
print (“x is less than 2”)
else:
print (“x is greater than 2”)
Output:
x is greater than 2
4
PPS Unit-II DIT,Pimpri
2.1.4 nested if
• A statement that contains other statements is called nested/compound statements.
• In nested if else statements, if statement is nested inside an if statements. So, the
nested if statements will be executed only if the expression of main if statement
returns TRUE.
• Syntax:
if (expression/condition):
if (expression/condition):
statements
else:
statements
else:
statements
• Flowchart
• Example
x=5
if (x<=10):
if(x==10):
print (“Number is Ten”)
else:
print (“Number is less than Ten”)
else:
print (“Number is greater than Ten”)
5
PPS Unit-II DIT,Pimpri
• Iterative statements are decision control statements that are used to repeat the
execution of a list of statements.
• Python language supports two types of statements while loop and for loop.
• As shown in the syntax above, in the while loop condition is first tested.
• If the condition is True, only then the statement block will be executed.
• Otherwise, if the condition is False the control will jump to statement y, that is the
immediate statement outside the while loop block.
• Flowchart:
6
PPS Unit-II DIT,Pimpri
• Example:
Program to print numbers from 0 to 10.
i=0
while (i<10):
print(i, end=” “)
i=i+1
Output: 0 1 2 3 4 5 6 7 8 9
• Syntax:
for loop_control_var in sequence:
statement block1
statement x
7
PPS Unit-II DIT,Pimpri
• Flowchart:
• Example:.
Output: Output:
1 2 3 4 1 35 7 9
• If condition is not met in entry-controlled loop, then the loop will never execute.
• However, in case of post-test, the body of the loop is executed unconditionally for
the first time.
• If the requirement is to have a pre-test loop, then choose a for loop or a while loop.
• The table below shows comparison between ore-test loop and post-test loop.
Feature Pre-test Loop Post-test Loop
Initialization 1 2
Number of tests N+1 N
Statements executed N N
Loop control variable update N N
Minimum Iterations 0 1
9
PPS Unit-II DIT,Pimpri
10
PPS Unit-II DIT,Pimpri
print("* ",end="")
print("\r")
Output
*
**
***
****
*****
Example 2:
lastNumber = 6
for row in range(1, lastNumber):
for column in range(1, row + 1):
print(column, end=' ')
print("")
Output
1
12
123
1234
12345
11
PPS Unit-II DIT,Pimpri
• Example 1 (For ‘for loop’): Print numbers from 0 to 10 and print a message when
the loop is ended.
for x in range(11):
print(x)
else:
print(“Loop is finished”)
Output:
if(i=="c"):
break
print(i)
Output:
w
e
l
2.5.2 continue
• Continue statement can appear only in the body of loop.
• When the continue statement encounters, then the rest of the statements in the loop
are skipped
• The control is transferred to the loop-continuation portion of the nearest enclosing
loop.
• Its syntax is simple just type keyword continue as shown below
continue
• Example:
for i in "welcome":
if(i=="c"):
continue
print(i)
Output:
w
e
l
o
m
e
• We can say continue statement forces the next iteration of the loop to take place,
skipping the remaining code below continue statement.
13
PPS Unit-II DIT,Pimpri
while(…): for(…):
… …
if condition: if condition:
continue continue
…. …
……. …
2.5.3 pass
• It is used when a statement is required syntactically but you do not want any command
or code to execute.
• The pass statement is a null operation.
• Nothing happens when it executes.
14
PPS Unit-II DIT,Pimpri
• It is used as placeholder.
• In a program where for some conditions you don’t want to execute any action or what
action to be taken is not yet decided, but we may wish to write some code in future, In
such cases pass can be used.
• Syntax:
Pass
• Example:
for i in “welcome”:
if (i == 'c'):
pass
print (i)
Output:
w
e
l
c
o
m
e
2.6.1 Tuples
Q. What is tuple? Explain how to access, add and remove elements in a tuple
• Tuple is a data structure supported by python.
• A tuple is a sequence of immutable objects. That means you cannot change the
values in a tuple.
• Tuples use parentheses to define its elements.
15
PPS Unit-II DIT,Pimpri
• For example, to access values in tuple, slice operation is used along with the index or
indices to obtain value stored at that index.
• Example:
Tup1=(1,2,3,4,5,6,7,8,9,10)
print(“Tup[3:6]=”,Tup1[3:6])
print(“Tup[:8]=”,Tup1[:4])
print(“Tup[4:]=”, Tup1[4:])
output:
Tup[3:6]=(4,5,6)
Tup[:8]=(1,2,3,4)
Tup[4:]=(5,6,7,8,9,10)
• Tuples are immutable means we cannot add new element into it.
• Also it is not possible to change the value of tuple.
Program:
tup1=(“Kunal”,”Ishita”,”Shree”,”Pari”,“Rahul”)
tup1[5]=”Raj”
print(tup1)
Output:
It will raise an error because new element cannot be added.
• Since tuple is an immutable data structure, you cannot delete value(s) from it.
Program:
16
PPS Unit-II DIT,Pimpri
Tup1=(1,2,3,4,5)
del Tup1[3]
print(Tup1)
output: It will raise error as ‘tuple’ object doesn’t support item deletion.
• However, we can delete the entire tuple by using the “del” statement.
Example:
Tup1=(1,2,3,4,5)
del Tup1
Operations on Tuple
Q. Explain various operations on Tuple.
• Tuple behave like similar way as string when operators like concatenation (+),
and repetition (*) are used and returns new list rather a string.
• Tuple supports various operations as listed below:
17
PPS Unit-II DIT,Pimpri
2.6.2 Lists
Q. What is list? Explain how elements are accessed, added and removed from list.
• List is a data type in python.
• List is a collection of values (items / elements).
• The items in the list can be of different data types.
• The elements of the list are separated by comma (,) and written between square
brackets [].
• List is mutable which means the value of its elements can be changed.
• Syntax:
List = [value1, value2, …]
• Example1:
List1 = [1,2,3,4]
print(List1)
Output:
[1, 2, 3, 4]
• Example 2:
List2 = ['John','PPS',94]
print(List2)
18
PPS Unit-II DIT,Pimpri
Output:
['John','PPS',94]
19
PPS Unit-II DIT,Pimpri
Output:
['Sam', 'PPS', 94, 'FE']
['Sam', 94, 'FE']
[94, 'FE']
['FE']
Operations on list
Q. Explain various operations on list.
• List behave like similar way as string when operators like concatenation (+), and
repetition (*) are used and returns new list rather a string.
• List supports various operations as listed below:
20
PPS Unit-II DIT,Pimpri
2.6.3 Dictionary
Q. What is dictionary? Explain how to create dictionary, access, add and remove
elements from dictionary.
21
PPS Unit-II DIT,Pimpri
➢ Creating Dictionary
• The syntax to create an empty dictionary can be given as:
Dict = { }
• The syntax to create a dictionary with key value pair is:
Dict = {key1: value1, key2: value2, key3: value3}
• Example1:
Dict = { }
Print(Dict)
Output:
{}
• Example2:
Dict = {1: "PPS", 2: "PHY"}
print(Dict)
Output:
{1: 'PPS', 2: 'PHY'}
22
PPS Unit-II DIT,Pimpri
23
PPS Unit-II DIT,Pimpri
Operations on Dictionary:
Method Description
24
PPS Unit-III DIT,Pimpri
Advantages
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding
1
PPS Unit-III DIT,Pimpri
• Understanding, coding and testing multiple separate functions are far easier than
doing the same for one huge function.
• If big program has to be developed without the use of any function, then there
will be large number of lines in the code and maintaining that program will be a
big mess.
• All the libraries in Python contains pre-defined and pre-tested functions which the
programmers are free to use directly in their programs without worrying about
their code in detail.
• When a big program is broken into comparatively smaller functions, then
different programmers working on that project can divide the workload by writing
different functions.
• Like Python libraries, programmers can also make their own functions and use
them from different points in the main program or any other program that needs
its functionalities.
• Code Reuse: Code reuse is one of the prominent reason to use functions. Large
programs follow DRY principle i.e. Don’t Repeat Yourself principle. Once a
function is written, it can be called multiple times within the same or by different
program wherever its functionality is needed. Correspondingly, a bad repetitive
code abides by WET principle i.e. Write Everything Twice or We Enjoy Typing.
If a set of instructions have to be executed abruptly from anywhere within the
program code, then instead of writing these instructions everywhere they are
required, a better way is to place these instructions in a function and call that
function wherever required.
Syntax:
def function_name(variable1, variable2,..): Function Header
Documentation string
Statement block
return [expression] Function Boy
• Function call statement has the following syntax when it accepts parameters
function_name(variable1, variable2,..)
3
PPS Unit-III DIT,Pimpri
OUTPUT
10
4
PPS Unit-III DIT,Pimpri
5
PPS Unit-III DIT,Pimpri
• For ex.
x=”Good”
def show()
global y
y = “Morning”
print(“In function x is – “, x)
show()
print(“Outside function y is – “, y) # accessible as it is global variable
print(“ x is – “, x)
Output:
In function x is- Good
Outside function y is – Morning
x is - Good
Ans:
• If we have variable with same name as Global and Local variable. Then local
variable is accessible within the function/block in which it is defined.
• Global variable is defined outside of any function and accessible throughout the
program.
• In the code given below, str is a global string because it has been defined before
calling the function.
• Program that demonstrates using a variable defined in global namespace.
6
PPS Unit-III DIT,Pimpri
def fun():
print(str)
str = “Hello World!!!”
fun()
Output:
Hello World
• You cannot define a local variable with the same name as that of global variable. If
you want to do that you just use the global statement.
• Program describes using a local variable with same name as that of global
def f():
global str
print(str)
str= “hello world”
print(str)
Output:
Value of x: 5
Hello World
• So from this we can say that return statement is optional in function definition.
Q. Write a note on return statement with suitable example.
Ans:
• In python, every function is expected to have return statement.
• When we do not specify return statement at the end of our function, Implicit return
statement is used as last statement for such function.
• This implicit return statement returns nothing to its caller, so it is said to return none.
• But you can change this default behavior by explicitly using the return statement to
return some value to the caller.
def display(str):
print(str)
x= display(“Hello World”)
print(x)
print(display(“Hello again”))
Output:
Hello World
None
Hello again
None
Output:
Cube of 10 = 100
Note: return statement cannot be used outside the function.
9
PPS Unit-III DIT,Pimpri
Ans: There are four types of function arguments available in Python as follow:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required Arguments:
• In the required arguments, the arguments are passed to the 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
• For ex.
def person(name, age):
print(name)
print( age)
person(“Amar”, 20)
Output:
Amar
20
2. Keyword Arguments:
• In keyword arguments the order(or position) of the arguments can be changed.
• The values are assigned to the arguments by using their names
• The python interpreter uses keywords provided in the function call to match the
values with parameters.
• Program to demonstrate keyword arguments
def person(name, age, salary):
print(“Name: ”, name)
print(“Age: ”, age)
print(“Salary: ”, salary)
10
PPS Unit-III DIT,Pimpri
Output:
Name: Ajay
Age: 30
Salary: 50000
• Note:
o All the keyword arguments passed should match one of the arguments
accepted by the function
o The order of keyword argument is not important
o In no case argument should receive a value more than once
3. Default Arguments:
• Python allows user to specify function arguments that can have default
values
• Function call can have less number of arguments than provided in its
definition.
• User can specify default value for one or more arguments which is used if no
value provided in call for that argument.
def display(name, age=18):
print(“Name: ”+ name)
print(“Age: ”, age)
display(age=25, name=”Ajay”)
display(”Amar”)
Output:
Name: Ajay
Course: 25
Name: Amar
Course: 18
• In the above example, default value is not specified for name, so it is mandatory.
11
PPS Unit-III DIT,Pimpri
• But age has provided default value, so if value not provided in calling for age, it will
take 18.
Note: Non default arguments should be provided before default arguments.
• In the above program, in the function definition we have two parameters- one is a
and other is variable length parameter tup.
• The first value is assigned to a and other values are assigned to parameter tup.
• In tup parameter, 0 to n values are acceptable.
• The variable length argument if present in the function definition should be the last
in the list of formal parameters.
• To see or use all the values in the variable length parameter, we have to use for loop
as given in above example.
12
PPS Unit-III DIT,Pimpri
Output:
Sum=8
13
PPS Unit-III DIT,Pimpri
15
PPS Unit-III DIT,Pimpri
o To use a module in any program, add import module_name as the first line in your
program.
Syntax:
import module_name
o Then module_name.var is written to access functions and values with the name var
in the module.
16
PPS Unit-III DIT,Pimpri
• To import more than one item from a module, use comma separated list. For
example, to import value of pi and sqrt( ) from math module write:
Example:
from math import pi, sqrt
print("PI= ", pi)
print("Square root of 4=", sqrt(4))
Output:
PI= 3.141592653589793
Square root of 4= 2.0
17
PPS Unit-III DIT,Pimpri
• Then open another file (main.py) and write code given below.
File Name: main.py
import Mymodule
print("Mymodule string=", Mymodule.str)
Mymodule.display()
• Modules should be placed in the same directory as that of the program in which it is
imported.
• It can also be stored in one of the directories listed in sys.path.
• The dot operator is used to access members (variables or functions) of module.
3.10 Packages
Q. What are packages in python?
Ans:
• A package is a hierarchical file directory structure.
• A package has modules and other packages within it.
• Every package in python is a directory which must have a special file called
__init__.py. This may not even have a single line of code.
• It is simply added to indicate that this is not an ordinary directory and contains a
Python package.
• A package can be accessed in other python program using import statement.
• For example, to create a package MyPackage, create directory called MyPackage
having module MyModule and __init__.py file.
File Name: Mymodule.py
def display():
19
PPS Unit-III DIT,Pimpri
print("Hello")
str = "Welcome to World of Python"
• Now, to use MyModule in a program, import it in any one of the two ways:
import MyPackage.MyModule
or
from MyPackage import MyModule
Q 1. What is String? With the help of example explain how we can create string
variable in python.
Ans:
Strings data type is sequence of characters, where characters could be letter, digit,
whitespace or any other symbol.
a. Creation of Strings:
o Strings in Python can be created using single quotes or double quotes or even
triple quotes.
o Example:
string1 = 'Welcome' # Creating a String with single Quotes
string2 = "Welcome" # Creating a String with double Quotes
string3 = '''Welcome''' # Creating a String with Triple Quotes
b. Accessing strings:
o In Python, individual characters of a String can be accessed by using the method
of Indexing or range slice method [:].
o Indexing allows negative address references to access characters from the back
of the String, e.g. -1 refers to the last character, -2 refers to the second last
character and so on.
String W E L C O M E
Indexing 0 1 2 3 4 5 6
Negative Index -7 -6 -5 -4 -3 -2 -1
1
PPS Unit-VI DIT,Pimpri
o Example:
string = 'Welcome'
print(string[0]) #Accessing string with index
print(string[1])
print(string[2])
print(srting[0:2]) #Accessing string with range slice
method
Output:
w
e
l
wel
2
PPS Unit-VI DIT,Pimpri
3
PPS Unit-VI DIT,Pimpri
Output:
String1 value is: Good
Address of String1 is: 1000
From the above output you can see string1 has address 1000 before modification. In
later output you can see that string1 has new address 3000 after modification.
It is very clear that, after some operations on a string new string get created and it has
new memory location. This is because strings are unchangeable/ immutable in nature.
Modifications are not allowed on string but new string can be created at new address
by adding/appending new string.
4
PPS Unit-VI DIT,Pimpri
The % operator takes a format string on the left and the corresponding values in a
tuple on the right.
The format operator, % allows users to replace parts of string with the data stored in
variables.
The syntax for string formatting operation is:
"<format>" % (<values>)
The statement begins with a format string consisting of a sequence of characters and
conversion specification.
Following the format string is a % sign and then a set of values, one per conversion
specification, separated by commas and enclosed in parenthesis.
If there is single value then parenthesis is optional.
Following is the list of format characters used for printing different types of data:
Format Purpose
Symbol
%c Character
%d or %i Signed decimal integer
%s String
%o Octal integer
%x or %X Hexadecimal integer
%e or %E Exponential notation
5
PPS Unit-VI DIT,Pimpri
Output:
Name = Amar and Age = 8
Name = Ajit and Age = 6
In the output, we can see that %s has been replaced by a string and %d has been replaced by
an integer value.
6
PPS Unit-VI DIT,Pimpri
7
PPS Unit-VI DIT,Pimpri
8
PPS Unit-VI DIT,Pimpri
9
PPS Unit-VI DIT,Pimpri
Indices in a String
Index from
P Y T H O N
the start
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Index from
Syntax:
the end
string_name[start:end]
where start- beginning index of substring
end -1 is the index of last character
OUTPUT
str[1:5]= YTHO
str[ :6]= PYTHON
str[1: ]= YTHON
str[ : ]= PYTHON
10
PPS Unit-VI DIT,Pimpri
str[-1]= N
str[ :-2 ]= PYTH
str[ -2: ]= ON
str[-5 :-2 ]= YTH
OUTPUT
str[ 2: 10]=lcome to
str[ 2: 10]= lcome to
str[ 2:10:2 ]=loet
str[ 2:10:4 ]=l
Whitespace characters are skipped as they are also part of the string.
4.6 ord() and chr() functions
Q 7.Write a short note on ord() and chr() functions
Ans.
The ord() function return the ASCII code of the character
11
PPS Unit-VI DIT,Pimpri
For example:
str1=” Welcome to the world of Python!!!“ str1=” This is very good book“
str2=”the” str2=”best”
if str2 in str1: if str2 in str1:
print(“found”) print(“found”)
else: else:
print(“Not found”) print(“Not found”)
OUTPUT OUTPUT
Found Not found
You can also use in and not in operators to check whether a character is present in a
word.
For example:
‘u‘ in “starts” ‘v‘ not in “success”
12
PPS Unit-VI DIT,Pimpri
OUTPUT OUTPUT
False True
These operators compare the strings by using ASCII value of the characters.
The ASCII values of A-Z are 65-90 and ASCII code for a-z is 97-122.
For example, book is greater than Book because the ASCII value of ‘b’ is 98 and ‘B’
is 66.
13
PPS Unit-VI DIT,Pimpri
Example1:
first_str='Kunal works at Phoenix'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by ==
if first_str==second_str:
print("Both Strings are Same")
else:
print("Both Strings are Different")
Output:
First String: Kunal works at Phoenix
Second String: Kunal works at Phoenix
Both Strings are Same
14
PPS Unit-VI DIT,Pimpri
Output:
First String: Kunal works at PHOENIX
Second String: Kunal works at Phoenix
Both Strings are Different
Using the !=(not equal to) operator for comparing two strings:
The != operator works exactly opposite to ==, that is it returns true is both
the strings are not equal.
Example:
first_str='Kunal works at Phoenix'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by !=
if first_str!=second_str:
print("Both Strings are Different")
else:
print("Both Strings are Same")
output:
First String: Kunal works at Phoenix
Second String: Kunal works at Phoenix
Both Strings are Same
15
PPS Unit-VI DIT,Pimpri
print(“name2:”,name2)
print(“Both are same”,name1 is name2)
name2=”Kunal”
print(“name1:”,name1)
print(“name2:”,name2)
print(“Both are same”,name1 is name2)
Output:
name1=Kunal
name2=Shreya
Both are same False
name1=Kunal
name2=Kunal
Both are same True
In the above example, name2 gets the value of Kunal and subsequently
name1 and name2 refer to the same object.
4.9 Iterating strings
Q. No.10 How to iterate a string using:
Ans.
i) for loop with example
ii) while loop with example
Ans.
i) for loop:
for loop executes for every character in str.
The loop starts with the first character and automatically ends when
the last character is accessed.
Example-
16
PPS Unit-VI DIT,Pimpri
str=”Welcome to python”
for i in str:
print(i,end=’ ’)
Output-
Welcome to Python
In the above program the loop traverses the string and displays each
letter.
The loop condition is index < len(message), so the moment index
becomes equal to the length of the string, the condition evaluates to
False, and the body of the loop is not executed.
Index of the last character is len(message)-1.
17
PPS Unit-VI DIT,Pimpri
18