Learn to Code via Tutorials on Repl.it!

← Back to all posts
Add-ons to your Python code to make it better!
h
Bookie0 (2797)

Hello hello hello wassup people,

I’m just going to show you some quick things to make your Python code cool!

1) Screen Clearing

Screen clearing is very useful; you use it to, well, clear the screen. I like it a lot because you can use it to erase everything so that it looks better, and so that not too much text crowds the screen!

For the screen clearing, you need to just:

os.system('clear')

You can copy this code and put it every time you need to.
However, i prefer to create a function, so that i dont need to keep putting that (even if its just a few letters...):

def sc():
     os.system(‘clear’)

As you can see I called the function sc(),which stands for screen clear, so each time I want to clear the screen, i just call that function. It makes it just a bit shorter.
(Thanks to @ArjunSS1 for helping me with the screen clear)

2) Typewriter effect

Now this typewriter effect is super cool, because it makes the text print one letter at the time. You can regulate it so that it prints the text fast or slow.
First the imports:

import sys, os, curses
from time import sleep

And this is the code:

st = 0.04
def sp(str):
  for letter in str:
    sys.stdout.write(letter)
    sys.stdout.flush()
    time.sleep(st)
  print()

I usually put it at 0.04because it prints it not too fast and not too slow. But you can change it. Just change the value after st

Each time you want to do this typewriter effect, just do:

sp(“Hello World”)

Output:

Hello World

3) While loops to go back to menu (very basic)

Personally, I’m not a pro in loops, but this is what I do sometimes. Imagine you want to do sort of menu option, like this:

print (“This is the menu”)
action1 = input(“Type hello for some greetings >  ”)
if action1 == “hello”:
    print(“Hola”)
    print(“Bonjour”)
    print(“Aloha”)

So when the user types hello, several greetings will appear. But what if the user types something else by accident? Then, you could add an else statement, and saying something like “invalid”, and then the user could return to the menu,
This is how you do that:

back_to_menu = True

while back_to_menu == True:
     print (“This is the menu”)
     action1 = input(“Type “hello” for some greetings >  ”)
     if action1 == “hello”:
          print (“Hola”)
          print (“Bonjour”)
          print (“Aloha”)
      else:
           print (“You wrote something else than “hello”! ”)
           back_to_menu = True

So when you put back_to_menu = True at the end of the else statement, the user will arrive back at the menu!

4) Colors

This is how to make colors in Python.

Pretty simple, just copy paste these colors (because typing them would be to long...)

# colors
black = "\033[0;30m"
red = "\033[0;31m"
green = "\033[0;32m"
yellow = "\033[0;33m"
blue = "\033[0;34m"
magenta = "\033[0;35m"
cyan = "\033[0;36m"
white = "\033[0;37m"
bright_black = "\033[0;90m"
bright_red = "\033[0;91m"
bright_green = "\033[0;92m"
bright_yellow = "\033[0;93m"
bright_blue = "\033[0;94m"
bright_magenta = "\033[0;95m"
bright_cyan = "\033[0;96m"
bright_white = "\033[0;97m"

So to use it, just put the color before the text:

print(bright_yellow + “text here”)

This also works with the slowPrintI mentioned earlier

So that’s about it i know this tutorial isn’t very good, but upvote if it helped you or if you like it.
Lastly, nothing is under copyright, so go on and copy paste!

Tips, suggestions, questions, comments to let me know stuff, etc. Feel free to contact me!
And remember, upvoting ⬆️ is caring! 😊 😃 🙏

Commentshotnewtop
ArjunSS1 (105)

Small things, good article but you could do these things

You can use os to clear the screen instead like os.system('clear') which clears the screen
2.
For the typewriter there is an inbuilt argument in your print statement so instead of running sys.stdout.flush() you can just print(char, end='', flush=True)

Intead of running whille_back_to_menu = True you can just run while back_to_menu which is true so it will loop alternatively you can run while 1: which is True and you add a break statement to the if action1 == 'hello' block.

NoelB33 (291)

Also you can print a certain string to clear the screen also. @ArjunSS1

Bookie0 (2797)

