Search code examples
pythonpython-3.xloopsnested-loops

Python nested loops with if statements: Replacing values inside a range


Question

Given a range from 0 to 30, output all the integers inside the range with the following requirements:

I. Replace all the numbers that aren't divisible by 3 with Asterisk symbol(*);

II. Replace all the numbers inside range(10, 15) and range(20, 25) with Underscores(_).

Sample Output

0 * * 3 * * 6 * * 9 _ _ _ _ _ _ * * 18 * _ _ _ _ _ _ * 27 * * 30

My Codes:

range1 = range(10, 16)
range2 = range(20, 26)
for i in range(0, 31):
    while i not in range1 or range2:
        if i % 3 == 0:
            print(i, end = " ")
            break
        elif i % 3 != 0:
            print('*', end = " ")
            break
    else:
        print('_', end = " ")

My Output:

0 * * 3 * * 6 * * 9 * * 12 * * 15 * * 18 * * 21 * * 24 * * 27 * * 30

I am struggling with my codes since I've tried many times my codes failed to replace the numbers inside both ranges, it always skips the range check and outputs *. Any helpful ideas are appreciated, I hope I can improve my logic mindset instead of just getting the answers.


Solution

  • You can't use i not in range1 or range2, I suggest to use set union for efficiency. Also the while loop is useless, a simple test is sufficient.

    NB. trying to keep an answer as close as possible to your original code here.

    ranges = set(range(10, 16)) | set(range(20, 26))
    
    for i in range(0, 31):
        if i not in ranges:
            if i % 3 == 0:
                print(i, end = " ")
            elif i % 3 != 0:
                print('*', end = " ")
        else:
            print('_', end = " ")
    

    output: 0 * * 3 * * 6 * * 9 _ _ _ _ _ _ * * 18 * _ _ _ _ _ _ * 27 * * 30

    ranges: {10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25}