python - 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
解决方案
我已经为所需的更改添加了评论
一些事情:
- 缩进错误(可能是 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.
推荐阅读
- ssh - ssh 会话中的 sh 脚本不返回值
- node.js - 使用 Axios 从 React 向 mongodb 发送请求
- java - 从 Java 中的 tflite 模型推断
- reactjs - reactstrap 和 react-bootstrap 有什么区别?
- reactjs - 未找到反应下拉输入模块:错误
- ios - Collection View 中的 UIKit Dynamics 总是以混乱结束
- bash - Phrase similar filenames as a string with separated by coma and different filenames by whitespace
- c++ - 如何将派生类型的容器传递给需要基类型容器的函数
- java - IDEA - 导入maven项目后,看不到源代码
- php - 如何将输入值从 PHP 传递给 Python 文件?