186k views
2 votes
The len function consumes a list and returns its length as an integer. Use the len function to write your own function check_length that consumes a list and returns whether it is 3-5 items long. Call and print this function twice.

User Endemic
by
5.2k points

1 Answer

4 votes

Answer:

def check_length(mylist):

length = len(mylist)

if 3<=length<=5:

message = "The length of the list is "+str(length)+" items long"

else:

message = "The length of the list is not within range of 3 to 5"

return message

mylist = []

print("Press Y to continue input")

cont = 'Y'

while cont == 'Y':

b = input("Input: ")

mylist.append(b)

cont = input("More Input?Y: ")

print(check_length(mylist))

print(check_length(mylist))

Step-by-step explanation:

The program creates an empty list and prompts user for input until user presses a key other than Y

This line declares function check_list

def check_length(mylist):

This line calculates the length of the list passed to the function

length = len(mylist)

This line checks the length of the list if it is within the range of 3 to 5

if 3<=length<=5:

This line gets the length of the list if it is between 3 and 5 (inclusive)

message = "The length of the list is "+str(length)+" items long"

else:

If otherwise, this line returns that the length is not within range

message = "The length of the list is not within range of 3 to 5"

This line returns the appropriate message based on the conditional statement above

return message

The main statement starts here

This line defines an empty list

mylist = []

This line gives the user instruction on how to input

print("Press Y to continue input")

cont = 'Y'

While the user presses Y, the following while conditional statement is executed

while cont == 'Y':

b = input("Input: ")

mylist.append(b)

cont = input("More Input?Y: ")

The next two line calls the function twice

print(check_length(mylist))

print(check_length(mylist))

User Turanga
by
5.2k points