Home > Back-end >  Python: How to limit print output to increments with user input control
Python: How to limit print output to increments with user input control

Time:10-23

Let's say that we have a long list of items and we would only like to print 10 at a time before asking the user whether to display more items. What would be the most efficient way to iterate through the list and print 10 items at a time? Would slicing be the answer here?

CodePudding user response:

Used a list of integers as example. Typing 'yes' continues to print, anything else, ends the cycle.

list_name = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

for index, element in enumerate(list_name):
  if(index % 10 == 0) and index is not 0:
     print("Keep Printing Elements?")
     answer = input()
     if(answer != "yes"):
        break
  print(element)

CodePudding user response:

def printNextTenItems(list, times):
    print(list[10*times: 10*times   10])

times = 0
keepGoing = True
while (keepGoing):
    printNextTenItems(list, times)
    times  = 1
    keepGoing = input("Wanna see more?")
  • Related