0

I have written the following code but it is getting unnecessarily lengthy and messy. How can I keep it dry ? Any tips please ?

https://code.sololearn.com/cg3CAglAdDkm/?ref=app

20th May 2018, 4:47 AM
Masquerade
Masquerade - avatar
6 odpowiedzi
+ 5
I think you can modularize the stdout part as a function, then call it whenever you need to print stuff using that style, instead of rewriting the loop and its content each time you need it. def gamePrint(question): for character in question : sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) def startGame(): os.system('clear') gamePrint("Hello, what's your name?\n") playerName = input("> ") gamePrint("What role do you want to play?\n" + playerName +" ,You can play as Iron Man, Thor, Captain America\n")
20th May 2018, 5:15 AM
Hatsy Rei
Hatsy Rei - avatar
+ 13
Masquerade yes, you could print different dialogs at different speeds. Include another function argument called speed or something like that. (sleep maybe) i.e def gamePrint(question, speed): See: https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2286/?ref=app
20th May 2018, 5:36 AM
jay
jay - avatar
+ 7
Exactly as jay pointed out. E.g. def gamePrint(question, s): for character in question : sys.stdout.write(character) sys.stdout.flush() time.sleep(s)
20th May 2018, 5:48 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
oh wow ! Sweet. Thanks a lot jay and Hatsy. I wonder, why I couldn't think of this, even when I have studied and understood the chapters you referred. Before, I got the answer, I was so confused but now it's so clear.
20th May 2018, 5:53 AM
Masquerade
Masquerade - avatar
+ 1
Okay hatsy, that's working. thanks. But what, if I wanted to print different dialogues with different speeds ? would that be possible ?
20th May 2018, 5:31 AM
Masquerade
Masquerade - avatar