Home > Blockchain >  Printing a star instead of a number
Printing a star instead of a number

Time:11-14

I need to write a function numbers_around(n, k) that prints the numbers smaller and larger than n in order. Instead of the number n, it should print an asterisk.

What I've done:

def numbers_around(n, k):
    for n in range((n-k),(n k 1)):
        print(n, end=' ')
    print()

numbers_around(15, 3)        
numbers_around(8, 6)        
numbers_around(27, 2)

My output:

12 13 14 15 16 17 18 
2 3 4 5 6 7 8 9 10 11 12 13 14 
25 26 27 28 29 

The output needed:

12 13 14 * 16 17 18 
2 3 4 5 6 7 * 9 10 11 12 13 14 
25 26 * 28 29 

CodePudding user response:

You are using the same name for two variables, this is bad practice. If you change one of the variable in the for loop and check if it is equal to the original number you can print out a "*" when needed like so:

def numbers_around(n, k):
    for i in range((n-k),(n k 1)):
        if i == n:
            print("*", end = " ")
        else:
            print(i, end=' ')
    print()

numbers_around(15, 3)        
numbers_around(8, 6)        
numbers_around(27, 2)
  • Related