首页 > 解决方案 > while True 和 if 语句打印相同的计算

问题描述

我正在研究一个实际上很容易创建的英尺到英寸转换器,就像我以前做过的那样。但是这一次,我需要使用一个while循环。基本上,如果英尺数等于 0,它应该打印“程序已成功完成”。如果英尺数大于或等于 1,代码将继续计算,直到用户输入 0 退出脚本。我的问题是,当我测试退出脚本时,它会打印:“0 英尺 = 0 英寸程序已成功完成。” 我只想让它打印终止消息,而不是 0 英尺 = 0 英寸。我无法弄清楚我做错了什么。

def feet_to_inches(feet):
return 12 * feet

feet = int(input('Enter the number of feet (or 0 to end): '))
inches = feet_to_inches(feet)
print(f'{feet} feet = {inches} inches')

while True:
    if feet == 0:
        print('The program has finished successfully.')
        break
    ...       
    if feet >= 1:
        feet = int(input('Enter the number of feet (or 0 to end): '))
        inches = feet_to_inches(feet)
        print(f'{feet} feet = {inches} inches')
        continue

标签: pythonif-statementwhile-looppython-3.8converters

解决方案


我已经为所需的更改添加了评论

一些事情:

  • 缩进错误(可能是 StackOverflow)
  • 由于您将需要用户输入来决定是否退出循环,因此您可以在循环中请求输入,然后决定要做什么
  • 最终不需要继续

建议代码:

def feet_to_inches(feet):
    return 12 * feet #indentation error

while True:
    feet = int(input('Enter the number of feet (or 0 to end): ')) #moving input inside the while loop
    inches = feet_to_inches(feet)
    if feet == 0:
        print('The program has finished successfully.')
        break     
    elif feet >= 1:
        # feet = int(input('Enter the number of feet (or 0 to end): '))#not required
        # inches = feet_to_inches(feet) #not required
        print(f'{feet} feet = {inches} inches')
        # continue #this is not required

输出:

Enter the number of feet (or 0 to end): 1
1 feet = 12 inches
Enter the number of feet (or 0 to end): 2
2 feet = 24 inches
Enter the number of feet (or 0 to end): 3
3 feet = 36 inches
Enter the number of feet (or 0 to end): 0
The program has finished successfully.

推荐阅读