python - 在 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 循环出了点问题,我希望这是有道理的,非常感谢所有帮助!
谢谢!!!
解决方案
在此代码中,您获取输入,然后开始循环。该input
功能是获取用户输入的内容,而您再也不会得到它。您的and
s 也有逻辑错误,它们应该是or
s。
# 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')
推荐阅读
- android - MaterialDatePicker 选择后返回不正确的日期
- reactjs - npm WARN deprecated tar@2.2.2: 此版本的 tar 不再受支持,并且不会收到安全更新
- angular - Angular RxJS 如何使时间延迟来自先前的管道
- javascript - $.each() 中带有 CSS 变量的样式
- sql - SQL,如何获取数据以显示前 30 天
- react-hooks - 在 typescript 中检查 URL 的有效性后如何更新图标的颜色与 useState 反应?
- vb.net - 协助“不是数组的成员”
- azure - 我是否可以创建 Azure 策略以将资源组中每个资源的日志转发到具有特定保留期的 Azure 监视器/日志分析
- python - 模块熊猫没有属性'DataFrame'
- python - 如何使用 importlib 动态加载 python 文件?