1

I have following code, which should print an output of k numbers around n number, and instead the n number the code should replace by *:

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

numbers_around(8, 3)
numbers_around(10, 2)

The output should be:

5 6 7 * 9 10 11
8 9 * 11 12

But my output is all in one line:

5 6 7 * 9 10 11 8 9 * 11 12
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Pali V
  • 11
  • 1

3 Answers3

1

You are using the parameter end = " " in the print function, which replaces the default end used by python which is starting new line; if you want to start new line after each printing, just add print() at the end.

the full function should be

def numbers_around(n, k):
    for cislo in range(n-k, n+k+1):
        if cislo == n: 
            print("*", end=" ")
        else: 
            print(cislo, end=" ")
    print()
Omar Zaki
  • 191
  • 6
1

Using end=" " tells the print function to output a space at the end, instead of the line break that it would normally output.

Therefore the output of the second function call starts on the same line as the output of the first function call ends.

You need to output an additional line break at the end of the numbers_around function.

To do that, just add an empty print() after the for loop:

def numbers_around(n, k):
    for ...:
        # ...
    print()
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
1

The problem is that you're telling print() to put a space at the end instead of the newline character '\n' it normally uses. You could fix this by just adding another call to print() at the end, but actually, if you redesign the function a little bit, you can make it a lot simpler. By using the splat operator, you can print everything at once.

Option 1: Use a generator expression or list comprehension instead of a for-loop.

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

Option 2: Instead of replacing n, get the two ranges around n and put a '*' in the middle.

def numbers_around(n, k):
    r1 = range(n-k, n)
    r2 = range(n+1, n+k+1)
    print(*r1, '*', *r2)
wjandrea
  • 28,235
  • 9
  • 60
  • 81