PythonNewbie
PythonNewbie

Reputation: 828

Extra new line on print Python

I have small fun function that prints rhombus with asterisks. It looks like this:

from time import sleep

while True:
    whitespaces_count = 0
    dots_count = 8
    for _ in range(0, 5):
        print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
        whitespaces_count += 2
        dots_count -= 2
        sleep(0.15)
    whitespaces_count = 6
    dots_count = 2
    for _ in range(0, 4):
        print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
        whitespaces_count -= 2
        dots_count += 2
        sleep(0.15)
    print("\n")

It works fine, but, after every print command, it prints additional blank line, so output looks like this:

********
***  ***
**    **
*      *

*      *
**    **
***  ***
********

But I want it looks like this:

********
***  ***
**    **
*      *
*      *
**    **
***  ***
********


What am I'm doing wrong?

Upvotes: 0

Views: 48

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155505

Your problem isn't print, it's that your first loop runs one extra time printing no dots, all whitespace. Change it to loop over range(4) instead of range(5) and that extra line goes away.


Side-note: You should really take advantage of the loop itself to do the work of determining how many asterisks and spaces to print; you're using a range to decide how many loops to run, but it could do double duty, allowing this (minimally fixed code):

whitespaces_count = 0
dots_count = 8
for _ in range(4):
    print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
    whitespaces_count += 2
    dots_count -= 2
    sleep(0.15)

to become:

for whitespaces_count in range(0, 8, 2):
    dots_count = 8 - whitespaces_count
    print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
    sleep(0.15)

or letting the loop do even more work, pushing more work to built-ins that outperform hand-written code (and having dots_count refer to the number of dots on each side):

for whitespaces_count, dots_count in zip(range(0, 8, 2), range(4, 0, -1)):
    print("*"*dots_count + " "*whitespaces_count + "*"*dots_count)
    sleep(0.15)

Upvotes: 3

Kent Shikama
Kent Shikama

Reputation: 4060

With for _ in range(0, 5):, you're looping once more than in your second loop. Try the following:

from time import sleep

while True:
    whitespaces_count = 0
    dots_count = 8
    for _ in range(0, 4):
        print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
        whitespaces_count += 2
        dots_count -= 2
        sleep(0.15)
    whitespaces_count = 6
    dots_count = 2
    for _ in range(0, 4):
        print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
        whitespaces_count -= 2
        dots_count += 2
        sleep(0.15)
    print("\n")

Upvotes: 0

Related Questions