Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite printed line in python 3.x on mac

I'm attempting to write a program that involves the use of a coin flip, heads or tails, but so that it will print 'heads' then be replaced by 'tails' and continue doing this until it decides on an answer.

At the moment, when I run the program, it prints the 'heads' or 'tails' on the next line every time. This happens on both Idle and Terminal.

I've tried using carriage return (\r), backspace (\b) and sys.stdout.write() and .flush() but neither are working, it just keeps printing on the next line.

Is there either another way of erasing what's been printed or is there other software I can use? Here is my code:

import time
import random

offset = random.randint(0,1)

for i in range (0, 20+offset):
    if i % 2 == 0:
        print("Heads")
    else:
        print("Tails")
    print("\r")
    time.sleep(0.1)
like image 898
revolve Avatar asked Dec 29 '25 15:12

revolve


1 Answers

print writes a \n character to the end, therefore you need to modify that if you want to keep on the same line.

import time
import random

offset = random.randint(0,1)

for i in range (0, 20+offset):
    if i % 2 == 0:
        print("Heads", end='')
    else:
        print("Tails", end='')
    print("\r", end='')
    time.sleep(0.1)

Edit: That only works for python 3, If you want to use that in python 2 then you need to write to sys.stdout

import time
import random
import sys  

offset = random.randint(0,1)

for i in xrange(0, 20+offset):
    if i % 2 == 0:
        sys.stdout.write("Heads")
    else:
        sys.stdout.write("Tails")
    time.sleep(0.1)
    sys.stdout.flush()  
    sys.stdout.write("\r")  

I'm aware this might not be the fastest implemention, but It works, I could type a faster approach later

like image 138
no_name Avatar answered Jan 01 '26 06:01

no_name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!