PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 18, 2022

[FIXED] How to create a print function in python

 September 18, 2022     class, function, methods, printing, python     No comments   

Issue

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') it doesn't work;

An example 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 functionality of the normal print but with the additional of possibility of delay?


Solution

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) 


Answered By - user15256253
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing