0% found this document useful (0 votes)
171 views80 pages

Module 3 Merged

This document provides an introduction to problem solving and programming using Python. It discusses fundamental algorithms like exchange values, counting, summation, and more. It also covers Python control flow and functions. Specifically, it describes conditionals like if, if-else, if-elif-else statements and iteration statements like for, while loops. It provides examples of using conditional statements, loops, nested loops, and the range() function in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
171 views80 pages

Module 3 Merged

This document provides an introduction to problem solving and programming using Python. It discusses fundamental algorithms like exchange values, counting, summation, and more. It also covers Python control flow and functions. Specifically, it describes conditionals like if, if-else, if-elif-else statements and iteration statements like for, while loops. It provides examples of using conditional statements, loops, nested loops, and the range() function in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

VIT Bhopal University

Bhopal-Indore Highway, Kothri Kalan, Sehore, Madhya Pradesh – 466114.

Introduction to Problem Solving and Programming


Course Code: CSE 1021
Chapter 3

By: Akshay Jadhav


CHApTeR 3:
SyLLAbus
Fundamental Algorithms: Python Control Flow, Functions:
– Introduction
– Exchange the values –Conditionals: Boolean values and
– Counting operators, conditional (if, if- else,
– Summation if-elif-else)
– Factorial Computation
– Fibonacci Sequence –Iteration statements (state, while, for
– Reverse break, continue, pass
– Base Conversion
– Character to Number Conversion
PyTHOn COnTROL
flLw , funcCiIns
A program’s control flow is the order in which the program’s code executes.

The control flow of a Python program is regulated by conditional statements, loops, and
function calls.

● Conditional Statements- if, if-else, nested if-else


● Loops- for , while loops
● Function Calls.
COndiTiOnAL
sT
● ATemenTs
Decision making is the most important aspect of almost all the programming
languages.
● Decision making allows us to run a particular block of code for a particular
decision
● Condition checking is the backbone of decision making.
COndiTiOnAL
sT ATemenTs in pyTHOn
If Statement
The if statement is used to test a specific condition. If the condition is true, a block of code
(if-block) will be executed.

If - else Statement
The if-else statement is similar to if statement except the fact that, it also provides the
block of the code for the false case of the condition to be checked. If the
condition provided in the if statement is false, then the else statement will be executed.

Nested if Statement
Nested if statements enable us to use if - else statement inside an outer if statement.
‘IF’
sT ATemenT
The if statement is used to test a specific
condition. If the condition is true, a block of
code (if-block) will be executed.

if condition:
statement
‘IF’
sT ATe
Example: 1 menT Example: 2
a = int(input("Enter a? "));
num = int(input("enter the
b = int(input("Enter b? "));
number?")) c = int(input("Enter c? "));

if num%2 == 0:
if a>b and a>c:
print("Number is print("a is largest");
even")
if b>a and b>c:
print("b is largest");

if c>a and c>b:


print("c is largest");
‘IF-ELSE’
sT ATemenT
The if-else statement is similar to if
statement except the fact that, it also
provides the block of the code for the false
case of the condition to be checked. If the
condition provided in the ‘if’ statement is
false, then the else statement will be
executed. (Alternative Execution)

if condition:
block of statements
else:
another block of statements
‘IF-ELSE’
sT ATe
Example: 1 menT
age = int (input("Enter your age? "))

if age>=18:

print("You are eligible to vote !!");

else:
Example: 2
print("Sorry! you have to wait !!");
num = int(input("enter the number?"))

if num%2 == 0:

print("Number is even...")

else:

print("Number is odd...")
‘ELIF’
sT
It isATe menTused
a keyword in Python in
replacement of else if to place another
condition in the program. This is called
Chained condition.

Chained conditions allows more than two


possibilities and need more than two
branches.
if condition:
expression
elif condition:
expression
else:
expression
‘ELIF’
STA TEMENTS
The elif statement enables us to check if condition 1:
multiple conditions and execute the block of statements

specific block of statements depending elif condition 2:


upon the true condition among them. block of statements

The elif statement works like an if-else-if elif condition 3:


ladder statement in C. It must block of statements
be succeeded by an if statement.
else:
The syntax of the elif statement is given block of statements

below.
‘ELIF’
STATEMENTS
Example: 1 Example: 2
a = int(input("Enter a? ")); marks = int(input("Enter the marks? "))
b = int(input("Enter b? ")); if marks > 85 and marks <= 100:
c = int(input("Enter c? "));
print("Congrats ! you scored grade A ...")

if a>b and a>c: elif marks > 60 and marks <= 85:
print("a is largest"); print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
elif b>a and b>c: print("You scored grade B ...")
print("b is largest"); elif (marks > 30 and marks <=
40): print("You scored grade
else:
print("c is largest"); C ...")
else:
print("Sorry you are
fail ?")
‘NESTED IF-ELSE’
STA TEMENTS
We can write the entire ‘if-else’ statement Syntax:
in another ‘if-else’ statement, is called if condition 1:
block of statements
Nesting and statement is called ‘Nested if-
else’. if condition 1:
block of statements
In a nested if construct, you can have an
‘if-elif-else’ construct inside an ‘if-elif- elif condition 2:
block of statements
else’ construct.
else:
block of statements
‘NESTED IF-ELSE’
STATEMENTS
if condition 1:

if condition 2:
Statement 1

else:
Statement 2

else:
Statement 3

Statement x
‘NESTED IF-ELSE’
STATEMENTS
Example:

num = float(input("Enter a number: "))

if num >= 0:

if num == 0:

print("Zero")

else:

print("Po
sitive
number")

else:

print("Negative number")
ITeRATiVe
sT
● ATemenTs
The flow of the programs written in
any programming language is
sequential by default. Sometimes we
may need to alter the flow of the
program.
● The execution of a specific code may
need to be repeated several numbers
of times.
AdVAnTAGes Of LOOps OR
iTe RATiVe sTATemenTs
1. It provides code reusability.
2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures.
ITeRATiVe
sT ATemenTs in
for loop
p yTHOn
The for loop is used in the case where we need to execute some part of the code until the
given condition is satisfied. The for loop is also called as a per-tested loop. It is better to
use ‘for’ loop if the number of iteration is known in advance.

while loop
The while loop is to be used in the scenario where we don't know the number of iterations
in advance. The block of statements is executed in the while loop until the condition
specified in the while loop is satisfied. It is also called a pre-tested loop.
‘FOR’
LOOp
The ‘for’ loop in Python is used to iterate
the statements or a part of the program
repeatedly until the condition become
false.

It is frequently used to traverse the


data structures like list, tuple, or
dictionary.

Syntax:
for iterating_var in sequence:

statement(s)
Output: 1
‘FOR’ LOOp P
Y
Example: 1 T
str = "Python" H
for i in str:
print(i) o
n

Example: 2 Output: 2

list = [10,30,23,43,65,12] The sum is: 183


sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)
‘FOR’
LOOp
Example: 3 Example: 4

list = [1,2,3,4,5,6,7,8,9,10] n = int(input("Enter the number "))


n = 5 for i in range(1,11):
for i in list: c = n*i
c = n*i print(n,"*",i,"=",c)
print(c)
‘range()’
funcTiOn
The range() function is used to generate the sequence of the numbers. If we pass the range(10),
it will generate the numbers from 0 to 9. The syntax of the range() function is given below.

range(start,stop,step size)

● The start represents the beginning of the iteration.


● The stop represents that the loop will iterate till stop-1. The range(1,5) will generate
numbers 1 to 4 iterations. It is optional.
● The step size is used to skip the specific numbers from the iteration. It is optional to use.
By default, the step size is 1. It is optional.
‘NESTED FOR’
LOOp
Python allows us to nest any number of for loops inside a for loop. The inner loop is
executed n number of times for every iteration of the outer loop. The syntax is
given below.

Syntax:
for iterating_var1 in sequence: outer loop

for iterating_var2 in sequence: inner loop

block of statements

Other statements
‘NESTED FOR’
LOOp
Example:

User input for number of rows

rows = int(input("Enter the rows:"))

Outer loop will print number of rows

for i in range(0,rows+1): Output:

Inner loop will print number of Asterisk(*) *


**
for j in range(i): ***
****
print("*",end = '')
*****
print()
USinG ‘ELSE’ wiTH ‘FOR’
LOOp
Example 1:
Python allows us to use the else statement with the
for i in range(0,5): for loop which can be executed only when all the
print(i) iterations are exhausted.
else:
print("for loop completely exhausted, since there is no break.")

Example: 2
for i in range(0,5):

print(i)

break;

else:print("
for loop is
exhausted");
‘WHILE’
LOOp
The Python while loop allows a part of the
code to be executed until the given condition
returns false. It is also known as a pre-tested
loop.

It can be viewed as a repeating if statement.


When we don't know the number of iterations
then the while loop is most effective to use.

Syntax:

while expression:
statements.
‘WHILE’
LOOp
Example: 1 Example: 2

i=1 i=1

while(i<=10): number=0

print(i) number =
int(inpu
i=i+1 t("Enter
the
number:"
))

while
i<=10:

print("%d X %d = %d \n"%(number,i,number*i))
USinG ‘ELSE’ wiTH ‘WHILE’
LOOp
Python allows us to use the else statement with
the while loop also. The else block is executed
when the condition given in the while statement
becomes false.
Example: 1 Example: 2
i=1
i=1
while(i<=5):
while(i<=5
): print(i)
print(i) i=i+1
i=i+1 if(i==3):
else: break
print("The while loop else:
exhausted") print("Th
e while
loop
exhausted
MORe in
LOOp
● Continue

● Break

● Pass
VIT Bhopal University
Bhopal-Indore Highway, Kothri Kalan, Sehore, Madhya Pradesh – 466114.

Introduction to Problem Solving and Programming


Course Code: CSE 1021
Chapter 3

By: Akshay Jadhav


CHApTeR 3:
SyLLAbus
Fundamental Algorithms: Python Control Flow, Functions:
– Introduction
– Exchange the values –Conditionals: Boolean values and
– Counting operators, conditional (if, if- else,
– Summation if-elif-else)
– Factorial Computation
– Fibonacci Sequence –Iteration statements (state, while, for
– Reverse break, continue, pass
– Base Conversion
– Character to Number Conversion
MORe in
LOOp
● Continue

● Break

● Pass
CONTINUE
● When the continue statement is encountered, the control transfer to the beginning of
the loop.
● The continue statement skips the remaining lines of code inside the loop and start
with the next iteration.
● It is mainly used for a particular condition inside the loop so that we can skip some
specific code for a particular condition.
● Syntax:
loop statements
continue
the code to be skipped
continue
Example: 1 Example: 2

i = 0 str = "HelloSWorld"
while(i < 10): for i in str:
i = i+1 if(i == 'S'):
if(i == 5): continue
continue print(i)
print(i)

Output: 1 Output: 2
1 2 3 4 6 7 H e l l o W o r l d
8 9 10
QuesTi
On
i = 0 Print all the letters in the string
str1 = 'Hello to the world of Python' except ‘o’ and ‘t’?

while i < len(str1):


if str1[i] == 'o' or str1[i] == 't':
i += 1
continue
print('Current Letter :', str1[i]) i
+= 1
BREAK
● The break is a keyword in python which is used to bring the program control out
of the loop.
● The break statement breaks the loops one by one, i.e., in the case of nested loops,
it breaks the inner loop first and then proceeds to outer loops.
● In other words, we can say that break is used to abort the current execution of the
program and the control goes to the next line after the loop.
● Syntax:
loop statements

break;
break
Example: 1 Example: 2
i = 0; str = "python"
while 1: for i in str:
print(i," ",end=""), if i == 'o':
i=i+1; break
if i == 10: print(i);
break;
print("came out of while loop")

Output: 1 Output: 2
break
Example: 3

i = 0
str1 = 'Iterative_Statements'

while i < len(str1):


if str1[i] == 'v': Output: 3
i += 1
break
print('Current Letter :', str1[i]) i
+= 1
PAS
S● In Python, the pass keyword is used to execute nothing; it means, when we don't want
to execute code, the pass can be used to execute empty.
● It is the same as the name refers to. It just makes the control to pass by without
executing any code.
● If we want to bypass any code pass statement can be used.
● It is beneficial when a statement is required syntactically, but we want we don't want
to execute or execute it later.
● The difference between the comments and pass is that, comments are entirely ignored
by the Python interpreter, where the pass statement is not ignored.
pass
Example: 1 Example: 2

values = {'P', 'y', 't', 'h','o','n'} str1 = 'javatpoint'


for val in values: i = 0
pass
while i < len(str1):
i += 1
pass
print('Value of
i :', i)

Output: 1
Output: 2
FundAmenTAL
ALGORiTHms/pROGRAms
– Exchange the values
– Counting
– Summation
– Factorial Computation
– Fibonacci Sequence
– Reverse
– Base Conversion
– Character to Number Conversion
BASE
CONVERSION
CO
nT.
Decimal to Binary Conversion
def decimalToBinary(num):
if num > 0:
decimalToBinary(num // 2)
print(num % 2, end = " ")

number = int(input("Enter the decimal number: "))


main()
decimalToBinary(number)

(15)10 = (1111)2
(55)10 (256)10= (100000000)2

(110111)2

(111011)2

55 27 13 6 3 1

27 13 6 3 1 0

1 1 1 0 1 1
BinARy TO DecimAL
COnVe RsiOn
We have already seen that the Binary System is a combination of [0 or 1] with each digit
being worth two times more than the last digit, so let’s see how this information will help
us to convert binary to decimal equivalent.

Consider a Binary Number (01011)2

Digit 0 1 0 1 1
Weight 2^4=16 2^3=8 2^2=4 2^1=2 2^0=1
0 8 0 2 1

= 0 + 8 + 0 + 2 + 1 = (11)10
1 1 0 1 1 1

2^5=32 2^4=16 2^3=8 2^2=4 2^1=2 2^0=1

32*1 16*1 8*0 4*1 2*1 1*1

= 32+16+0+4+2+1 = 55
CO
nT.
Binary to Decimal Conversion:
binary = input("Enter a binary number:")
def BinaryToDecimal(binary):
decimal = 0
for digit in binary:
print(digit)
decimal = decimal*2
+ int(digit)

print("The decimal value is:", decimal)

Calling the function


BinaryToDecimal(binary)
DecImaL to OctaL
CoNVersIoN:
Decimal to Octal Conversion:
def dectoOct(decimal):
if (decimal > 0):
dectoOct((int)(decimal / 8))
print(decimal % 8, end='')

decimal = int(input("Enter a decimal number: "))


print("Octal: ", end='')
dectoOct(decimal)
CO
nT. Decimal Number: (1032)10

Octal: (2010)8
OctaL to DecImaL
CoNVersIo
Octal N
to Decimal Conversion:
Octal : (37246)8

Digit 3 7 2 4 6
Weight 8^4=4096 8^3=512 8^2=64 8^1=8 8^0=1
12288 3584 128 32 6

= 12288 + 3584 + 128 + 32 + 6 = (16038)10


CO
nT.
Octal to Decimal Conversion:
def OctalDecimal(num): user-defined function
decimal = 0
base = 1 Initializing base value to 1, i.e
8^0 while (num):
Extracting last digit
last_digit = num % 10
num = int(num / 10)

decimal += last_digit *
base base = base * 8
return decimal

take inputs
num = int(input('Enter an octal number: '))
calling function and display result
print('The decimal value is
DecImaL to HexadecImaL
CoNVersIoN
Decimal to Hexadecimal Conversion:

Decimal: (4156)10
Hexadecimal: (103C)16
CO
nT.
Decimal to Hexadecimal Conversion:
conversion_table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F']

decimal = int(input("Enter a number: "))


hexadecimal = ''

while (decimal > 0):


remainder = decimal % 16
hexadecimal = conversion_table[remainder] + hexadecimal
decimal = decimal // 16

print("Hexadecimal: ", hexadecimal)


HexadecImaL to DecImaL
CoNVersIo
Hexadecimal N Conversion:
to Decimal

Digit A=10 3 7 E= 14
Weight
16^3=4096 16^2=256 16^1=16 16^0=1

40960 768 112 14

(A37E)16 = 40960 + 768 + 112 + 14 = (41854)10


CONT
.
Hexadecimal to Decimal Conversion:

hex = 'FF'

conversion

dec = int(hex, 16)

print('Value in hexadecimal:', hex)

print('Value in decimal:', dec)


Python Program to Convert Decimal to Binary, Octal and Hexadecimal

dec = 344

print("The decimal value is", dec,)


print(bin(dec), "in binary.")
print(oct(dec), "in octal.") Output:
print(hex(dec), "in hexadecimal.")
The decimal value is: 344
0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.
COnVeR
shttps://www.learnpick.in/prime/documents/ppts/details/663/co
iOn
mputer-number-conversion
Number Conversion
text = "a" number = 97
number = ord(text) ascii = chr(number)

print(number) print(ascii)

Output: Output:
97 a
VIT Bhopal University
Bhopal-Indore Highway, Kothri Kalan, Sehore, Madhya Pradesh – 466114.

Introduction to Problem Solving and Programming


Course Code: CSE 1021
Chapter 3 Programming

By: Akshay Jadhav


CHApTeR 3:
SyLLAbus
Fundamental Algorithms:
– Introduction
– Exchange the values
– Counting
– Summation
– Factorial Computation
– Fibonacci Sequence
– Reverse
– Base Conversion
– Character to Number Conversion
ExcHAnGe
Of VALues
Example1:
a= int(input("Enter the number: "))
b= int(input("Enter the number: "))
print("Before swapping")
print("a=",a, "b=",b)
a,b=b,a
print("After swapping")
print("a=",a, "b=",b)
ExcHAnGe
Of VALues
Example2:
a= int(input("Enter the number: "))
b= int(input("Enter the number: "))
print("Before swapping")
print("a=",a, "b=",b)
a=a+b
b=a-b
a=a-b
print("After swapping")
print("a=",a, "b=",b)
ExcHAnGe
Of VALues
Example3:
a= int(input("Enter the number: "))
b= int(input("Enter the number: "))
print("Before swapping")
print("a=",a, "b=",b)
a=a*b
b=a/b
a=a/b
print("After swapping")
print("a=",a, "b=",b)
ExcHAnGe
Of VALues
Example4:
a= int(input("Enter the number: "))
b= int(input("Enter the number: "))
print("Before swapping")
print("a=",a, "b=",b)
temp=a
a=b
b=temp
print("After swapping")
print("a=",a, "b=",b)
ExcHAnGe
Of VALues
Example5:
a= int(input("Enter the number: "))
b= int(input("Enter the number: "))
print("Before swapping")
print("a=",a, "b=",b)
a=(a+b)-(b=a)
print("After swapping")
print("a=",a, "b=",b)
ExcHAnGe
Of VALues
Example6:
a= int(input("Enter the number: "))
b= int(input("Enter the number: "))
print("Before swapping")
print("a=",a, "b=",b)
a=a^b
b=a^b
a=a^b
print("After swapping")
print("a=",a, "b=",b)
ExcHAnGe
Of VALues
Example7:
a= int(input("Enter the number: "))
b= int(input("Enter the number: "))
print("Before swapping")
print("a=",a, "b=",b)
a= (a and b) + (a or b)
b= a + (~b) + 1
print("After
a= a + (~b) +swapping")
1
print("a=",a, "b=",b)
COun
Example1: TinG
n=int(input("Enter number:"))
count=0
while(n>0):
count=count+1
n=n//10
print(n)
print("The number
of digits in the
number
are:",count)
COun
Example2: TinG
num=int(input("Enter a number:"))
print(len(str(num)))
SummATi
Example1: On
num=int(input("Enter a number:"))
sum=0
while(num>0):
reminder=num%10
sum=sum+reminder
num=num//10
print("The sum of
all digit of given
number is :",sum)
ReVeRse A
Example1: NUMBER
num=int(input("Enter a number:"))
reverse=0
while(num>0):
digit=num%10
reverse=reverse*10+digit
num=num//10
print("The reverse of given
num is :",reverse)
ReVeRse A
Example1: STRING
def reverse_str(str):
str1=""
for i in str:
str1=i+str1 string concatenation
return str1

str=input("Enter string: ")


print("Orignal string: ",str)
print("After reversing
string: ",reverse_str(str))
ReVeRse A
Example2: STRING
def reverse_str(str):
str1=str[::-1] slice operator
return str1

str=input("Enter string: ")


temp=str
print("Orignal string:
",str)
print("After reversing
string: ",reverse_str(str))
PALindROm
num=int(input("Enter a (
NumbeR)
Example1:
number:"))
temp=num
reverse=0
while(num>0):
digit=num%10
reverse=reverse*10+digit
num=num//10
print("The reverse of given
num is :",reverse)

if temp==reverse:
print("The number is palindrom!")
else:
print("The number is not a
Example1:
PALindROm
def reverse_str(str):
str1=""
(STRinG)
for i in str:
str1=i+str1
return str1

str=input("Enter
string: ") temp=str
print("Orignal string:
",str)
print("After reversing string:
",reverse_str(str)) if temp==str:
print("The string is Palindrom!")
else:
Example1:
PALindROm
def reverse_str(str):
str1=str[::-1]
(STRinG)
return str1

str=input("Enter string: ")


temp=str
print("Orignal string:
",str)
print("After reversing string: ",reverse_str(str))
if temp==str:
print("The string is Palindrom!")
else:
print("The string is not
Palindrom!")
Example1:
FACTO
RiAL
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial
of",num,"is",factorial)
FACTORiAL usinG
Example2:
def factorial(num):
if num==1:
RecuRsiOn
return 1
else:
retu
rn
(num*fac
torial(n
um-1))

num=int(input("Enter a number: "))


print("Factorial is:
",factorial(num))
ReVeRse
FibOnACCi seRies
def reverseFibonacci(n):
a = [0] * n
assigning first and second elements
a[0] = 0
a[1] = 1
for i in range(2, n):
storing sum in the preceding location
a[i] = a[i - 2] + a[i - 1]
for i in range(n - 1, -1, -1):
printing array in reverse order
print(a[i],end=' ')
Driver function
n = 10
reverseFibonacci(n)

You might also like