需要让range()值基于用户输入的任何内容作为开始和结束因素。它还需要行和列的标题。请使用简单的语法,我是编程新手!
# This program creates a multiplication table with nested loops and limits the
# factors based on user input values.
#
# References:
# https://www.youtube.com/watch?v=0rWHH5JfKdo
# https://www.youtube.com/watch?v=Dpkfh-hX4-M
# https://stackoverflow.com/questions/27312273/python-meaning-of-end-in-the-
# statement-print-t-end/27312325
def nested_loop(start, end):
for i in range(start, end + 1):
for j in range(start, end + 1):
print(i * j, end='\t')
print('')
def get_value(label):
print("Enter " + label + " value:")
value = int(input())
return value
def main():
start = get_value("starting")
end = get_value("ending")
nested_loop(start, end)
main()
您的代码已经完成了大部分工作,它在用户指定的时间段内打印了乘法表的二维矩阵,您只缺少可以像这样添加的标头部分
def nested_loop(start, end):
# printing the top header
print('', end='\t')
for i in range(start, end + 1):
print(i, end='\t')
print('')
for i in range(start, end + 1):
print(i, end='\t') # printing the running column alongside the matrix
for j in range(start, end + 1):
print(i * j, end='\t')
print('')
def get_value(label):
print("Enter " + label + " value:")
value = int(input())
return value
def main():
start = get_value("starting")
end = get_value("ending")
nested_loop(start, end)
main()
使用类似3, 10
程序输出:
3 4 5 6 7 8 9 10
3 9 12 15 18 21 24 27 30
4 12 16 20 24 28 32 36 40
5 15 20 25 30 35 40 45 50
6 18 24 30 36 42 48 54 60
7 21 28 35 42 49 56 63 70
8 24 32 40 48 56 64 72 80
9 27 36 45 54 63 72 81 90
10 30 40 50 60 70 80 90 100
同意接受的答案,但只需要显示python爱好者如何使事情复杂化……类似这样的东西:
def nasty_loop(start, end):
print('\t'+'\t'.join(str(x) for x in range(start,end+1)))
for y in range(start, end+1):
print("%d\t" % y + '\t'.join(str(x*y) for x in range(start,end+1)))