0% found this document useful (0 votes)
3 views42 pages

02 - Problem Solving With Python

The document covers problem-solving techniques in Python, focusing on conditional and repetition structures. It explains various decision-making constructs such as one-way, two-way, and multi-way decisions using if, if-else, and if-elif-else statements, as well as loops like while and for. Key learning outcomes include developing programming strategies, using specific programming terms, and understanding the importance of indentation and loop control.
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)
3 views42 pages

02 - Problem Solving With Python

The document covers problem-solving techniques in Python, focusing on conditional and repetition structures. It explains various decision-making constructs such as one-way, two-way, and multi-way decisions using if, if-else, and if-elif-else statements, as well as loops like while and for. Key learning outcomes include developing programming strategies, using specific programming terms, and understanding the importance of indentation and loop control.
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/ 42

Programming In Python

CT088-0-M version 1 (November 2017)

Problem solving with Python


Topic & Structure of the lesson

• Conditional structures in Python


– One way decision
– Two way decision
– Multi way decision
– Nested decision
• Repetition structures in Python
– while loop
– for loop

CT088-0-M Programming In Python Problem Solving with Python


Learning outcomes

• At the end of this lecture you should be


able to:
– Develop a problem-based strategy for
creating and applying programmed solutions
– Create, edit, compile, run, debug and test
programs using an appropriate development
environment

CT088-0-M Programming In Python Problem Solving with Python


Key terms you must be able to
use
• If you have mastered this topic, you should
be able to use the following terms correctly
in your assignments and exams:
– if
– if-else
– if-elif-else
– while
– for

CT088-0-M Programming In Python Problem Solving with Python


Conditional Structure

• While programming to solve a problem,


there might be a situation where a set of
instructions (actions) is to be performed
only when a given criteria is met
• For example a message “Negative” is to
be displayed on the screen, if the value
received is negative.

CT088-0-M Programming In Python Problem Solving with Python ‹#›


Conditional Structure

• In another scenario, where the system has


to choose between two sets of instructions
(actions) based on a condition is true or
false.
• For example the system has to choose
between two messages “Pass” and “Fail”
based on mark of a student.
• Python facilitate this with if, if – else, if –
elif – else constructs
CT088-0-M Programming In Python Problem Solving with Python ‹#›
One Way Decision

if (condition):
action_1
action_2
.
.
action_n

Please note the “:” and the indent


CT088-0-M Programming In Python Problem Solving with Python ‹#›
Examples

if x < 0:
print(“Negative”)

if mark >= 50:


print(“Pass”)

CT088-0-M Programming In Python Problem Solving with Python ‹#›


Using the if-else Structure

• If structure is good but not good enough,


what if you want your program to "make a
choice" based on a condition:
– do one thing if the condition is true, do
something else if it's false.
• The if-else structure gives you that power.

CT088-0-M Programming In Python Problem Solving with Python


Two Way Decision
if (condition):
action_1
action_2
.
.
action_n
else:
action_1
action_2
.
.
action_n

Please note the “:” after else, and the indent


CT088-0-M Programming In Python Problem Solving with Python ‹#›
Examples

if x < 0: In an if-else
print(“Negative”) structure, you're
else: guaranteed that
exactly one of the
print(“Positive”)
code blocks will
execute.
if mark >= 50:
print(“Pass”)
else:
print(“Fail”)
CT088-0-M Programming In Python Problem Solving with Python ‹#›
Syntax of else

• You create an else clause immediately


following the if block with else, followed by
a colon, followed by a block of statements.
• The else statement must be in the same
block as its corresponding if.
• That is, the else and if must be indented
the same amount; otherwise, your
program will generate a nasty error.

CT088-0-M Programming In Python Problem Solving with Python


A note on Indentation

• Increase indent after an if statement or for (will see


later) statement
• Maintain indent to indicate the scope of the block
(which lines are affected by the if/for)
• Reduce indent to back to the level of the if statement or
for statement to indicate the end of the block
• Blank lines are ignored - they do not affect indentation
• Comments on a line by themselves are ignored w.r.t.
indentation

CT088-0-M Programming In Python Problem Solving with Python


Indentation is very important in
Python
• Blocks can be as many statements as you
like.
• Indenting to create blocks is not optional
but the only way to define a block.
• This is one of Python's more unique
features.
• By indenting your code, you'll pick up a
good programming habit that makes your
code more readable and easy to debug.
CT088-0-M Programming In Python Problem Solving with Python
Creating Conditions

