I have the below script which works fine, I only want to make the The running sum is:
integer output to be colored.
I have defined the class style
which I am trying to use.
Code:
#!/usr/local/bin/python3.6
import os
os.system("")
# Group of Different functions for different styles
class style():
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
def running_sum(n):
running_sum = 0
for k in range(n):
running_sum += k
print(f"The running sum is: {running_sum}")
if __name__ == "__main__":
running_sum(int(input("Enter an integer: ")))
Script output:
Enter an integer: 15
The running sum is: 105
In the above script 105
is the output which I want to printed in red color.
I tried to use
print(style.RED + f"The running sum is: {running_sum}")
but this makes the entire output red.
You can add codes in different places in string
print(f'The running sum is: {style.RED}{ running_sum }{style.RESET}')
The same without f-string
print('The running sum is:', style.RED, running_sum, style.RESET)
The same with format()
print('The running sum is: {}{}{}'.format(style.RED, running_sum, style.RESET))
You can use different colors in the same string - ie. green text and red sum
print(f'{style.GREEN}The running sum is: {style.RED}{ running_sum }{style.RESET}')
If you don't use {style.RESET}
then text in all next print()
will be also red
print(f'The running sum is: {style.RED}{ running_sum }')
print('This text is still red')
print('And this text is also red')
You can use use it also in input()
Red text and normal value entered by user
input(f"{style.RED}Enter an integer:{style.RESET} ")
Red text and green value entered by user
input(f"{style.RED}Enter an integer:{style.GREEN} ")
But after that you may have to print style.RESET
(without '\n') to get again normal color in next strings.
input(f"{style.RED}Enter an integer:{style.GREEN} ")
print(style.RESET, end="")
You can also assign color to variable to display wrong value on red and good value on green
if n >= 0:
color = style.GREEN
else:
color = style.RED
print(f"Value: {color}{n}{style.RESET}")
#print("Value: {}{}{}".format(color, n, style.RESET))