Home > Net >  How can I print this table vertical?
How can I print this table vertical?

Time:12-01

x = 0
y = 0
z = 0

sign = "*"

x = int(input("Enter a number : "))
y = int(input("Enter a number : "))
z = int(input("Enter a number : "))

print(f'{"x":2}{"y":3}{"z":4}')
print(f'{x*sign}{y*sign}{z*sign}')

I want this to print like this but how can I take print it vertically?

x  y  z 
*  *  *
*  *

CodePudding user response:

You can use itertools.zip_longest with a space as fillvalue, and a for loop:

from itertools import zip_longest

sign = "*"

x = int(input("Enter a number : "))
y = int(input("Enter a number : "))
z = int(input("Enter a number : "))

print(f'{"x":2}{"y":3}{"z":4}')
for a,b,c in zip_longest(x*sign, y*sign, z*sign, fillvalue=' '):
    print(f'{a:2}{b:3}{c:4}')

Example output:

x y  z   
* *  *   
* *  *   
*    *   
*    *   
*        

alternative

If you don't have the specific formatting with different spaces you can even get rid of the (explicit) loop:

x,y,z = 5,2,4
print('x y z')
print('\n'.join(map(' '.join, zip_longest(x*sign, y*sign, z*sign, fillvalue=' '))))

output:

x y z
* * *
* * *
*   *
*   *
*    

CodePudding user response:

You will have to print every rows separatelly and check x,y,z to print single sign or space " "

You can get max value form x, y, z and run for-loop with range(max_val) and compare this value with x, y, z to check if it has to display sign or space.

sign = "*"

#x = int(input("Enter a number : "))
#y = int(input("Enter a number : "))
#z = int(input("Enter a number : "))
x = 5
y = 2
z = 4

print(f'{"x":2}{"y":3}{"z":4}')

maxval = max([x, y, z])

for n in range(maxval):
    sign_x = sign if n < x else " "
    sign_y = sign if n < y else " "
    sign_z = sign if n < z else " "
    print(f'{sign_x:2}{sign_y:3}{sign_z:4}')
  • Related