Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Flowchart
Example:
a=10
if a>9:
print(“a is Greater than 9”)
Output:
a is Greater than 9
Example:
a=10
b=20
if a>b:
print(“a greater than b”)
else:
print(“b is greater than a”)
Output:
b is greater than a
Flowchart:
F
expressio
n1
T F
statement1 expressio
n2
T F
statement2 expressio
n3
T
statement3 statement4
Output:
b is greatest
if(condition 1):
if(condition 2):
True statement 2
else:
False statement 2
else:
False statement 1
Flowchart
F
Condition
1
T False statement 1
T
F
Condition
2
Example:
x=10
y=20
if x == y:
print('x and y are equal')
else:
if x < y:
PPG INSTITUTE OF TECHNOLOGY Page 6
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
Output:
x is less than y
3.3 ITERATION:
Iteration/Looping is defined as the block of statements which are repeatedly executed
for certain number of times or until a particular condition is satisfied.
Types of Iteration/Looping:
While loop
For loop
Nested loop
3.3.1 While loop
It is a repetitive control structure, used to execute the statements within the body,
until the condition satisfies.
The while loop is an entry controlled loop statement, which means the condition is
evaluated first and if it is true, then the body of the loop is executed.
Syntax:
while( condition):
body of the loop
Flow Chart:
F
conditio
n
Flowchart
If no more item in
sequence
Items in
sequenc
e
Next item from
sequence
Statements
Output:
1 1
1 2
1 3
1 4
Syntax:
while(expression):
statement_1
statement_2
......
else:
statement_3
statement_4
......
Example 1: Program to illustrate the else in while loop
count = 0
count = count + 1
else:
Output:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
print(“Iteration Over”)
Output:
0
1
2
3
4
Iteration Over
Flowchart of break
Output:
s
t
r
The end
3.3.5.2 Python continue statement
It is used to continue with the next iteration of the loop by skipping its remaining
body of the loop
Syntax:
continue
Flowchart of continue
Output:
s
t
r
n
g
The end
break continue
Terminates the loop Continue with the next iteration of the loop
Syntax: Syntax:
break continue
Exits the loop It never terminates the loop
Ex: pow,abs,sqrt
The built-in functions we have used, such as abs, pow, and max, have produced
results.
Ex:
e = math.exp(1.0)
Example for a fruitful function:
def area(radius):
a = math.pi * radius**2
return a
In the above example, the function returns a value. It is also possible to include an
expression in the return statement as follows.
Example:
def area(radius):
return math.pi * radius**2
Sometimes it is useful to have multiple return statements, one in each branch of a
conditional as follows:
def absolute_value(x):
if x < 0:
return -x
else:
return x
Since these return statements are in an alternative conditional, only one runs.
As soon as a return statement runs, the function terminates without executing any
subsequent statements.
Code that appears after a return statement, or any other place the flow of execution
can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through the
program hits a return statement.
For example:
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x
3.4.2 Parameters:
When a function is invoked, a value is passed to the parameter. This value is referred
to as actual parameter or argument. Parameters provide the data communication
between calling function and called function.
Two types:
Actual parameters:
These are the parameters transferred from the calling function [main function]
to the called function [user defined function].
Formal parameters:
Passing the parameters from the called functions [user defined function] to the
calling functions [main function].
Note:
Actual parameter – This is the argument which is used in function call.
Formal parameter – This is the argument which is used in function definition.
declared functions.
Local variables exist within functions. Global Variables exist outside of functions.
Let’s look at another example where we use the same variable name for a global
variable and a local variable:
num1 = 5
def my_function():
num1 = 10
num2 = 7
print(num1)
print(num2)
my_function()
print(num1)
Output
10
7
5
Inside the function num1 has the value 10 since it is locally assigned and outside the
function num1 has the value 5 since it has global value.
We can create a global variables within a function by using Python’s global statement
as follows:
def new_shark():
global shark
shark = "Sammy"
new_shark()
print(shark)
Output:
Sammy
>>> is_divisible(6, 4)
False
>>> is_divisible(6, 3)
True
The result of the == operator is a boolean, so we can write the function more
concisely by returning it directly:
def is_divisible(x, y):
return x % y == 0
Boolean functions are often used in conditional statements:
if is_divisible(x, y):
print 'x is divisible by y'
3.4.6 Recursion:
A function that calls itself is recursive; the process of executing it is called
recursion.
Computing the factorial of a number using recursion
The factorial of an integer n, which is written as n!, is the result of multiplying n by
all of the positive integers less than n. For instance, 3! = 3 x 2 x 1, which results in 6
and 4! = 4 x 3 x 2 x 1, which results in 24.
An efficient way to calculate a factorial is by using a recursive function.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input())
print(factorial(n))
3.5 STRINGS
A String is a sequence of characters .i.e they can be a letter, a number, special
symbols or combination of these types.
Python permits to represent the string either by using single or double quote.
Python strings are “immutable” which means they cannot be changed after they are
created.
Example :
>>>str= “Hello Python”
>>>print(str)
Hello Python
We can access the characters one at a time using bracket operator.
>>>letter=fruit[1]
It selects character number 1 from fruit and assigns it to a letter.
The expression in brackets is called an index.
The index indicates which character in the sequence we need.
An index may be expressions that contain variables and operators.
>>>fruit=`banana`
>>>i=1
>>>fruit[i]
`a`
>>>fruit[i+1]
`n`
But the value of the index has to be an integer.
>>>letter=fruit[1.5]
TypeError:String indices must be integers.
len:
len is a built-in function that returns the number of characters in a string:
>>>fruit=`banana`
>>>len(fruit)
6
To get the last character, we have to subtract from length.
>>>last=fruit[length-1]
>>>last
`a`
>>>last=fruit[length]
IndexError:string index out of range
The reason for IndexError is that there is no letter in ‘banana’ with index 6 since the
count starts from 0, the six letters are numbered as 0 to 5.
>>>fruit[-1] which yields the last character.
B A N A N A
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1
Example:
Fruit=”banana”
print(fruit[0]) #return 1st character
#output:b
print(fruit[-1]) #return last character
#output:a
print(fruit[-2]) #return last second character
#output:n
3.5.1 String Slices:
To retrieve a range of characters in a String we use “Slicing Operator”, the colon
“:”
With the slicing operator, we define the range as [a:b]. It’ll let us print all the
characters of the String starting from index ‘a’ up to character at index ‘b-1’.
So the character at index ‘b’ is not a part of the output.
Example:
sample_str = 'Python String'
print (sample_str[3:5])
print (sample_str[7:])
print (sample_str[:6])
print (sample_str[7:-4])
Output
ho
String
Python
St
True
>>>print(str1.endswith(“String”,0,
27))
False
Returns true if string contains >>>str1=”StringString3”
only digits and false >>>str2=”4567”
otherwise. >>>print(str1.isdigit())
11 isdigit()
False
>>>print(str2.isdigit())
True
This method will return a title >>>str1=”string string string”
case version of the given >>>print(str1.title())
string, where the first letter of String String String
12 title()
a word is in uppercase and the
rest of the characters in the
lower case
This method will return true, >>>str1=” “
if the given string contains >>>print(str1.isspace())
13 isspace
only whitespace characters True
and false otherwise
This method will return true, >>>str1=”String String”
if the given string is a title >>>print(str1.istitle())
14 istitle() cased string and it should True
have at least one character
and false otherwise
This method will return true, >>>str1=”String String”
15 isupper() if all the characters in >>>print(str1.isupper())
uppercase and false otherwise True
This method will return true, >>>str1=”String String”
16 islower if all the characters in >>>print(str1.islower())
lowercase and false otherwise False
Many string module functions are also available as string object methods.
This module contains constants for a number of frequently used collection of
characters.
Example for constants:
import string
print(string.digits)
print(string.hexdigits)
print(string.octdigits)
print(string.punctuation)
print(string.whitespace)
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
Output:
0123456789
0123456789abcdefABCDEF
01234567
!”#$%&’()*+,-./:;?@[\]^_’{|}`
‘\011\012\013\014\015’
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Example 2: Functions
import string
text="Monty Python's Flying Circus"
print(string.upper(text))
print(string.lower(text))
print(string.split(text))
print(string.join(string.split(text), "+"))
print(string.replace(text, "Python", "Java"))
print(string.find(text, "Python"), string.find(text, "Java"))
print(string.count(text, "i"))
PPG INSTITUTE OF TECHNOLOGY Page 30
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
Output:
MONTY PYTHON'S FLYING CIRCUS
monty python's flying circus
['Monty', "Python's", 'Flying', 'Circus']
Monty+Python's+Flying+Circus
Monty Java's Flying Circus
(6, -1)
2
3.8 ILLUSTRATIVE PROBLEMS:
1. Square root of a number
def newtonSqrt(n, howmany):
approx = 0.5 * n
for i in range(howmany):
betterapprox = 0.5 * (approx + n/approx)
approx = betterapprox
return betterapprox
print(newtonSqrt(10, 3))
print(newtonSqrt(10, 5))
print(newtonSqrt(10, 10))
Output:
3.16231942215
3.16227766017
3.16227766017
3. Exponentiation
n=int(input("Enter a number :"))
p=int(input("Enter its power :"))
pow=1
for i in range(1,p+1):
pow=pow*n
print (pow)
Output:
Enter a number :2
Enter its power :3
8
5. Linear search
def linearSearch(myList, searchColour):
flag=0
for i in range(len(myList)):
if myList[i] == searchColour:
flag=1
break
if flag:
print("Color is found at index", i)
else:
print("Color is not found at index")
myList = ['Red', 'Blue', 'Yellow', 'White', 'Black']
searchColour = input("Enter a Color:")
linearSearch(myList, searchColour)
Output
Enter a Color: Red
Color is found at index 0
6. Binary Search
myList = [5, 10, 12, 24, 34, 47, 54]
def binarySearch(myList, searchNum):
firstNum = 0
lastNum = len(myList)-1
result = False
while(result == False and firstNum <= lastNum):
midNum = (firstNum + lastNum)//2
if myList[midNum] == searchNum:
result = True
else:
if searchNum < myList[midNum]:
lastNum = midNum - 1
else:
firstNum = midNum + 1
return result
searchNum = (int(input("Enter the number to be search")))
PPG INSTITUTE OF TECHNOLOGY Page 33
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
Output:
Enter the number to be search 12
Number found and the number is: 12