首页 > 解决方案 > 在 python 中创建基于“用户输入”的乘法表

问题描述

我正在尝试创建一个程序,要求用户输入两个输入,由此将创建一个乘法表。例如,用户输入 2 和 5。

输入小于 1,000 且大于 0 的起始整数:2

输入一个大于第一个数字且小于 1,000 的结束整数:5

我得到的东西看起来像这样:

     4     6     8    10

     6     9    12    15

     8    12    16    20

    10    15    20    25

但是数学是错误的,我想在顶部和左侧打印 2-5。

这是我到目前为止所拥有的:

    # In this program I will help you make a multiplication table
    print('In this program, I will help you make a multiplication table.')
    print('\n')

    # Ask user for a starting integer 
    start_value = int(input('Enter a starting integer of less than 1,000 and greater than 0: '))
    while start_value < 1 and start_value > 1000:
        start_value = int(input('Enter a starting integer of less than 1,000 and greater than 0: '))

    # Ask user for an ending integer
    end_value = int(input('Enter an ending integer greater than the first number and less than 1,000 : '))
    while end_value < 0 and end_value > 1000 and end_value > start_value:
        print('Invalid number')
        end_value = int(input('Enter an ending integer greater than the first number and less than 1,000 : '))

    for num1 in range(start_value, end_value+1):
        for num2 in range(start_value, end_value+1):
            table = (num1*num2)
            print(format(table, '6d'), end = '')
        print('\n')

我觉得 for 循环出了点问题,我希望这是有道理的,非常感谢所有帮助!

谢谢!!!

标签: pythonfor-loopwhile-loopnested-loopsmultiplication

解决方案


在此代码中,您获取输入,然后开始循环。该input功能是获取用户输入的内容,而您再也不会得到它。您的ands 也有逻辑错误,它们应该是ors。

# this is your code, exactly as above
end_value = int(input('Enter an ending integer greater than the first number and less than 1,000 : '))
while end_value < 0 and end_value > 1000 and end_value > start_value:
    print('Invalid number')

最简单的修复:

end_value = int(input('Enter an ending integer greater than the first number and less than 1,000 : '))
while end_value < 0 or end_value > 1000 or end_value > start_value:
    print('Invalid number')
    end_value = int(input('Enter an ending integer greater than the first number and less than 1,000 : '))

但这重复了第一行。因此,还有其他几个选择:

while True:
    end_value = int(input('Enter an ending integer greater than the first number and less than 1,000 : '))
    if end_value < 0 or end_value > 1000 or end_value > start_value:
        break
    print('Invalid number')
   

或者,如果你使用的是 python 3.8+,你可以使用:=这里的语法

while (end_value := int(input('Enter an ending integer greater than the first number and less than 1,000 : '))) < 0 or end_value > 1000 or end_value > start_value:
    print('Invalid number')
   

推荐阅读