python-3.x - 华氏或摄氏 Python 程序不断重复
问题描述
我是编码新手,我正在尝试在摄氏度和华氏度之间建立一个简单的转换,但我一直遇到问题。如果我运行程序并键入并按回车键,则不会发生任何事情,否则会出现其他错误。我非常感谢您的帮助,并尽可能多地解释,以便我学习。
#!/usr/bin/python3
def fahrenheitToCelsius(fahrenheit):
celsius = (fahrenheit - 32.0) * (5.0/9.0)
return celsius
def celsiusToFahrenheit(celsius):
fahrenheit = (9.0/5.0) * celsius + 32.0
return fahrenheit
print('Welcome')
userInput = 0
while userInput != 3 :
userInput = input('''Main Menu
1:Fahrenheit to Celsius
2:Celsius to Fahrenheit
3:Exit program
Please enter 1, 2 or 3:''')
if userInput == 1:
fahren = input('\nPlease enter degrees Fahrenheit: ')
try:
fahren = float(fahren)
except:
print('Sorry, %s is not a valid number' % fahren)
exit(1)
cels = fahrenheitToCelsius(fahren)
print('%s degrees Fahrenheit equals %d degrees Celsius' % fahren % cels)
elif userInput == 2:
cels = input('\nPlease enter degrees Celsius: ')
try:
cels = float(cels)
except:
print('\nSorry, %s is not a valid number' % cels)
exit(1)
fahren = celsiusToFahrenheit(cels)
else:
print('Invalid entry')
解决方案
Python 不会自动将接收input()
到的值转换为它们各自的类型。(Python 2 做到了这一点,所以混乱可能源于那里)。因此,您收到的号码仍然是str
. "3"
永远不等于3
。最简单的方法是简单地将输入转换为一个数字,方法是将其包装在int
函数中:
userInput = int(input('...'))
你应该把它包起来try
——except
就像你输入温度一样——但一定要添加一个continue
语句。(它所做的只是转到循环的开头,有效地“重试”输入)。
try:
userInput = int(input('...'))
except:
print('Invalid number!')
continue
您忘记的一件小事是缩进语句,以 . 开头if userInput == 1
。这样,它们将在循环外执行。
推荐阅读
- c# - EF RemoveRange 在事务范围内不起作用
- multithreading - 如何测量一个非常大的程序的上下文切换开销?
- angular - 在 ngx-clipboard 中根据 cbOnSuccess 更改元素的文本
- java - 如何输入不同类型的数据并根据它们输出文本?
- java - SpringBootTest ava.lang.IllegalStateException:无法在无法打开 ServletContext 资源 [/application.yml] 处加载 ApplicationContext
- swift - 错误线程 1:EXC_BAD_ACCESS(代码=1,地址=0x30)
- visual-studio-code - VSCode 中的文本编辑器
- git - 为什么 git 合并操作没有显示在 git log 中?
- node.js - 快递js发送pdf文件
- svelte - 在 {@html} 中使用插槽