tawheed
tawheed

Reputation: 5821

printing on the same line in python

I have a basic code that just simply loops over and print some numbers in python. My problem was that I needed a different way to print my output since I wanted them to be on the same line. (The standard python print statement just prints stuffs on a new line). After doing some research i discovered that I could do something like this

    import random
from sys import stdout
    i= 0
    while i < 100:
        j = 0
        while j < 4:
            k =0
            while k < 4:
                sys.stdout.write(random.randint(0, 9))
                k += 1
            sys.stdout.write(" ") 
            j += 1   
        i += 1
        print "\n" 

This works like charm when I run it using IDLE -- python's ide, my only problem is that whenever I try to run it from the terminal it complains about this

    CallingCard $ python numGenerator.py 
Traceback (most recent call last):
  File "numGenerator.py", line 13, in <module>
    sys.stdout.write(random.randint(0, 9))
NameError: name 'sys' is not defined
CallingCard $ 

Wondering what might be the problem since running it from IDLE, FYI I am using python 2.7.3

Upvotes: 0

Views: 3088

Answers (4)

RITIK XHHETRI
RITIK XHHETRI

Reputation: 1

if __name__ == '__main__':
    n = int(input())
    
    for i in range(n):
        i =i +1
        print(i, end="", sep = '')

#printing the number on a single line with no whitespacing.

Upvotes: 0

hqtay
hqtay

Reputation: 430

If you did intend to print a 100 lines of four 4-digit numbers per line, you could use

from sys import stdout
....
stdout.write(str(random.randint(0, 9)))

Although you could really still use print and make it neater with something like

import random
from sys import stdout
i= 0
while i < 100:
    for j in range(4):
        print '%04d' % random.randint(0,10000),
   i += 1
   print "\n" 

Upvotes: 0

tawheed
tawheed

Reputation: 5821

Found the solution. Deep thinking helps sometimes Below is the code

    i= 0
while i < 100:
    j = 0
    while j < 4:
        k =0
        while k < 4:
            sys.stdout.write("%s" % random.randint(0, 9))
            k += 1  
        sys.stdout.write(" ") 
        j += 1   
    i += 1
    print "\n"

Upvotes: 1

jdi
jdi

Reputation: 92559

You need to import the sys module instead of just the stdout object, because you refer to it from the sys name:

import sys

Otherwise you would have to modify you call like:

stdout.write("foo")

Or just use a print command with a comma to supress a newline.

print "foo",

Upvotes: 1

Related Questions