byu
byu

Reputation: 11

Why is my program printing to only one line instead of a seperate line?

so i'm using this snippet of code:

def print_slow(str):
    for letter in str:
    print letter,
    time.sleep(.1)

from this link on SO: printing slowly (Simulate typing) and if fits my needs. However, my code so far is this:

import time
import random
import sys
def print_slow(str):
   for letter in str:
   print letter,
   time.sleep(.5)
print_slow("MEME QUEST!")
time.sleep(.5)
print_slow("BY XXX XXXXX")

But when I run this code, it prints both snippets of code on the same line. Is there any way to put them on seperate lines?

EDIT: Adding an extra print to the print_slow function worked, thank you.

Upvotes: 0

Views: 400

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121894

You are missing a newline; normally print outputs that, but not if you add a , comma at the end.

You could insert an extra blank print between calls to print_slow() to write one:

print_slow("MEME QUEST!")
print
time.sleep(.5)
print_slow("BY XXX XXXXX")
print

You could just add that extra print statement to the function:

def print_slow(str):
    for letter in str:
        print letter,
        time.sleep(.1)
    print

A blank print writes the missing newline.

Alternatively, add a \n newline character to the text you print:

print_slow("MEME QUEST!\n")
time.sleep(.5)
print_slow("BY XXX XXXXX\n")

but take into account the same .1 second delay applies to writing the newline too.

Upvotes: 2

gutelfuldead
gutelfuldead

Reputation: 602

The comma after your

print letter,

statement is suppressing it from printing a new line.

Try

import time

def print_slow(string):
        for letter in string:
            print letter,
            time.sleep(.1)
        print '\n'

print_slow("hello")
print_slow("world")

I'm sure there is a cleaner way to implement this but this should resolve your problem.

Upvotes: 0

ifma
ifma

Reputation: 3818

You could just simply add a newline character

print_slow("MEME QUEST!\n")

Upvotes: 0

Related Questions