Question: The example code below shows two types of loops that can be coded using a while loop. The first is a sentinel loop that will

The example code below shows two types of loops that can be coded using a while loop.

The first is a sentinel loop that will repeat until the user enters the sentinel value. The

second loop is an input validation loop that will repeat until the user enters a value that

falls between a minimum and maximum value

Code

#Constants

MIN = 1

MAX = 100

SENTINEL = 0

def main():

count = 0 #counter variable

total = 0 #accumulator variable

int_value = get_integer() #priming read

while int_value != SENTINEL:

count += 1

total += int_value

int_value = get_integer() #loop read

print('Total number of values eneter is', count)

print('The sum of the values entered is', total)

print('The avrage value is', total/count)

def get_integer():

num_input = int(input('Enter a value between 1 and 100, 0 to

stop: '))

good_data = MIN <= num_input <= MAX or num_input ==

SENTINEL

while not good_data:

print('Value out of range')

num_input = int(input('Enter a value between 1 and 100,

0 to stop: ': '))

good_data = MIN <= num_input <= MAX or num_input ==

SENTINEL

return num_input

main()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Psychology Questions!