0% found this document useful (0 votes)
9 views53 pages

Condition Controlled Loops in Python

The document discusses condition controlled loops in Python. It explains how to use while loops to repeatedly execute a block of code as long as a condition is true. It provides examples of using while loops and accumulator variables to count iterations and calculate totals.

Uploaded by

esmaalanya007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views53 pages

Condition Controlled Loops in Python

The document discusses condition controlled loops in Python. It explains how to use while loops to repeatedly execute a block of code as long as a condition is true. It provides examples of using while loops and accumulator variables to count iterations and calculate totals.

Uploaded by

esmaalanya007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C O N D I T I O N CONTROLLED LOOPS

Dr. Zahra Golrizkhatami

CS101 Introduction to Python Programming -


Dr. Zahra Golrizkhatami
Generating a randominteger
 Sometimes you need your program to generate
information that isn’t available when you write
your program
 One way to solve this problem is to ask your
programming language to select a “random
number” – from there youcan use this number
to construct asomewhat random set of running
conditions
 You can generate a random number by using the
randint() function. This function takes two
parameters (a starting integer and an ending
integer) and returns one value (a random integer in
this range)
 In order to use the randint() function you must
first “import” the “random” module so that
Python can access the necessary code library.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge:Rock,
Paper, Scissors
 Write a program to ask
the user to select one of
three options - Rock(r),
Paper (p) or Scissors (s)
 Use the [Link]()
function to select an
option for thecomputer
 Determine thewinner
and print theresult.
¤ Rock beats Scissor
¤ Scissor beats Paper
¤ Paper beats Rock
CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami
Repetition Structures
 Programmers commonly find that they need to
write code that performs the same task over and
over again

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Example: Commission calculator
for a sales team
 Write aprogram that allows the user to calculate sales
commission earned by each member of asales team.
 Currently there are 3 people on the sales team,but
there maybe more in the future.
 Input
¤ Gross sales (float)
¤ Commission Rate (float)
 Process
¤ Commission = gross sales * commission rate
 Output
¤ Commission earned

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Repetition Structures
 In the previous example our code ended up being
one long sequence structure which contained alot
of duplicate code
 There are several disadvantages to this approach
¤ Your programs will tend to get very large
¤ Writing this kind of program can be extremely time
consuming
¤ If part of the duplicated code needs to be corrected
then the correction must be implemented many times

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Repetition Structures
 One solution to this kind of problem is to use a
repetition structure, which involves the following:
¤ Write the code for the operation one time
¤ Placethe code into aspecial structure thatcauses
Python to repeat it as many times as necessary
 We callthis a “repetition structure” or,more
commonly,a“loop”
 There are a variety of different repetition
structures that can be used in Python

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Condition Controlled Loops
 A condition controlled loop isprogramming
structure that causes a statement or set of
statements to repeat as long as a condition
evaluates toTrue

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Condition Controlled Loops

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


The “While”Loop
 In Python we can implement acondition controlled
loop by writing a“while” loop
 “while” loops work asfollows:
¤ Evaluate a Boolean expression.
¤ If it is False, skip the block of statements associated with
the while loop and condition the program as normal
¤ If it is True
 Execute a series of statements.
 At the end of the statement block re-evaluate the condition
 If it is True,repeat the block of statements
 If it is False,skip the block of statements associated with the
while loop and continue the program as normal

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


The “While”Loop

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge:
Commission Calculator
 Write aprogram that allows the user to calculate
sales commission earned by each member of a
sales team.
 Input
¤ Gross sales (float)
¤ Commission Rate (float)
 Process
¤ Commission = gross sales * commission rate
 Output
¤ Commission earned
CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami
Some notes of “while”loops
 We refer to the process of going through aloop as
an“iteration”
 If a loop cycles through 5 times then we say we
have“iterated” through it 5 times
 The “while” loop is considered a “pre-test” loop,
meaning that it only iterates upon the successful
evaluation of acondition
 This means that you alwaysneed to “set up” your
loop prior to Python being able to work with it
([Link] up acontrolvariable)
CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami
Warning!
 When working with a“while” loop there is nothing
to prevent you from writing a Boolean condition
that will never evaluateto False
 If this happens your loop will continue executing