• All if structures have a condition.


• A condition is just an expression that is either
true or false.
• In the example given in previous slides, the
condition used in the if structure is x <0.
– This condition evaluates to either true or false,
depending on the value of x.
– If the value of x is less than zero, then the condition is
true. Otherwise, the condition is false.

CT088-0-M Programming In Python Problem Solving with Python


Understanding Comparison
Operators
• Conditions are often created by comparing
values.
• Values are compared using comparison
operators.
• The == as shown in the example is the
equal-to comparison operator.
• Python allows you to compare any values
you like, regardless of their type.

CT088-0-M Programming In Python Problem Solving with Python


Comparison Operators

CT088-0-M Programming In Python Problem Solving with Python


Using the if-elif-else Structure

• If-else is still not good enough, to choose


from among several possibilities is the job
of the if-elif-else structure.
• This is the most powerful and flexible of all
the conditional structures.
• It can be used in multiple ways, but it is
particularly good if you have one variable
that you want to compare to a bunch of
different values.
CT088-0-M Programming In Python Problem Solving with Python
Multi-way
Decision
yes
x<2 print 'Small'
if x < 2 : no
print 'Small'
yes
elif x < 10 : x<10 print 'Medium'
print 'Medium'
no
else :
print 'LARGE'
print 'LARGE'
print 'All done'

print 'All Done'


CT088-0-M Programming In Python Problem Solving with Python
Multi-way X=0

yes
x<2 print 'Small'

x=0 no

if x < 2 : yes
print 'Small' x<10 print 'Medium'
elif x < 10 : no
print 'Medium'
else : print 'LARGE'
print 'LARGE'
print 'All done'
print 'All Done'
CT088-0-M Programming In Python Problem Solving with Python
Multi-way X=5

yes
x<2 print 'Small'

x=5 no

if x < 2 : yes
print 'Small' x<10 print 'Medium'
elif x < 10 : no
print 'Medium'
else : print 'LARGE'
print 'LARGE'
print 'All done'
print 'All Done'
CT088-0-M Programming In Python Problem Solving with Python
Multi-way X = 20

yes
x<2 print 'Small'

x = 20 no

if x < 2 : yes
print 'Small' x<10 print 'Medium'
elif x < 10 : no
print 'Medium'
else : print 'LARGE'
print 'LARGE'
print 'All done'
print 'All Done'
CT088-0-M Programming In Python Problem Solving with Python
Examining the if-elif-else
Structure
• An if-elif-else structure can contain a whole list of
conditions for a program to evaluate.
• In the example given, the lines containing the different
conditions are
– if x <2:
– elif x <10:
• Notice that you write the first condition using an if clause,
but then list the remaining conditions using elif (short for
"else if") clauses. elif clauses are constructed just like if
clauses. And you can have as many elif clauses as you
like.

CT088-0-M Programming In Python Problem Solving with Python


Repetition Structure in Python

• At times, it may be required that a


statement or a set of statements is to be
repeated for a number of times, say N.
• Python supports this with the following
– while loop
– for loop

CT088-0-M Programming In Python Problem Solving with Python ‹#›


while loop

while (condition):
action_1
action_2
.
.
.

CT088-0-M Programming In Python Problem Solving with Python ‹#›


Example

Program to print a series of numbers from 5 down to 1:

n=5 Output:
while n > 0 : 5
print(n) 4
n=n–1 3
2
1

Please note the variable n , it is called loop variable.


CT088-0-M Programming In Python Problem Solving with Python
Examining the while Structure
• The loop from the previous example is just two lines:
while n > 0 :
print(n)
n=n–1
• The format of the while loop looks resemblance to the if
structure.
– The only difference is that if is replaced by while.
– And the similarities are:
• If the condition is true, the block (sometimes call the loop body in a loop) is
executed.
• But in the while structure, the computer tests the condition and executes the
block over and over, until the condition is false. That's why it's called a loop.

CT088-0-M Programming In Python Problem Solving with Python


Initializing the Loop Variable

• While loops are often controlled by a loop variable, a


variable used in the condition and compared to some
other value or values.
• It's important to initialize your loop variable.
• Most of the time, loop variables are initialized right
before the loop itself.
n=5
while n > 0 :
print(n)
n=n–1
• It is good idea to initialize the sentry variables to some
type of empty value.
CT088-0-M Programming In Python Problem Solving with Python
Checking the Loop Variable

