我正在学习Python,需要一点帮助来将我的符号向左移动几个空格。我已经完成了作业,不再寻求家庭作业的帮助。我只想让它在我这边看起来更好。在我在下面的链接中添加的图片中,您可以看到"#“太靠右了。我想让它坐在偶数旁边。我尝试在print语句中增加空格,但这样做只是移动了整个表。我怎样才能把那个"#“放在我的偶数旁边?
这是我的代码。
#ask for user input on size of Multiplication Table.
size = int(input("What size Multiplication Table would you like? (2-10):"))
while (size <2) or (size >10):
print("Invalid entery! Enter a Number Between 2 and 10")
size = int(input("What size Multiplication Table would you like? (2-10):"))
print()
print()
#dispaly header
print(" --- Multiplication Table(",size,"x",size,") ---")
print(" ",end="")
size += 1
for h in range(1,11):
if h == 10:
print(" ",h, end=" ")
else:
print(" ",h, end=" ")
print()
for h in range(1,100):
print('-',end='')
print()
#display Multiplication Table
#outer loop
for a in range(1,size):
if a ==10:
print('',a,'|',end='')
else:
print('',a,' |',end='')
#inner loop
for b in range(1,size):
result = a * b
if result >=100:
print(' ',result, end=' ')
elif result >=10:
print(' ',result, end=' ')
else:
print(' ', result, end=' ')
# for putting '#' at the end of even numbers
if result %2==0:
print('#', end='')
elif result == 100:
print('', end='')
else:
print(' ', end='')
print()发布于 2021-01-30 04:55:55
我对你的内部循环做了最小的修改,以产生想要的效果:
for b in range(1,size):
result = a * b
# for putting '#' at the end of even numbers
if result %2==0:
end_str='#'
elif result == 100:
end_str=''
else:
end_str=' '
if result >=100:
print(' ',result, end=end_str+' ')
elif result >=10:
print(' ',result, end=end_str+' ')
else:
print(' ', result, end=end_str+' ')修改后的输出:
1 2 3 4 5 6 7 8 9 10
---------------------------------------------------------------------------------------------------
1 | 1 2# 3 4# 5 6# 7 8# 9 10#
2 | 2# 4# 6# 8# 10# 12# 14# 16# 18# 20#
3 | 3 6# 9 12# 15 18# 21 24# 27 30#
4 | 4# 8# 12# 16# 20# 24# 28# 32# 36# 40#
5 | 5 10# 15 20# 25 30# 35 40# 45 50#
6 | 6# 12# 18# 24# 30# 36# 42# 48# 54# 60#
7 | 7 14# 21 28# 35 42# 49 56# 63 70#
8 | 8# 16# 24# 32# 40# 48# 56# 64# 72# 80#
9 | 9 18# 27 36# 45 54# 63 72# 81 90#
10 | 10# 20# 30# 40# 50# 60# 70# 80# 90# 100# 发布于 2021-01-30 05:31:03
试试这个:
for b in range(1,size):
result = a * b
flag = " " if result % 2 else "#"
#put the number and the flag together
temp = f"{result}{flag}"
#and pad the number + flag to a constant length
print(f' {temp:6.6}', end="")请看我关于f-string格式如何工作的更清晰的分类的问题下的评论。
输出:
--- Multiplication Table( 4 x 4 ) ---
1 2 3 4 5 6 7 8 9 10
---------------------------------------------------------------------------------------------------
1 | 1 2# 3 4#
2 | 2# 4# 6# 8#
3 | 3 6# 9 12#
4 | 4# 8# 12# 16#请看我关于f-string格式如何工作的评论。找不到一个真正明确的引用,关于格式是如何指定的f"{<variable>:<formatting-to-apply>}",所以不能链接一个,但它也可以做像填充零和格式浮点这样的事情。
https://stackoverflow.com/questions/65961085
复制相似问题