python-3.x - 具有嵌套循环和用户输入的乘法表,在偶数后包括 # 符号
问题描述
尝试学习python ..我正在尝试构建一个乘法表,提示用户输入乘法表的大小,如果数字小于2或大于10无效,则使用验证循环。我还需要在表格中的任何偶数之后加上 # 号,而赔率只有一个空格。
我使用第一个代码来获得与上面类似的图像,但在偶数后面没有 # 符号。
我使用第二个来尝试创建一个可以涉及用户输入的表格,但我不知道如果数字<2 或>10 无效,我不知道如何包含该表格。而且我不知道如何在偶数后面加上#号
print("\t\t\t\tMultiplication table")`enter code here`
print(" ", end="")
for i in range(1,11):
print("%6d "%i, end="")
print()
print("-----"*17)
for i in range(1,11):
print("%2d|"%i, end="")
for j in range(1,11):
print("%8d"%(i*j), end="")
print()
朝着用户输入表工作
for row in range(0, 11):
for col in range(0, 11):
num = row * col
if num < 10:
empty = "\t"
else:
if num <= 100:
empty = "\t"
if col == 0:
if row == 0:
print("\t", end = '')
else:
print("\t", row, end='')
elif row == 0:
print("\t", col, end='')
else:
print(empty, num, end = '')
print()
解决方案
您的第一个代码非常接近。这是带有我的评论的修改代码:
def print_mult_table():
while True:
a = int(input('Enter rows count: ')) # allows user to enter string and convert to number of rows
if a < 2 or a > 10: # invalid number
print('Invalid rows count')
continue
b = int(input('Enter columns count: ')) # allows user to enter string and convert to number of columns
if b < 2 or b > 10: # invalid number
print('Invalid columns count')
continue
break
print()
print("\t\t\t\tMultiplication table ({} x {})".format(a, b)) # added table size here
print(" ", end="")
for i in range(1, a + 1): # using of user-defined value instead of hardcoded one
print("%7d "%i, end="")
print()
print("-----" * 19)
for i in range(1, a + 1): # using of user-defined value instead of hardcoded one
print("%2d| "%i, end="")
for j in range(1, b + 1): # using of user-defined value instead of hardcoded one
current_number = i * j
print("%7d" % (current_number), " " if current_number % 2 else "#", end="") # added # for even numbers
print()
print_mult_table()
输出:
Enter rows count: 10
Enter columns count: 10
Multiplication table (10 x 10)
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 #
推荐阅读
- r - 使用正则表达式更改列表中数据框的元素名称
- python-3.x - df.to_excel 仅捕获迭代 pandas 的最后一个请求
- amazon-web-services - AWS EC2 中的 JSF Websocket 在 localhost 但不在 EC2 (AWS) 上工作
- python-3.x - 当测试结束时并非所有任务都停止时,Asyncio 单元测试将失败
- python - Visual Code Studio 不允许我运行 discord.py 文件
- git - Git - 以下未跟踪的工作树文件将被合并覆盖:
- python - 如何执行二维神经网络?
- javascript - ReferenceError:未定义响应。我不明白
- android - Android:如何进行多模块匕首组件注入?
- r - 将两列组合在一起并将其原始列名保留为单独的列