• Make sure that it is possible for the while


condition to evaluate to true at some point,
otherwise, the block will never run.
n = -2
while n > 0 :
print(n)
n=n–1

CT088-0-M Programming In Python Problem Solving with Python


Updating the Loop Variable

• Once the condition is established, loop variable


is initialized and making sure that under some
conditions the loop block will execute, this will
give you a working loop.
• Next, make sure the loop will end.
• If a loop that never stops, this is a called an
infinite loop.
• Infinite loop is one of the main cause of program
hang and freeze.

CT088-0-M Programming In Python Problem Solving with Python


Example
counter = 0
while counter <= 10
print(counter)

• What the programmer probably meant was for the loop to print the
numbers from 0 to 10.
• Unfortunately, what this program does is print 0, forever.
• The programmer forgot to change counter, the loop variable inside
the block.
• Remember, the values in the condition must change inside the loop
block.
• If they never change, the loop will not end, and an infinite loop is
created.

CT088-0-M Programming In Python Problem Solving with Python


Breaking Out of a Loop

• The break statement ends the current loop


and jumps to the statement immediately
following the loop
• It is like a loop test that can happen anywhere
in the body of the loop
> hello there
while True:
hello there
line = raw_input('> ')
> finished
if line == 'done' :
finished
break
> done
print line
Done!
print 'Done!'

CT088-0-M Programming In Python Problem Solving with Python


Finishing an Iteration with
continue
• The continue statement ends the
current iteration and jumps to the top of
the loop and starts the next iteration

while True:
> hello there
line = raw_input('> ')
hello there
if line[0] == '#' :
> # don't print this
continue
> print this!
if line == 'done'
print this!
: break
> done
print line
Done!
print 'Done!'

CT088-0-M Programming In Python Problem Solving with Python


for Loops

• A for loop repeats a block of statement (its


loop body) for each element of the
sequence, in order.
• A for end when it reaches the end of the
sequence, the loop ends.

CT088-0-M Programming In Python Problem Solving with Python


Example

word = input("Enter a word: ")


print("\nHere's each letter in your word:")
for letter in word:
print(letter)
input("\n\nPress the enter key to exit.")

CT088-0-M Programming In Python Problem Solving with Python


Understanding for Loops

• In previous example any string entered is


really a sequence.
• All sequences are made up of elements.
• For strings, each element is one character.
• Since a for loop goes through a sequence
one element at a time, this loop goes
through the letters in the string entered
one at a time.

CT088-0-M Programming In Python Problem Solving with Python


Creating a for Loop

• To create a for loop, you start with


– for,
– followed by a variable for each element,
– followed by in,
– followed by the sequence you want to loop
through,
– followed by a :, and
– finally, the loop body.
for variable in sequence :
loop body
CT088-0-M Programming In Python Problem Solving with Python
for loop companion – range()

• The Counter Program:-


print("Counting:“)
for i in range(10):
print(i)
print("\n\nCounting by fives:“)
for i in range(0, 50, 5):
print(i)
print("\n\nCounting backwards:“)
for i in range(10, 0, -1):
print(i)
input("\n\nPress the enter key to exit.\n")

CT088-0-M Programming In Python Problem Solving with Python


Counting Forwards

• The first loop in the program counts forwards:


for i in range(10):
print(i)
• This for loop loops through a sequence.
• The sequence the loop moves through is created
by the range() function.
• range() function creates a sequence of numbers.
• Give range() a positive integer and it will create a
sequence starting with 0, up to, but not including,
the number you gave it.
CT088-0-M Programming In Python Problem Solving with Python
Counting Forward Another Way

• Substitute the range() function with the


sequence of numbers into the code.
for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
print(i)
• The output from this program is exactly the
same as the output from previous
program.

CT088-0-M Programming In Python Problem Solving with Python


Counting by Fives

• The next loop counts by fives:


for i in range(0, 50, 5):
print(i)
• This is done with a call to range() that creates
a list of numbers that are multiples of 5.
• To create a sequence of numbers with
range(), you can give it the start point, the
end point, and the number by which to count.

CT088-0-M Programming In Python Problem Solving with Python


Counting Backwards

• The following loop in the program counts


backwards:
for i in range(10, 0, -1):
print(i)
• This done because the last number in the
range() call is -1. This tells the function to go
from the start point to the end point by adding -1
each time.
• This is the same as saying "subtract 1."

CT088-0-M Programming In Python Problem Solving with Python

You might also like