forever, or until you send an “inter upt” to IDLE
using the CTRL-C keycombination
 We callthis an “infiniteloop” since it never stops
executing
 With the exception of a fewspecial cases you
want to try and avoid writing infinite loops
CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami
Trace the Output

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge:Guess the
Number
 Write the “guess the
number” game we’ve
seen to use a “while”
loop
 Allow the user to
continually guess a
number until they
eventually guessthe
correct number

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Solution

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge:Rock,
Paper, Scissors
 Write a program to ask
the user to select one of
three options - Rock(r),
Paper (p) or Scissors (s)
 Use the [Link]()
function to select an
option for thecomputer
 Determine thewinner
and print theresult.
¤ Rock beats Scissor
¤ Scissor beats Paper
¤ Paper beats Rock
CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami
Solution

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Accumulator Variables andAugmented
Assignment Operators

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


UsingAccumulatorVariables
 Set up your accumulator variables outside of your
loops. (Either top of program or before loop)
 Decide on a value you want to start your
accumulator values at. 0 or 0.0 is generally a good
starting point depending on whether you are
counting whole numbers or numbers with
fractional values.
 Use a self-referential assignment statement when
incrementing an accumulator variable. Example:
¤ counter = counter + 1

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Self-referential assignment statements

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Augmented AssignmentOperators
 The self-referential assignment statement that we
justused is extremely useful,and can be extended
to use any of the other math operations we have
covered in class so far.
¤a =a+1
¤ b = b *2

¤ c = c /3

¤ d = d -4

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Augmented AssignmentOperators
 However, Python (and most other programming
languages) contains a series of “shortcuts” that can
be used to cut down the amount of typing when
working with self-referential assignment
statements.
 We callthese shortcuts the “augmented
assignment operators”

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Augmented AssignmentOperators

Operator Usage Equal to


+= c += 5 c = c + 5
-= c -= 2 c = c – 2
*= c *= 3 c = c * 2
/= c /= 3 c = c / 3
%= c %= 3 c = c % 3

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge:Grocery
Checkout Calculator

 Write aprogram that asks the user to enter in a


series of price values
 Calculate arunning total of these values
 Calculate sales tax (7%) on the total billand display
the result to the user atthe end of the program

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Solution

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge: CoinFlips

 Write aprogram that simulates acoin flipping1


million times
 Count the # of heads and tailsthat result,and
display the result to the user after you have
finished running the simulation

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Solution

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Sentinels

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Sentinels
 Imaginethatyou wantto ask your users to enter inalarge
numberof itemsthatneedto becalculatedinacertain way.
 Youdon’tknow how manyvaluestheuser willbe entering.
 Given our current toolset wereallyonly havewaysto
handlethiskind of scenario:
¤ Ask the user atthe end of eachiteration ifthey
want to continue. This can be annoying and
makeyour program cumbersome ifyou will be
entering in hundreds or thousands of values.
¤ Ask the user ahead of time how many items
they will be [Link] canbe difficultsince
the user maynot know at the beginningof the
loop how many items they will be working
with.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Sentinels
 A sentinel value is apre-defined value thatthe user can type in to
indicate that they are finished entering data
 Example:
¤ >> Enter atest score (type -1 to end):100
¤ >> Enter atest score (type -1 to end):80
¤ >> Enter atest score (type -1 to end):-1
¤ >> Your test averageis:90%
 In the example above the value -1 is considered asentinel -- it
indicatesto the program thatthe user is finished entering data.
 Sentinels must be distinctive enough thatthey will not be mistaken
for regular data (in the previous example the value -1 was used –
there is no way that a“real”test value could be -1)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Repetition Flow Control

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


The “break”command
 The “break” command is aspecial Python command
that can be used to immediatelyend a loop.
 It will not, however,end your program – it simplyends
the current repetition structure and allows the
program to pick up from the line directly after the end
of your loop
 Note that when the break command runs it will
immediately terminate the current loop, which
prevents any commands afterthe break command
from running

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Trace the Output

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


The “continue”command
 The “continue” command is a special Python
command that can be used to immediatelygo to
the start of theloop.
 It will not continue going through the loop, but
