Home > Software engineering >  How to create a print function in python
How to create a print function in python

Time:11-08

I tried to program a new type of print function, i wanted that the text was printed out in procedural way, so i wrote this:

def print(text):
    for t in text:
        sys.stdout.write(t)
        sys.stdout.flush()
        time.sleep(0.1) 
print('Monkey')
#program stamp  Monkey  letter by letter with delay of 0.1 sec

but if instead of 'Monkey' i put inside ('text', object.param, 'text') he rightly don't work; an exemple is:

class Monkey:
     def __init__(self, name):
        self.name=str

Monkey.name = 'George'

def print(text):
    for t in text:
        sys.stdout.write(t)
        sys.stdout.flush()
        time.sleep(0.1)
print('Monkey', Monkey.name, 'is funny')

#TypeError: print() takes 1 positional argument but 2 were given

how i can program this new print for get the same potentiality of the normal print but with the additional of possibility of delay

Thank for attention and sorry for the bad english ( pls don't dv me for that )

CodePudding user response:

Change

def print(text)

to this:

def print(*texts)

It accepts many args more than one.

And do this:

def print(*texts):
    for text in texts:
        for t in text:
           sys.stdout.write(t)
           sys.stdout.flush()
           time.sleep(0.1) 

EDIT

If you want to print out int as well, you can convert int to str:

def print(*texts):
    for text in texts:
        text = str(text) # Notice!! I added this line
        for t in text:
           sys.stdout.write(t)
           sys.stdout.flush()
           time.sleep(0.1) 

CodePudding user response:

You can add a star sign before the argument text.

class Monkey:
     def __init__(self, name):
        self.name=str

Monkey.name = 'George'

def print(*text):
    for t in text:
        sys.stdout.write(t)
        sys.stdout.flush()
        time.sleep(0.1)
print('Monkey', Monkey.name, 'is funny')
  • Related