Professional Documents
Culture Documents
Ge1105 Problem Solving and Python Programming Unit - 1
Ge1105 Problem Solving and Python Programming Unit - 1
UNIT 1
ALGORITHMIC PROBLEM SOLVING
Algorithms, building blocks of algorithms (statements, state, control flow, functions), notation
(pseudo code, flow chart, programming language), algorithmic problem solving, Basic
algorithms, flowcharts, and pseudocode for sequential, decision processing, and iterative
processing strategies, Illustrative problems: find minimum in a list, insert a card in a list of sorted
cards, guess an integer number in a range, Towers of Hanoi.
PROBLEM-SOLVING
Problem-solving is the systematic approach to defining the problem and creating several solutions.
The problem-solving process starts with the problem specifications and ends with a Correct program.
PROBLEM-SOLVING TECHNIQUES
The problem-solving technique is a set of techniques that helps in providing logic for solving a
problem.
Problem-Solving Techniques:
Problem-solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. programs
ALGORITHM
It is defined as a sequence of instructions that describe a method for solving a problem. In other
words, it is a step-by-step procedure for solving a problem.
Properties of Algorithms
• Should be written in simple English
• Each and every instruction should be precise and unambiguous.
• Instructions in an algorithm should not be repeated infinitely.
• An algorithm should conclude after a finite number of steps.
• Should have an endpoint
• Derived results should be obtained only after the algorithm terminates.
P a g e 1 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
2. State:
Transitioning from one process to another process under the specified condition within a time is
called a state.
3. Control flow:
The process of executing the individual statements in a given order is called control flow.
The control can be executed in three ways
a) sequence
b) selection
c) iteration
Sequence:
All the instructions are executed one after another is called sequence execution.
P a g e 2 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
Example:
Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop
a) Selection:
A selection statement causes the program control to be transferred to a specific part of the program
based on the condition.
If the conditional test is true, one part of the program will be executed, otherwise, it will execute the
other part of the program.
Example
Write an algorithm to check whether he is
eligible to vote?
Step 1: Start
Step 2: Get the age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop
b) Iteration:
In some programs, a certain set of statements are executed again and again based upon the
conditional tests. i.e. executed more than one time. This type of execution is called looping or
iteration.
P a g e 3 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
Example
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
4. Functions:
A function is a subprogram that consists of a block of code(set of instructions) that performs a
particular task.
For complex problems, the problem is been divided into smaller and simpler tasks during algorithm
design.
Benefits of Using Functions
• Reduction in line of code
• code reuse
• Better readability
• Information hiding
• Easy to debug and test
• Improved maintainability
Example
Algorithm for the addition of two numbers using function
Main function() sub function add()
Step 1: Start Step 1: Function start
Step 2: Call the function add() Step 2: Get a, b Values
Step 3: Stop Step 3: add c=a+b
Step 4: Print c
Step 5: Return
P a g e 4 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
NOTATIONS
FLOW CHART
A flow chart is defined as a graphical representation of the logic for problem-solving.
The purpose of the flowchart is to make the logic of the program clear in a visual representation.
P a g e 5 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
4. Only one flow line should enter a decision symbol. However, two or three flow lines may leave
the decision symbol.
Advantages of flowchart:
i. Communication: - Flowcharts are a better way of communicating the logic of a system to all
concerned.
ii. Effective analysis: - With the help of a flowchart, the problem can be analyzed more
effectively.
iii. Proper documentation: - Program flowcharts serve as good program documentation, which
is needed for various purposes.
iv. Efficient Coding: - The flowcharts act as a guide or blueprint during the systems analysis
and program development phase.
v. Proper Debugging: - The flowchart helps in debugging process.
vi. Efficient Program Maintenance: - The maintenance of the operating program becomes easy
with the help of a flowchart. It helps the programmer to put efforts more efficiently into that
part.
P a g e 6 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
PSEUDO CODE:
i. Pseudocode consists of short, readable, and formally styled English languages used to
explaining an algorithm.
ii. It does not include details like variable declaration, and subroutines.
iii. It is easier to understand for the programmer or nonprogrammer to understand the general
working of the program because it is not based on any programming language.
iv. It gives us a sketch of the program before actual coding.
v. It is not a machine-readable
vi. Pseudocode can’t be compiled and executed.
vii. There is no standard syntax for pseudo code.
Guidelines for writing pseudo code:
• Write one statement per line
• Capitalize the initial keyword
• Indent to the hierarchy
• End multiline structure
• Keep statements language independent
Common keywords used in pseudocode
The following gives common keywords used in pseudocodes.
1. //: This keyword is used to represent a comment.
2. BEGIN, END: Begin is the first statement and end is the last statement.
3. INPUT, GET, READ: The keyword is used to inputting data.
4. COMPUTE, CALCULATE: used for calculation of the result of the given expression.
5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.
6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.
7. IF, ELSE, ENDIF: used to make a decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented tested automatically.
P a g e 7 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
Advantages:
• Pseudo is independent of any language; it can be used by most programmers.
• It is easy to translate pseudo code into a programming language.
• It can be easily modified as compared to a flowchart.
• Converting a pseudo code to a programming language is very easy compared with converting
a flowchart to a programming language.
Disadvantages:
• It does not provide a visual representation of the program’s logic.
• There are no accepted standards for writing pseudo codes.
• It cannot be compiled or executed.
• For a beginner, It is more difficult to follow the logic or write pseudo code as compared to a
flowchart.
P a g e 8 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
Example:
Addition of two numbers:
BEGIN
GET a,b
ADD c=a+b
PRINT c
END
PROGRAMMING LANGUAGE
A programming language is a set of symbols and rules for instructing a computer to perform specific
tasks. The programmers have to follow all the specified rules before writing a program using a
programming language. The user has to communicate with the computer using language that it can
understand.
Types of programming language
i. Machine language
ii. Assembly language
iii. High-level language
i. Machine language:
The computer can understand only machine language which uses 0’s and 1’s. In machine language,
the different instructions are formed by taking different combinations of 0’s and 1’s.
Advantages:
Translation free:
Machine language is the only language that the computer understands. For executing any program
written in any programming language, the conversion to machine language is necessary. The program
written in machine language can be executed directly on a computer. In this case, any conversion
process is not required.
P a g e 9 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
High speed
The machine language program is translation free. Since the conversion time is saved, the execution
of the machine language program is extremely fast.
Disadvantage:
• It is hard to find errors in a program written in machine language.
• Writing programs in machine language is a time-consuming process.
Machine dependent: According to the architecture used, the computer differs from each other. So
machine language differs from computer to computer. So a program developed for a particular type of
computer may not run on other types of computer.
ii. Assembly language: To overcome the issues in programming language and make the
programming process easier, an assembly language is developed which is logically equivalent to
machine language but is easier for people to read, write and understand.
Assembly language is a symbolic representation of machine language. Assembly languages are
symbolic programming language that uses symbolic notation to represent machine language
instructions. They are called low-level languages because they are so closely related to machines.
Assembler
Assembler is the program that translates assembly language instruction into a machine language.
• Easy to understand and use.
• It is easy to locate and correct errors.
Disadvantage
Machine dependent
The assembly language program which can be executed on the machine depends on the architecture
of that computer.
Hard to learn
It is machine-dependent, so the programmer should have the hardware knowledge to create
applications using assembly language.
Less efficient
• Execution time of an assembly language program is more than machine language program.
• Because an assembler is needed to convert from assembly language to machine language.
iii. High-level language
The high-level language contains English words and symbols. The specified rules are to be followed
while writing a program in a high-level language. The interpreter or compilers are used for converting
these programs into machine-readable form.
P a g e 10 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 11 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 12 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
Analyzing an Algorithm
1. Efficiency.
• Time efficiency, indicating how fast the algorithm runs,
• Space efficiency indicates how much extra memory it uses.
2. simplicity.
• An algorithm should be precisely defined and investigated with mathematical expressions.
• Simpler algorithms are easier to understand and easier to program.
• Simple algorithms usually contain fewer bugs.
Coding an Algorithm
Most algorithms are destined to be ultimately implemented as computer programs. Programming an
algorithm presents both a peril and an opportunity.
A working program provides an additional opportunity in allowing an empirical analysis of the
underlying algorithm. Such an analysis is based on timing the program on several inputs and then
analyzing the results obtained.
1. Iterations
2. Recursions
1. Iterations:
A sequence of statements is executed until a specified condition is true is called iterations.
[1] for loop
[2] While loop
P a g e 14 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
Recursions:
A function that calls itself is known as recursion.
Recursion is a process by which a function calls itself repeatedly until some specified condition has
been satisfied.
Algorithm for factorial of n numbers using recursion:
Main function: Sub function factorial(n):
Step1: Start Step1: if(n==1) then fact=1 return fact
Step2: Get n Step2: else fact=n*factorial(n-1) and return fact
Step3: call factorial(n)
Step4: print fact
Step5: Stop
P a g e 15 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 16 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
MORE EXAMPLES
1. Write an algorithm to find area of a rectangle
Step 1: Start BEGIN
Step 2: get l,b values READ l,b
Step 3: Calculate A=l*b CALCULATE A=l*b
Step 4: Display A DISPLAY A
Step 5: Stop END
P a g e 17 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 18 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 19 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
10. Write an algorithm to check whether given number is +ve, -ve or zero.
P a g e 20 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 21 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 22 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 23 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
ILLUSTRATIVE PROBLEMS
1. Guess an integer in a range
Algorithm: Pseudocode:
Step1: Start BEGIN
Step 2: Declare hidden, guess COMPUTE hidden=random value in range
Step 3: Compute hidden= Choose a random READ guess
value in a range
IF guess=hidden, then
Step 4: Read guess
PRINT Guess is hit
Step 5: If guess=hidden, then
ELSE
Print Guess is hit
PRINT Guess not hit
Else
PRINT hidden
Print Guess not hit
END IF-ELSE
Print hidden
END
Step 6: Stop
Flowchart:
P a g e 24 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 25 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
Flowchart:
P a g e 26 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
Algorithm: Pseudocode:
Step 1: Start BEGIN
Step 2: Read n READ n
Step 3:Initialize i=0 FOR i=0 to n, then
Step 4: If i<n, then goto step 4.1, 4.2 else goto READ a[i]
step 5
INCREMENT i
Step4.1: Read a[i]
END FOR
Step 4.2: i=i+1 goto step 4
READ item
Step 5: Read item
FOR i=n-1 to 0 and item<a[i], then
Step 6: Calculate i=n-1
CALCULATE a[i+1]=a[i]
Step 7: If i>=0 and item<a[i], then go to step
DECREMENT i
7.1, 7.2 else goto step 8
END FOR
Step 7.1: a[i+1]=a[i]
COMPUTE a[i+1]=a[i]
Step 7.2: i=i-1 goto step 7
COMPUTE n=n+1
Step 8: Compute a[i+1]=item
FOR i=0 to n, then
Step 9: Compute n=n+1
PRINT a[i]
Step 10: If i<n, then goto step 10.1, 10.2 lse
goto st 11 INCREMENT i
Step10.1: Print a[i] END FOR
Step10.2: i=i+1 goto step 10 END
Step 11: Stop
P a g e 27 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
Flowchart:
P a g e 28 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
4. Tower of Hanoi
Algorithm: Pseudcode:
Step 1: Start BEGIN
Step 2: Read n READ n
Step 3: Calculate move=pow(2,n)-1 CALCULATE move=pow(2,n)-1
Step 4: Function call T(n,Beg,Aux,End) FUNCTION T(n,Beg,Aux,End) Recursiv ly
recursively until n=0 until n=0
Step 4.1: If n=0, then goto PROCEDURE
step 5 else goto step IF n=0 then,
4.2 Step No disk to move
4.2: T(n-1,Beg,End,Aux) T(1,Beg,Aux,End) , Else
Move disk from source to desti ation T(n-
T(n-1,Beg,End,Aux)
1,Aux,Beg,End)
T(1,Beg,Aux,End), move isk from source to
Step 5: Stop
destination
T(n-1,Aux,Beg,En )
END PROCEDURE
END
Flowchart:
P a g e 29 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 30 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 31 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 32 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 1
P a g e 33 | 33
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
UNIT 2
INTRODUCTION TO PYTHON
Python Introduction, Technical Strength of Python, Python interpreter and interactive mode,
Introduction to colab, pycharm, and jupyter idle(s), Values and types: int, float, boolean, string,
and list; Built-in data types, variables, Literals, Constants, statements, Operators: Assignment,
Arithmetic, Relational, Logical, Bitwise operators and their precedence, Expressions, tuple
assignment, Accepting input from Console, printing statements, Simple Python programs.
INTRODUCTION TO PYTHON
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming
language.
• It was created by Guido van Rossum during 1985- 1990.
• Python got its name from “Monty Python’s flying circus”. Python was released in the year
2000.
• Python is interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it.
• Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
• Python is Object-Oriented: Python supports an Object-Oriented style or technique of
programming that encapsulates code within objects.
• Python is a Beginner's Language: Python is a great language for beginner-level programmers
and supports the development of a wide range of applications.
Python Features:
• Easy-to-learn: Python is clearly defined and easily readable. The structure of the program is
very simple. It uses a few keywords.
• Easy-to-maintain: Python's source code is fairly easy-to-maintain.
• Portable: Python can run on a wide variety of hardware platforms and has the same interface
on all platforms.
• Interpreted: Python is processed at runtime by the interpreter. So, there is no need to compile a
program before executing it. You can simply run the program.
• Extensible: Programmers can embed python within their C, C++, Java script, ActiveX, etc.
• Free and Open Source: Anyone can freely distribute it, read the source code, and edit it.
• High-Level Language: When writing programs, programmers concentrate on solutions to the
current problem, no need to worry about the low-level details.
• Scalable: Python provides a better structure and support for large programs than shell scripting.
P a g e 1 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Applications
• Bit Torrent file sharing
• Google search engine, Youtube
• Intel, Cisco, HP, IBM
• i–Robot
• NASA
• Facebook, Dropbox
Python interpreter
Interpreter: To execute a program in a high-level language by translating it one line at a time.
Compiler: To translate a program written in a high-level language into a low-level language all at
once, in preparation for later execution.
P a g e 2 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Drawback:
We cannot save the statements and have to retype all the statements once again to re-run them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1+1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter code.
If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays a result on the screen. In this case, the result is the
words.
2. Script mode:
• In script mode, we type a python program in a file and then use an interpreter to execute the
content of the file.
• Scripts can be saved to disk for future use. Python scripts have the extension .py, meaning
that the filename ends with .py
• Save the code with filename.py and run the interpreter in script mode to execute the script.
P a g e 3 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Values
Value can be any letter, number, or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
Data type:
• Every value in Python has a data type.
• It is a set of values and the allowable operations on those values.
Python has four standard data types:
P a g e 4 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Numbers:
• Number data type stores Numerical Values.
• This data type is immutable [i.e. values/items cannot be changed].
• Python supports integers, floating point numbers and complex numbers. They are defined as,
Sequence:
• A sequence is an ordered collection of items, indexed by positive integers.
• It is a combination of mutable (value can be changed) and immutable (values cannot be
changed) data types.
• There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
1. Strings
A String in Python consists of a series or sequence of characters - letters, numbers, and special
characters.
Strings are marked by quotes:
• single quotes (' ') Eg, 'This a string in single quotes'
• double quotes (" ") Eg, "'This a string in double quotes'"
• triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple lines and sentences."""
➢ Individual character in a string is accessed using a subscript (index).
➢ Characters can be accessed using indexing and slicing operations
Strings are immutable i.e. the contents of the string cannot be changed after it is created.
P a g e 5 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
2. Lists
A list is an ordered sequence of items. Values in the list are called elements/items.
It can be written as a list of comma-separated items (values) between square brackets[ ].
Items in the lists can be of different data types.
3. Tuple:
• A tuple is the same as a list, except that the set of elements is enclosed in parentheses instead
of square brackets.
• A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to a
tuple or remove elements from the tuple.
The benefit of Tuple:
➢ Tuples are faster than lists.
➢ If the user wants to protect the data from accidental changes, a tuple can be used.
➢ Tuples can be used as keys in dictionaries, while lists can't.
4. Dictionaries:
• Lists are ordered sets of objects, whereas dictionaries are unordered sets.
• Dictionary is created by using curly brackets. i,e. {}
• Dictionaries are accessed via keys and not via their position.
• A dictionary is an associative array (also known as hashes). Any key of the dictionary is
associated (or mapped) to a value.
• The values of a dictionary can be any Python data type. So dictionaries are unordered key-
value-pairs(The association of a key and a value is called a key-value pair )
• Dictionaries don't support the sequence operation of the sequence data types like strings, tuples
and lists.
VARIABLES:
A variable allows us to store a value by assigning it to a name, which can be used later.
• Named memory locations to store values.
• Programmers generally choose names for their variables that are meaningful.
• It can be of any length. No space is allowed.
• We don't need to declare a variable before using it. In Python, we simply assign a value to a
variable and it will exist.
P a g e 6 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
IDENTIFIERS
Identifier is the name given to entities like classes, functions, variables, etc. in Python.
• Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits
(0 to 9) or underscore (_). all are valid examples.
• An identifier cannot start with a digit.
• Keywords cannot be used as identifiers.
• Cannot use special symbols like! @, #, $, %, etc. in our identifier.
• Identifiers can be of any length.
Example: Names like myClass, var_1, and this_is_a_long_variable
P a g e 7 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
COMMENTS
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Eg: percentage = (minute * 100) / 60 # calculating percentage of an hour
Python does not have multiple-line commenting feature. You have to comment each line
individually as follows :
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
LINES AND INDENTATION
• Most of the programming languages like C, C++, Java use braces { } to define a block of code.
But, python uses indentation.
• Blocks of code are denoted by line indentation.
• It is a space given to the block of codes for class and function definitions or flow control.
Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
TUPLE ASSIGNMENT
An assignment to all of the elements in a tuple using a single assignment statement.
• Python has a very powerful tuple assignment feature that allows a tuple of variables on the left
of an assignment to be assigned values from a tuple on the right of the assignment.
• The left side is a tuple of variables; the right side is a tuple of values.
• Each value is assigned to its respective variable.
• All the expressions on the right side are evaluated before any of the assignments. This feature
makes tuple assignments quite versatile.
• Naturally, the number of variables on the left and the number of values on the right have to be
the same.
>>> (a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack
P a g e 9 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Example:
It is useful to swap the values of two variables. With conventional assignment statements, we have
to use a temporary variable. For example, to swap a and b:
Swap two numbers
a=2;b=3 Output:
print(a,b) (2, 3)
temp = a (3, 2)
a=b
b = temp
print(a,b)
Tuple assignment solves this problem neatly: (a, b) = (b, a)
OPERATORS
Operators are the constructs that can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator
Types of Operators:
Python language supports the following types of operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic operators: They are used to perform mathematical operations like addition, subtraction,
multiplication etc. Assume, a=10 and b=5
P a g e 10 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Examples Output:
a=10 a+b= 15
b=5 a-b= 5
print("a+b=",a+b) a*b= 50
print("a-b=",a-b) a/b= 2.0
print("a*b=",a*b) a%b= 0
print("a/b=",a/b) a//b= 2
print("a%b=",a%b) a**b= 100000
print("a//b=",a//b)
print("a**b=",a**b)
P a g e 11 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Example Output:
a=10 a>b=> True
b=5 a>b=> False
print("a>b=>",a>b) a==b=> False
print("a>b=>",a<b) a!=b=> True
print("a==b=>",a==b) a>=b=> False
print("a!=b=>",a!=b) a>=b=> True
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)
P a g e 12 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Assignment Operators:
Assignment operators are used in Python to assign values to variables.
P a g e 13 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Example Output
a = 21 Line 1 - Value of c is 31
b = 10 Line 2 - Value of c is 52
c=0 Line 3 - Value of c is 1092
c=a+b Line 4 - Value of c is 52.0
print("Line 1 - Value of c is ", c) Line 5 - Value of c is 2
c += a Line 6 - Value of c is 2097152
print("Line 2 - Value of c is ", c) Line 7 - Value of c is 99864
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c= 2 c %= a
print("Line 5 - Value of c is ", c) c **= a
print("Line 6 - Value of c is ", c) c //= a
print("Line 7 - Value of c is ", c)
Logical Operators:
Logical operators are the and, or, not operators.
Example Output
a = True x and y is False
b = False
print('a and b is',a and b) x or y is True
print('a or b is',a or b)
not x is False
print('not a is',not a)
P a g e 14 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Bitwise Operators:
A bitwise operation operates on one or more bit patterns at the level of individual Bits
Example:
Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)
Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is -61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a | b; # 61 = 0011 1101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c
P a g e 15 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple, dictionary or
not.
Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators are used.
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators
They are used to check if two values (or variables) are located on the same part of the memory.
Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
P a g e 16 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
Output
False
True
OPERATOR PRECEDENCE
When an expression contains more than one operator, the order of evaluation depends on the order of
operations.
P a g e 17 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
• Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and
(1+1)**(5-2) is 8.
• You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60,
even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 *3**2 is 18,
not 36.
• Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1
is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are evaluated from left to right (except exponentiation).
Example:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6 find m=? a=2*3+4%5-3//2+6
a=? A=6+4%5-3/2+6 m=-43||8&&0||-2 a=6+4-1+6
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||0||-2 a=10-1+6
a=9-4+6-1 A=6+4-1+6 m=1||-2 a=15
a=5+6-1 A=10-1+6 m=1
a=11-1 A=9+6
a=10 A=15
P a g e 18 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
2. Area of rectangle
l=eval(input(“enter the length of rectangle”)) Output
b=eval(input(“enter the breath of rectangle”)) enter the length of rectangle 5
a=l*b enter the breath of rectangle 6
print(a) 30
P a g e 19 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
P a g e 20 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
P a g e 21 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
P a g e 22 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 2
P a g e 23 | 23
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
UNIT 3
CONTROL FLOW, FUNCTIONS, AND STRINGS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif- else); Iteration: while, for; Loop manipulation using the pass, break,
continue, and else; Modules and Functions, function definition and use, flow of execution,
parameters and arguments; local and global scope, return values, function composition,
recursion; Strings: string slices, immutability, string functions, and methods, string module;
Illustrative programs: square root, gcd, exponentiation, sum an array of numbers, linear search,
binary search.
BOOLEAN VALUES
Boolean:
Boolean data types have two values. They are 0 and 1.
0 represents False
1 represents True
True and False are keywords.
Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0
CONDITIONALS
1. Conditional if
2. Alternative if… else
3. Chained if…elif…else
4. Nested if….else
Conditional (if): conditional (if) is used to test a condition, if the condition is true the statements
inside if will be executed.
syntax:
if(condition 1):
Statement 1
P a g e 1 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Flowchart:
Examples:
a) Program to provide flat rs 500 if the purchase amount is greater than 2000.
b) Program to provide bonus marks if the category is sports.
a) Program to provide flat rs 500, if the purchase amount is Output
greater than 2000.
purchase=eval(input(“enter your purchase amount”)) enter your purchase amount
if(purchase>=2000): 2500
purchase=purchase-500 amount to pay
print(“amount to pay”,purchase) 2000
2. alternative (if-else)
In the alternative, the condition must be true or false. In this else statement can be combined with the
if statement. The else statement contains the block of code that executes when the condition is false. If
the condition is true statements inside the if get executed otherwise else part gets executed. The
alternatives are called branches because they are branches in the flow of execution.
syntax:
P a g e 2 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Flowchart:
Examples:
a) Odd or even number
b) A positive or negative number
c) Leap year or not
d) Greatest of two numbers
e) Eligibility for voting
a) Odd or even number Output
n=eval(input("enter a number")) enter a number: 4
if(n%2==0): even number
print("even number")
else:
print("odd number")
b) Positive or negative number Output
n=eval(input("enter a number")) enter a number8
if(n>=0): positive number
print("positive number")
else:
print("negative number")
P a g e 3 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
3. Chained conditionals(if-elif-else)
• The elif is short for else if.
• This is used to check more than one condition.
• If condition 1 is False, it checks condition 2 of the elif block. If all the conditions are False,
then the else part is executed.
• Among the several, if...elif...else parts, only one part is executed according to the condition.
• The if block can have only one else block. But it can have multiple elif blocks.
• The way to express a computation like that is a chained conditional.
syntax:
Flowchart:
P a g e 4 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Example:
a) Student mark system
b) Traffic light system
c) Compare two numbers
d) Roots of quadratic equation
a) Student mark system Output
mark=eval(input("enter ur mark:"))
enter ur mark:78
if(mark>=90):
grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
b) Traffic light system Output
colour=input("enter colour of light:") enter colour of light:green
if(colour=="green"):
GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
c) Compare two numbers Output
x=eval(input("enter x value:")) enter x value:5
y=eval(input("enter y value:"))
enter y value:7
if(x == y):
print("x and y are equal") x is less than y
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
d) Roots of quadratic equation Output
a=eval(input("enter a value:")) enter a value:1
b=eval(input("enter b value:"))
c=eval(input("enter c value:")) enter b value:0
d=(b*b-4*a*c) enter c value:0
if(d==0):
print("same and real roots") same and real roots
elif(d>0):
print("different real roots")
else:
print("imaginary roots")
P a g e 5 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Nested conditionals
One conditional can also be nested within another. Any number of the condition can be nested inside
one another. In this, if the condition is true it checks another if condition1. If both the conditions are
true statement 1 gets executed otherwise statement 2 gets to execute. if the condition is false statement3
gets executed
Syntax:
Flowchart:
Examples:
a) Greatest of three numbers
b) Positive negative or zero
a) Greatest of three numbers Output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
P a g e 6 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
b) Positive negative or zero Output
n=eval(input("enter the value of n:")) enter the value of n:-9
if(n==0): the number is negative
print("the number is zero")
else:
if(n>0):
print("the number is positive")
else:
print("the number is negative")
ITERATION/CONTROL STATEMENTS:
• state
• while
• for
• break
• continue
• pass
State:
The transition from one process to another process under a specified condition within a time is called
a state.
While loop:
While a loop statement in Python is used to repeatedly executes a set of statements as long as a given
condition is true.
In a while loop, the test expression is checked first. The body of the loop is entered only if the
test_expression is True. After one iteration, the test expression is checked again. This process continues
until the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The statements inside the while starting with indentation and the first unindented line marks the end.
Syntax:
P a g e 7 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Flowchart
Examples:
a) Program to find the sum of n numbers:
b) Program to find the factorial of a number
c) Program to find the sum of digits of a number:
d) Program to Reverse the given number:
e) Program to find the number is Armstrong number or not
f) Program to check whether the number is palindrome or not
P a g e 8 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
while(n>0): 123
a=n%10
sum=sum+a 6
n=n//10
print(sum)
d) Reverse the given number: output
n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 321
a=n%10
sum=sum*10+a
n=n//10
print(sum)
e) Armstrong number or not output
n=eval(input("enter a number")) enter a number153
org=n The given number is Armstrong number
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not Armstrong number")
f) Palindrome or not output
n=eval(input("enter a number"))
org=n enter a number121
sum=0 The given no is palindrome
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is not palindrome")
For loop:
for in range:
• We can generate a sequence of numbers using the range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
• In range, a function has to define the start, stop and step size as a range(start, stop, step size).
step size defaults to 1 if not provided.
P a g e 9 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Syntax
Flowchart:
For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over a sequence
is called traversal. Loop continues until we reach the last element in the sequence.
The body of for loop is separated from the rest of the code using indentation.
P a g e 10 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Examples:
a) Print nos divisible by 5 not by 10:
b) Program to print the Fibonacci series.
c) Program to find factors of a given number
d) Check whether the given number is perfect or not
e) Check whether the no is prime or not
f) Print first n prime numbers
g) Program to print prime numbers in a range
P a g e 11 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
sum=sum+i
if(sum==n):
print("the number is perfect number")
else:
print("the number is not perfect number")
P a g e 12 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Syntax:
Break
Flowchart
Example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)
P a g e 13 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
CONTINUE
It terminates the current iteration and transfers the control to the next iteration in the loop.
Syntax:
Continue
Flowchart
Example: Output
w
for i in "welcome":
e
if(i=="c"): l
o
continue m
print(i) e
P a g e 14 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
PASS
It is used when a statement is required syntactically but you don’t want any code to execute.
It is a null statement, nothing happens when it is executed.
Syntax:
pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c
o
m
e
P a g e 15 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Program Output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
else: 5
print("the number greater than 5") the number greater than 5
FRUITFUL FUNCTION
• Fruitful function
• Void function
• Return values
• Parameters
• Local and global scope
• Function composition
• Recursion
P a g e 16 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Void Function A function that performs an action but doesn’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Return values: return keywords are used to return the values from the function.
Example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value
P a g e 17 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
PARAMETERS / ARGUMENTS:
• Parameters are the variables used in the function definition.
• Parameters are inputs to functions.
• Parameter receives the input from the function call.
• It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
i. Required/Positional parameters
ii. Keyword parameters
iii. Default parameters
iv. Variable length parameters
i) Required/ Positional Parameter:
The number of parameter in the function definition should match exactly with number of arguments in
the function call.
Example
def student( name, roll ):
print(name,roll)
student(“George”,98)
Output:
George 98
ii) Keyword parameter:
When we call a function with some values, these values get assigned to the parameter according to
their position. When we call functions in keyword parameters, the order of the arguments can be
changed.
Example
def student(name,roll,mark):
print(name,roll,mark)
student(90,102,"bala")
Output:
90 102 bala
iii) Default parameter:
Python allows function parameters to have default values; if the function is called without the
argument, the argument gets its default value in a function definition.
P a g e 18 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Example
def student( name, age=17):
print (name, age)
student( “kumar”):
student( “ajay”):
Output:
Kumar 17
Ajay 17
iv) Variable length parameter
• Sometimes, we do not know in advance the number of arguments that will be passed into a
function.
• Python allows us to handle this kind of situation through function calls with several arguments.
• In the function definition, we use an asterisk (*) before the parameter name to denote this is the
variable length of the parameter.
Example
def student( name,*mark):
print(name,mark)
student (“bala”,102,90)
Output:
bala ( 102 ,90)
Local and Global Scope
Global Scope
• The scope of a variable refers to the places where you can see or access a variable.
• A variable with global scope can be used anywhere in the program.
• It can be created by defining a variable outside the function.
P a g e 19 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Local Scope A variable with local scope can be used only within the function .
Function Composition:
Function Composition is the ability to call one function from within another function
It is a way of combining functions such that the result of each function is passed as the argument
of the next function.
In other words the output of one function is given as the input of another function is known as
function composition.
Examples:
math.sqrt(math.log(10))
def add(a,b):
c=a+b Output:
return c 900
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Find sum and average using function output
composition
def sum(a,b): enter a:4
sum=a+b
enter b:8
return sum
def avg(sum): the avg is 6.0
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)
P a g e 20 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Recursion
A function calling itself till it reaches the base value - stop point of function call. Example: factorial
of a given number using recursion
Factorial of n
def fact(n):
if(n==1): Output
return 1 enter no. to find fact:5
else:
Fact is 120
return n*fact(n-1)
n=eval(input("enter no. to find
fact:"))
fact=fact(n)
print("Fact is",fact)
Explanation
Example:
a) Sum of n numbers
def sum(n):
if(n==1): Output
return 1
else: enter no. to find sum:10
return n*sum(n-1) Fact is 55
n=eval(input("enter no. to find
sum:"))
sum=sum(n)
print("Fact is",sum)
P a g e 21 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
STRINGS
• Strings
• String slices
• Immutability
• String functions and methods
• String module
Strings:
• A string is defined as a sequence of characters represented in quotation marks (either single
quotes ( ‘ ) or double quotes ( “ ).
• An individual character in a string is accessed using an index.
• The index should always be an integer (positive or negative).
• An index starts from 0 to n-1.
• Strings are immutable i.e. the contents of the string cannot be changed after it is created.
• Python will get the input at run time by default as a string.
• Python does not support character data type. A string of size 1 can be treated as a character.
Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Membership
P a g e 22 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
String slices:
A part of a string is called a string slice.
The process of extracting a substring from a string is called slicing.
Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
P a g e 23 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
String built in functions and methods: A method is a function that “belongs to” an object.
P a g e 24 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
String modules:
A module is a file containing Python definitions, functions, and statements.
The standard library of Python is extended as modules.
Once we import a module, we can reference or use to any of its functions or variables in our
code.
There is large number of standard modules also available in python.
Standard modules can be imported the same way as we import our user-defined modules.
Syntax:
import module_name
Example
import string Output
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y birthday")) ./:;<=>?@[\]^_`{|}~
Happy Birthday
print(string.hexdigits)
0123456789abcdefABCDEF
print(string.octdigits) 01234567
P a g e 25 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
List as an array:
Array:
An array is a collection of similar elements.
Elements in the array can be accessed by index. The index starts with 0.
An array can be handled in python by a module named array.
To create an array have to import an array module into the program.
Syntax :
import array
Example:
a=array.array(‘i’,[1,2,3,4])
a- array name
array- module name
i- integer datatype
P a g e 26 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Example
Program to find sum of array elements
import array
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
Output
10
Output
35
P a g e 27 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
Methods in array
a=[2,3,4,5]
P a g e 28 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
ILLUSTRATIVE PROGRAMS:
1. Square root using newtons method:
def newtonsqrt(n):
root=n/2
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
Output:
enter number to find Sqrt: 9
3.0
Output
Enter a number1:8
Enter a number2:24
8
P a g e 29 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
3. Exponent of number
def power(base,exp):
if(exp==1):
return(base)
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value:"))
result=power(base,exp)
print("Result:",result)
Output:
Enter base: 2
Enter exponential value:3
Result: 8
output:
the sum is 35
P a g e 30 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 3
5. Linear search
a=[20,30,40,50,60,70,89]
print(a)
search=eval(input("enter a element to search:"))
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found")
Output
[20, 30, 40, 50, 60, 70, 89]
enter a element to search:30
element found at 2
6. Binary search
a=[20, 30, 40, 50, 60, 70, 89]
print(a)
search=eval(input("enter a element to search:"))
start=0
stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("elemrnt found at",mid+1)
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")
Output
[20, 30, 40, 50, 60, 70, 89]
enter a element to search:30
element found at 2
P a g e 31 | 31
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
UNIT 4
LISTS, TUPLES, DICTIONARIES
Lists: Defining list and list slicing, list operations, list slices, list methods, list loop, List
Manipulation, mutability, aliasing, cloning lists, list parameters; Lists as arrays, Tuples: tuple
assignment, tuple as return value, Tuple Manipulation; Dictionaries: operations and methods;
advanced list processing – list comprehension; Illustrative programs: selection sort, insertion
sort, mergesort, histogram.
LISTS
A list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The
values in a list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets
([ and ]):
Examples [10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
The first example is a list of four integers. The second is a list of three strings. The elements of a list
don’t have to be the same type. The following list contains a string, a float, an integer, and (lo!) another
list:
['spam', 2.0, 5, [10, 20]]
A list within another list is nested. A list that contains no elements is called an empty list; you can
create one with empty brackets, [].
As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
Unlike strings, lists are mutable. When the bracket operator appears on the left side of an assignment,
it identifies the element of the list that will be assigned.
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers
[17, 5]
The one-eth element of numbers, which used to be 123, is now 5.
A list is a relationship between indices and elements. This relationship is called a mapping; each index
“maps to” one of the elements.
The in-operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
2. Traversing a list
The most common way to traverse the elements of a list is with a for loop. The syntax is the same as
for strings:
Example:
for cheese in cheeses:
print cheese
P a g e 2 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
This works well if you only need to read the elements of the list. But if you want to write or update the
elements, you need the indices. A common way to do that is to combine the functions range and len:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element. len returns the number of elements in the list.
range returns a list of indices from 0 to n 1, where n is the length of the list. Each time through the loop
i gets the index of the next element. The assignment statement in the body uses i to read the old value
of the element and to assign the new value. A for loop over an empty list never executes the body:
for x in []:
print 'This never happens.'
Although a list can contain another list, the nested list still counts as a single element.
The length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
3. List operations
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c=a+b
>>> print c
[1, 2, 3, 4, 5, 6]
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.
P a g e 3 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
4. List slices
The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
t[3:] ['d', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to
the end. So if you omit both, the slice is a copy of the whole list.
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle
or mutilate lists.
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t
['a', 'x', 'y', 'd', 'e', 'f']
5. List methods
Python provides methods that operate on lists. For example, append adds a new element to the end of
a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t
['a', 'b', 'c', 'd']
extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
P a g e 4 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
>>> print t1
['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified.
sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t
['a', 'b', 'c', 'd', 'e']
List methods are all void; they modify the list and return None.
6. List Loop
In Python, lists are considered a type of iterable. An iterable is a data type that can return its elements
separately, i.e., one at a time.
for <item> in <iterable>:
<body>
Example:
>>>names = ["Uma","Utta","Ursula","Eunice","Unix"]
>>>for name in names:
...print("Hi "+ name +"!")
6.1 Map, filter and reduce
To add up all the numbers in a list, you can use a loop like this:
def add_all(t):
total = 0
for x in t:
total += x
return total
total is initialized to 0. Each time through the loop, x gets one element from the list. The += operator
provides a short way to update a variable. This augmented assignment statement:
total += x
is equivalent to: total = total + x
P a g e 5 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
As the loop executes, total accumulates the sum of the elements; a variable used this way is sometimes
called an accumulator.
Adding up the elements of a list is such a common operation that Python provides it as a built-in
function, sum:
>>> t = [1, 2, 3]
>>> sum(t)
6
An operation like this that combines a sequence of elements into a single value is some times
called reduce.
7. Deleting elements
There are several ways to delete elements from a list. If you know the index of the elementyou want,
you can use pop:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print t
['a', 'c']
>>> print x
b
pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes
and returns the last element.
If you don’t need the removed value, you can use the del operator:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print t
['a', 'c']
If you know the element you want to remove (but not the index), you can use remove:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print t
['a', 'c']
P a g e 6 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
P a g e 7 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
In this case the delimiter is a space character, so join puts a space between words. To concatenate
strings without spaces, you can use the empty string, '', as a delimiter.
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
In this example, Python only created one string object, and both a and b refer to it. But when you create
two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
In this case, we would say that the two lists are equivalent. After all, they have the same
elements, but not identical, because they are not the same object.
If two objects are identical, they are also equivalent, but if they are equivalent, they are not
necessarily identical.
Until now, we have been using “object” and “value” interchangeably, but it is more precise to
say that an object has a value.
If you execute [1,2,3], you get a list object whose value is a sequence of integers.
If another list has the same elements, we say it has the same value, but it is not the same object.
P a g e 8 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
10. Aliasing
If a refers to an object and you assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b=a
>>> b is a
True
The association of a variable with an object is called a reference. In this example, there are two
references to the same object.
An object with more than one reference has more than one name, so we say that the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:
>>> b[0] = 17
>>> print a
[17, 2, 3]
Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when you
are working with mutable objects.
For immutable objects like strings, aliasing is not as much of a problem.
In this example:
a = 'banana'
b = 'banana'
It rarely makes a difference whether a and b refer to the same string or not.
11. Coloning Lists
Cloning means making an exact but separate copy. create a new list and copy every element
Eg:
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)
P a g e 9 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
An alternative is to write a function that creates and returns a new list. For example, tail returns all but
the first element of a list:
def tail(t):
return t[1:]
This function leaves the original list unmodified. Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> print rest
['b', 'c']
TUPLES
1. Tuples are immutable
A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in
that respect tuples are a lot like lists. The important difference is that tuples are immutable.
Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses:
>>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, you have to include a final comma:
>>> t1 = 'a',
>>> type(t1) <type 'tuple'>
A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty
tuple:
>>> t = tuple()
>>> print t
()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the
sequence:
P a g e 11 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
>>> t = tuple('lupins')
>>> print t
('l', 'u', 'p', 'i', 'n', 's')
Because tuple is the name of a built-in function, you should avoid using it as a variable name.
Most list operators also work on tuples. The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'
And the slice operator selects a range of elements.
>>> print t[1:3]
('b', 'c')
But if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
You can’t modify the elements of a tuple, but you can replace one tuple with another:
>>> t = ('A',) + t[1:]
>>> print t
('A', 'b', 'c', 'd', 'e')
2. Tuple assignment
It is often useful to swap the values of two variables. With conventional assignments, you have to use
a temporary variable. For example, to swap a and b:
>>> temp = a
>>> a=b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to
its respective variable. All the expressions on the right side are evaluated before any of the assignments.
P a g e 12 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
The number of variables on the left and the number of values on the right have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list or tuple). For example, to split
an email address into a user name and a domain, you could write:
>>> addr = 'monty@python.org'
>>> uname, domain = addr.split('@')
The return value from split is a list with two elements; the first element is assigned to uname, the
second to domain.
>>> print uname monty
>>> print domain python.org
P a g e 13 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
max and min are built-in functions that find the largest and smallest elements of
a sequence. min_max computes both and returns a tuple of two values.
The gather parameter can have any name you like, but args is conventional. Here’s howthe function
works:
>>> printall(1, 2.0, '3')
(1, 2.0, '3')
The complement of gather is scatter. If you have a sequence of values and you want to pass it to a
function as multiple arguments, you can use the * operator. For example, divmod takes exactly two
arguments; it doesn’t work with a tuple:
>>> t = (7, 3)
>>> divmod(t)
TypeError: divmod expected 2 arguments, got 1
But if you scatter the tuple, it works:
>>> divmod(*t)
(2, 1)
>>> max(1,2,3)
3
But sum does not.
>>> sum(1,2,3)
TypeError: sum expected at most 2 arguments, got 3
Practice: Write a function called sumall that takes any number of arguments and returns their
sum.
P a g e 14 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
P a g e 15 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
If you need to traverse the elements of a sequence and their indices, you can use the built-in function
enumerate:
for index, element in enumerate('abc'):
print index, element
The output of this loop is:
0a
1b
2c
Again.
P a g e 16 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
It is common to use tuples as keys in dictionaries (primarily because you can’t use lists). For example,
a telephone directory might map from last-name, first-name pairs to telephone numbers. Assuming
that we have defined last, first and number, we could write: directory[last,first] = number
The expression in brackets is a tuple. We could use tuple assignment to traverse this dictionary.
7. Comparing tuples
The relational operators work with tuples and other sequences; Python starts by comparing the first
element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds
elements that differ. Subsequent elements are not considered (even if they are really big).
>>> (0, 1, 2) < (0, 3, 4)
True
P a g e 17 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
PYTHON DICTIONARY
Python dictionary is an unordered collection of items. While other compound data types have only
value as an element, a dictionary has a key: value pair.
1. How to create a dictionary?
Creating a dictionary is as simple as placing items inside curly braces {} separated by a comma.
An item has a key and the corresponding value is expressed as a pair, key: value. While values can be
of any data type and can repeat, keys must be of immutable type (string, number , or tuple with
immutable elements) and must be unique.
# empty dictionary
# my_dict = {}
P a g e 18 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# Output: 26
print(my_dict.get('age'))
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
P a g e 20 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
# Output: {2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
P a g e 21 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
P a g e 22 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
list(sorted(marks.keys()))
P a g e 23 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
P a g e 24 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
ILLUSTRATIVE PROGRAM
data = []
print('Selection Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate s :')
for i in range(0,n-1):
small=int(data[i])
pos=i
for j in range(i+1,n):
if int(data[j])<small:
small=int(data[j])
pos=j
temp=data[i]
data[i]=data[pos]
data[pos]=temp
print(data)
print('Sorted Array :')
print(data)
P a g e 25 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
data = []
print('Insertion Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate s :')
for i in range(1,n):
temp=int(data[i])
j=i-1
while temp<int(data[j]) and j>=0:
data[j+1]=data[j]
j=j-1
data[j+1]=temp
print(data)
print('Sorted Array is:')
print(data)
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
P a g e 26 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if int(lefthalf[i]) < int(righthalf[j]):
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
data = []
print('Merge Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
P a g e 27 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 4
print('Intermediate s :')
mergeSort(data)
print('Sorted Array is:')
print(data)
4. HISTOGRAM PROGRAM
P a g e 28 | 28
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
UNIT 5
FILES, MODULES, PACKAGES
Files and exception: Concept of Files, Text Files; File opening in various modes and closing of a
file, Format Operators, Reading from a file, Writing onto a file, File functions-open(), close(),
read(), readline(), readlines(),write(), writelines(),tell(),seek(), Command Line arguments.
Errors and exceptions, handling exceptions, modules, packages; introduction to numpy,
matplotlib. Illustrative programs: word count, copy file.
FILES
❖ A file is a named location on a disk to store related information.
❖ It is used to permanently store data in non-volatile memory (e.g. hard disk).
❖ Since random access memory (RAM) is volatile and loses its data when a computer is turned
off, we use files for future use of the data.
❖ When we want to read from or write to a file we need to open it first. When we are done, it
needs to be closed, so that resources that are tied to the file are freed.
Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform the operation)
3. Close the file
1. Opening a file
Python has a built-in function open() to open a file. This function returns a file object, also called a
handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python33/README.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write
'w', or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file. On the
other hand, the binary mode returns bytes and this is the mode to be used when dealing with non-text
files like image or exe files.
Python File Modes
Mode: Description
❖ 'r': Open a file for reading. (default)
❖ 'w': Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
❖ 'x': Open a file for exclusive creation. If the file already exists, the operation fails.
❖ 'a': Open for appending at the end of the file without truncating it. Creates a new file if it does
not exist.
P a g e 1 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
2. Closing a File
❖ When we are done with operations on the file, we need to properly close it.
❖ Closing a file will free up the resources that were tied to the file and is done using the close()
method.
❖ Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file.
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
This method is not entirely safe. If an exception occurs when we are performing some operation with
the file, the code exits without closing the file. A safer way is to use a try...finally block.
try:
f= open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This way, we are guaranteed that the file is properly closed even if an exception is raised, causing the
program flow to stop.
The best way to do this is by using the statement. This ensures that the file is closed when the block
inside with is exited.
We don't need to explicitly call the close() method. It is done internally.
with open("test.txt",encoding = 'utf-8') as f:
# perform file operations
P a g e 2 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
P a g e 3 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
❖ An alternative is to use the format operator, %. When applied to integers, % is the modulus
operator. But when the first operand is a string, % is the format operator.
❖ The first operand is the format string, which contains one or more format sequences, which
specify how the second operand is formatted. The result is a string.
For example, the format sequence '%d' means that the second operand should be formatted as an integer
(d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
The result is the string '42', which is not to be confused with the integer value 42. A format sequence
can appear anywhere in the string, so you can embed a value in a sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
❖ If there is more than one format sequence in the string, the second argument has to be a tuple.
❖ Each format sequence is matched with an element of the tuple, in order.
The following example uses '%d' to format an integer, '%g' to format a floating-point number, and '%s'
to format a string:
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'
The number of elements in the tuple has to match the number of format sequences in the string. Also,
the types of elements have to match the format sequences:
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: illegal argument type for built-in operation
P a g e 4 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
Here Python script name is script.py and the rest of the three arguments - arg1 arg2 arg3 is command
line arguments for the program. There are following three Python modules that are helpful in parsing
and managing the command line arguments:
1. sys module
2. getopt module
3. argparse module
1. sys module - System-specific parameters
The Python sys module provides access to any command-line arguments via the sys.argv. This serves
two purposes −
• sys.argv is the list of command-line arguments.
• len(sys.argv) is the number of command-line arguments.
Here sys.argv[0] is the program ie. script name.
Example
Consider the following script test.py −
import sys
P a g e 5 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
EXCEPTION
Python (interpreter) raises exceptions when it encounters errors. Error caused by not following the
proper structure (syntax) of the language is called syntax error or parsing error.
>>> if a < 3
File "<interactive input>", line 1
if a < 3
SyntaxError: invalid syntax
❖ Errors can also occur at runtime and these are called exceptions.
P a g e 6 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
❖ They occur, for example, when a file we try to open does not exist (FileNotFoundError),
dividing a number by zero (ZeroDivisionError), the module we try to import is not found
(ImportError), etc.
❖ Whenever these types of runtime errors occur, Python creates an exception object.
❖ If not handled properly, it prints a traceback to that error along with some details about why
that error occurred.
>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero
>>> open("imaginary.txt")
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
P a g e 8 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
a=5
b='0'
print (a+b)
except TypeError:
print('Unsupported operation')
print ("Out of try except blocks")
Output
Unsupported operation
Out of try except blocks
2.2 try...finally
❖ The try statement in Python can have an optional finally clause. This clause is executed no
matter what and is generally used to release external resources.
❖ For example, we may be connected to a remote data center through the network or working
with a file, or working with a Graphical User Interface (GUI).
❖ In all these circumstances, we must clean up the resource once used, whether it was successful
or not. These actions (closing a file, GUI, or disconnecting from the network) are performed in
the finally clause to guarantee execution.
Syntax and Examples for various try and finally blocks
Syntax: Example: try...except blocks try:
try : a=5
#statements in the try block b='0'
except : print(a/b)
#executed when an error in the try except:
block
print('Some error occurred.')
print("Out of try except blocks.")
Output
Some error occurred.
Out of try except blocks.
Syntax: Example: Multiple except Blocks
try :
try:
#statements in the try block
a=5
except1 :
b=0
P a g e 9 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
Output
try block
Enter a number: 10
Enter another number: 2
else block
Division = 5.0
finally block
Out of try, except, else and finally blocks.
P a g e 10 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
MODULES
Any file that contains Python code can be imported as a module. For example, suppose you have a file
named wc.py with the following code:
def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
print linecount('wc.py')
If you run this program, it reads itself and prints the number of lines in the file, which is 7.
You can also import it like this:
>>> import wc
7
Now you have a module object wc:
>>> print wc
<module 'wc' from 'wc.py'>
>>> wc.linecount('wc.py')
7
P a g e 11 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
yy= 2017
mm = 8
PACKAGE
A package is a collection of modules. A Python package can have sub-packages and modules.
A directory must contain a file named __init__.py for Python to consider it as a package. This file can
be left empty but we generally place the initialization code for that package in this file.
Here is an example. Suppose we are developing a game, one possible organization of packages and
modules could be as shown in the figure below.
P a g e 12 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
❖ Although easier, this method is not recommended. Using the full namespace avoids confusion
and prevents two same identifier names from colliding.
❖ While importing packages, Python looks in the list of directories defined in sys.path, similar
to the module search path.
P a g e 13 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
x = np.arange(1,11)
y=2*x+5
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x,y)
plt.show()
A ndarray object x is created from np.arange() function as the values on the x axis. The corresponding
values on the y-axis are stored in another ndarray object y. These values are plotted using the
plot() function of pyplot submodule of matplotlib package.
The graphical representation is displayed by show() function.
The above code should produce the following output −
P a g e 14 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
ILLUSTRATION PROGRAM
1. Word Count
import sys
file=open("/Python27/note.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
file.close();
print ("%-30s %s " %('Words in the File' , 'Count'))
for key in wordcount.keys():
print ("%-30s %d " %(key , wordcount[key]))
P a g e 15 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
1. Write a function that copies a file reading and writing up to 50 characters at a time.
def exists(filename):
try:
f = open(filename)
f.close()
return True
except IOError:
return False
P a g e 16 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
3. Write a python program to count number of lines, words and characters in a text file. def
wordCount():
cl=0
cw=0
cc=0
f=open("ex88.txt","r") for line in f:
words=line.split()
cl +=1
cw +=len(words)
cc+=len(line)
print('No. of lines:',cl)
print('No. of words:',cw)
print('No. of characters:',cc)
f.close()
import sys
def inputCmd():
print ("Name of the script:", sys.argv[0])
print ("Number of arguments:", len(sys.argv))
P a g e 17 | 18
St. Joseph’s College of Engineering
GE1105 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT - 5
5. Mention the commands and their syntax for the following: get current directory, changing
directory, list, directories and files, make a new directory, renaming and removing directory.
P a g e 18 | 18
St. Joseph’s College of Engineering