goes back to the top and starts from there.
 It maybe alittle confusing, but ‘break’breaks the
[Link] ‘continue’immediatelycontinues it from
the start

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Prime NumberTester
 Write aprogram that
asks the user for an
integer
 Test to see if the
number is prime. A
prime number is any
number that is evenly
divisible by 1 and
itself.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Solution

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Simple DataValidation

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Simple DataValidation
 Often we need to ask the user to supply a value in
our programs
 But as you know you can't alwaystrust the user to
supply you with usabledata!
 One strategy you can use to ensure that you get
"good" datais to "validate" the user's [Link]
involves asking the user for a value – if it meets
our criteria we can continue. If not we will need
to ask the user to re-supply the value.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge
 Write aprogram that asks the user for apositiveinteger
 Do not accepta negative value (or zero) – ifthe user
supplies an invalidvalue you should re-prompt them
 Once you haveapositive integer you can print that
number of stars to the screen. For example:
Enter a positive integer: -5
Invalid, try again!
Enter a positive integer: 0
Invalid, try again!
Enter a positive integer: 5
*****

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Solution

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenges

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge:Temperature
Conversion

 Write aprogram that allows the user to convert a


temperature in Fahrenheit into Celsius using the
following formula
¤ Celsius = (Fahrenheit – 32) * 5/9
 After calculating the temperature ask the user if
they wish to continue. If so, repeat the conversion
with a new number. Otherwise end theprogram.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


DivisibilityTester
 Write aprogram that lets the user test to see ifa
series of numbers are evenly divisible by another
number (3). If they are,print out a status message
telling the user.
 Extension: Start off by asking the user to enter in
the number that should be used during the test
([Link] 5 ifyou want to test to see ifa range of
numbers is evenly divisible by 5)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge: Combo Lock
 Write a program that asks
the user forthree numbers
 Test those numbers against
three “secret” numbers that
represent thecombination to
avirtualpadlock
 If the user gets the numbers
right you should let them
know that they have gained
access to your program
 If not, allow them to continue
to enter combinations until
they guess correctly

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge:Arithmetic Quiz

 Write aprogram thatasks the


user to answer asimplemath
problem (5 + 6)
 Continually prompt the user for
the correct answer. If they
answer correctly, congratulate
them and end the program. If
they answer incorrectly you
should re-prompt them for the
answer asecondtime.
 Extension: Randomize the
numbers used in the math
problem
 Extension: Randomize the type
of problem the user is presented
with ([Link],subtraction)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge: MyGrades

 Write aprogram that


asks the user to enter
in a test score along
with the total points
possible for thetest
 Allow the user to enter
in as many scores as he
or she wishes
 When finished, calculate
the user’s average score
in the class
CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami
Programming Challenge:Math Quiz Part II

 Write aprogram thatasks


the user 5 simple math
problems
 Each problem should utilize
random numbers, but you can
standardize on a single
operation ([Link])
 Ask the user a question. If
they answer correctly, they
earn a point. If not, they do
not earn apoint.
 At the end of the program
present the user with their
score.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge:AI “Guess a
Number” game
 Write a program that
asks the user to supply a
secret number between1
and 1,000,000
 Then havethe computer
continually guess until
they find the secret
number
 Keep track of the number
of attempts
 Extension: How can this
be optimized?
CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami
Programming Challenge:Rock,
Paper, Scissors Tournament

 Write aprogram that lets the user playa gameof


Rock, Paper,Scissors against the computer
 End the gamewhen either the player or the
computer earns 3 points

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge:Adding Machine

 Write aprogram that


continually asks the
user for aninteger
 Add the supplied
integer to a total
variable
 When the user enters
a 0 value end the
program and display
the sum for theuser

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Programming Challenge:Weight Loss Log
 Write aprogram thatasks the
user to enter in a series of
weight measurements taken
over aperiod ofdays
 The user can enter as many or
as few weight values as they
would like. Entering the value
“0”should indicatethatthe user
has finished enteringdata.
 Calculatethe user’saverage
weight during thisperiod
 Also calculate their weight
change from the beginning of
their weightloss program to the
end of theprogram

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami

You might also like