Printing like a table in phyton | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Printing like a table in phyton

I have the following code: import sys import math def number(x): if x==0: return "Cero" return "Positivo" if x > 0 else "Negativo" def main(): try: list=["4","0","-12","0.0","0","-1"] #input("Please, enter only a list of number separated by a comma.If you enter another key the program will end.\n").split(",") list2=[] j=0 for i in range(len(list)): list2.append(list[i]) j+=1 list2.append(" ") list2.append(number(float(list[i]))) j+=1 a=1 print("INPUT"+" "+"OUTPUT") while a <len(list2): print(list2[a-1], list2[a]) a+=1 except ValueError: sys.exit("Invalid input. Program ends.") if __name__== "__main__" : main() I want to obtain a table like this INPUT OUTPUT 4 Positivo 0 Cero -12 Negativo 0.0 Cero 0 Cero -1 Negativo Can please someone help me?

28th Sep 2020, 4:11 PM
Rosana Rodríguez Milanés
Rosana Rodríguez Milanés - avatar
4 Answers
+ 3
Rosana Rodríguez Milanés , see my previous post to test how the output is working.
29th Sep 2020, 11:44 AM
Lothar
Lothar - avatar
+ 2
This is a short test. You can use it to see how it works. def number(num): if num == 0: return 'Cero' return "Positivo" if num > 0 else "Negativo" lst = ["4","0","-12","0.0","0","-1"] print(f"{'INPUT':6} {'OUTPUT'}") for i in lst: print(f"{i:>5} {number(float(i))}")
28th Sep 2020, 7:24 PM
Lothar
Lothar - avatar
0
You have to use String formatting in python . For ex : print("{10d}".format(value)) Will print the value of value ...upto 10 digits no matter the actual no of digits in the value . So u will have a nice formatted table . More on this here. : https://www.w3schools.com/python/ref_string_format.asp
28th Sep 2020, 5:46 PM
Akash Kumar S
Akash Kumar S - avatar
0
Hi, guys, I found a problem in the code, so I made some change and he output is better: import sys import math def number(x): if x==0: return "Cero" return "Positivo" if x > 0 else "Negativo" def main(): try: list=["4","0","-12","0.0","0","-1"] #input("Please, enter only a list of number separated by a comma.If you enter another key the program will end.\n").split(",") list2=[] j=0 for i in range(len(list)): list2.append(list[i]) j+=1 list2.append(number(float(list[i]))) j+=1 a=1 print("INPUT"+" "+"OUTPUT") while a <len(list2): print("{} {}".format(list2[a-1],list2[a]),end="\n") a+=2 except ValueError: sys.exit("Invalid input. Program ends.") if __name__== "__main__" : main() OUTPUT: INPUT OUTPUT 4 Positivo 0 Cero -12 Negativo 0.0 Cero 0 Cero -1 Negativo However, I want to line up the value much better. Any suggestion?
29th Sep 2020, 1:22 AM
Rosana Rodríguez Milanés
Rosana Rodríguez Milanés - avatar