specific amount of loop in python

Question:

I’m trying to create a code in python where user has to enter how many inputs there will be in a loop.I want to implement it with this code:

i = int(input(''))
  if int(i) in range (50 , 61):
    print('5')
  if int(i) in range (40 , 50):
    print('4')
  if int(i) in range (30 , 40):
    print('3')
  if int(i) in range (0 , 30):
    print('U')

the above only runs once and I want to create a loop where I first have to input how many times it should run i.e "3" times or "5" times. I tried to use while-loop but failed

Asked By: ruff

||

Answers:

When running code a certain number of times, for usually works better than while.

count = int(input("Enter number of loops: "))
for _ in range(count):
    i = int(input(''))
    if int(i) in range (50 , 61):
        print('5')
    if int(i) in range (40 , 50):
        print('4')
    if int(i) in range (30 , 40):
        print('3')
    if int(i) in range (0 , 30):
        print('U')

And while we’re at it, we can clean up that wall of ifs. You can pull your ranges into a list and loop through that instead.

my_ranges = [ (range(50, 61), '5'), (range(40, 50), '4'), (range(30,40), '3'),
    (range(0, 30), 'U')]
    
count = int(input("Enter number of loops: "))
for _ in range(count):
    i = int(input(''))
    for r, val in my_ranges:
        if i in r:
            print(val)
            break
Answered By: tdelaney
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.