Hey, thanks for commenting! I’m gonna change the screen clear and out your name for credit @ArjunSS1
Also for the typewriter I just put a function so that it’s shorter
For the back to menu, I know it can always loop back, but sometimes the user wants to just go to another thing instead of looping back.

But anyways thanks for the comments and remember,
Upvoting is caring! 😊

TheJuiceTin (4)

This helped me a LOT

JosephSanthosh (77)

Ummm @Bookie0 how do i add the typewriter effect thing for inputs.
Such as how do I add it to this: "email=input("What is the email address:").strip()"
Where do I put 'sp1' in the input?

JosephSanthosh (77)

The screen clearer thing and the typewriter effect thing don't work with me. They say I have to define everything when I run it.

Bookie0 (2797)

hum, are you sure you imported the things before? also did you put it in a function? send a pic of ur code plz @JosephSanthosh

JosephSanthosh (77)

Is there anyway you can add emoji's in inside a code?

Bookie0 (2797)

uh yea, just either copy from the internet or get it from the computer (dont know if its possible on PC tho) @JosephSanthosh

Nettakrim (366)

ansi stuff

\033[39m ends any ANSI escape code

\033[38;2;<r>;<g>;<b>m
means you can do any rgb color

\033[4m
underlines text and
\033[24m
removes underline

you can do

import re
self.removeAnsi = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
print(self.removeAnsi.sub('', green+"hi"))

to remove ansi codes (for if you are doing len() with variables that have color etc)

you can make colors accessable from all functions like this

def func1():
  print(colors.black+"hi")

def func2():
  print(colors.red+"hi")

class colors():
  black = "\033[0;30m"
  red = "\033[0;31m"
  ...

func1()
func2()

https://stackoverflow.com/questions/4842424/list-of-ansi-color-escape-sequences
is a usefull link for ansi escape codes, but quite a few dont work with the console

alternate way of clearing screen

also personally i prefer doing
print("\033c"+text)
to clear the screen as it is less flicker than

system("clear")
print(text)

V this prints alot but doesnt flicker much (it also uses spacing1 but we arnt there yet)
https://MaxDonalds.mcutten.repl.run

end=x on print statements

print(text,end="")
wont create a new line

print(text,end="hello")
will print "cathello" or "doghello"

3 variations on spacing for menus

for printing menus these can be usefull

def spacing1(length,a,b):
  removeAnsi = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
  a=str(a)
  b=str(b)
  return a+(" "*(length-(len(removeAnsi.sub('',a))+len(removeAnsi.sub('',b))))+b)

def spacing2(length,a,b):
  a=str(a)
  b=str(b)
  return a+(" "*(length-(len(a)+len(b)))+b)

def spacing3(length,a,b,c):
  a=str(a)
  b=str(b)
  return a+(c*(length-(len(a)+len(b)))+b)

print(spacing1(10,red+"hi","blue+hello"))
print(spacing1(10,red+"cat","blue+dog"))
will output (in red for the first value and blue for the second)

hi   hello
cat    dog

as you can see they maintain a legnth of 10

print(spacing2(10,"hi","hello"))
is the same but it doesnt work with ansi for simplicity
but you can do
print(red+spacing2(10,"hi","hello"))
to print in one single color

hi   hello

print(spacing3(10,"hi,"hello"," ")
print(spacing3(10,"cat,"dog","_")
will print

hi   hello
cat____dog

on the type writer effect

personally i find it annoying, add an option to remove it on the main menu if you use it

classes (better global variables)

class hi():
  def __init__(self):
    #this is called when the class is initiated
    self.var="hello"

  def hello(self):
    print(self.var)
    self.hi("cat")

  def hi(self,text):
    print(self.var+" "+self.hi)

example=hi()
example.hello()

will output

hello
hello cat

multiple of the same class can exist at the same time like this

example1=hi()
example2=hi()

any variables that change based of input will be seperate to eachover, self.var in example1 can have a different value to self.var in example2

Warhawk947 (509)

In typewriter effect, you imported curses but didn't use it.
Good tutorial though!

Bookie0 (2797)

Oh, i just took it because in case.... i didn’t know
but thank you so much tho! @Warhawk947