【发布时间】:2015-06-05 21:21:08
【问题描述】:
我正在使用 Python 开发一个非常简单的温度转换器(仅供练习),并且正在努力处理一些 UX 组件。我希望进行检查以在进行无效输入时继续提示输入变量。我的完整代码如下:
o_temp = ''
def temp_input(o_temp):
o_temp = raw_input('Enter a temperature (round to nearest integer): ')
return o_temp
def temp_input_check(o_temp):
o_temp = list(o_temp)
for i in o_temp:
if i not in '1234567890':
print 'Invalid entry. Please enter only the numerical temperature measurement in integer format.'
temp_input(o_temp)
else:
break
def converter(o_temp):
unit = raw_input('Convert to (F)ahrenheit or (C)elsius? ')
unit = unit.upper()
if unit == 'F' or unit == 'f':
n_temp = (9.0/5.0) * int(o_temp) + 32
print '%d C = %d F' % (o_temp, n_temp)
quit()
elif unit == 'C' or unit == 'c':
n_temp = (5.0/9.0) * (int(o_temp) - 32)
print '%d F = %d C' % (o_temp, n_temp)
quit()
else: #check for valid entry
print 'Invalid entry. Please enter F for Fahrenheit or C for Celsius'
unit_input()
def temp_converter():
#title, call sub-functions
print ''
print 'Temperature Converter'
print ''
temp_input(o_temp)
temp_input_check(o_temp)
converter(o_temp)
temp_converter()
但是,当我在 o_temp 提示中输入无效条目(例如,字母或字母和数字的组合)时,代码似乎无法识别这是无效的并继续单元提示。我没有正确返回变量吗?这里有什么问题?我尝试删除最初的 o_temp 声明,但随后出现“NameError:未定义全局名称 'o_temp'”
编辑
我想出了这个解决方案,还有什么进一步的建议来完善代码吗?
def converter():
print 'Temperature Converter'
while 1:
temp = raw_input('Starting temperature? ')
try:
temp = float(temp)
except ValueError:
print 'Invalid entry. Please enter only the numerical temperature measurement.'
else:
break
while 1:
unit = raw_input('Convert to Fahrenheit or Celsius? ')
if unit.upper().startswith('F') == True:
print "%f C = %f F" % (temp, temp*9./5+32)
return False
elif unit.upper().startswith('C') == True:
print "%f F = %f C" % (temp, (temp-32)*5./9)
return False
else:
print 'Invalid entry. Please enter F for Fahrenheit or C for Celsius'
converter()
【问题讨论】:
-
您的实际问题是什么?当您运行此代码时会发生什么,这与您的预期有何不同?
-
对不起,问题没有写完,不小心提前提交了。完整的代码和问题现已提出!
-
另外,您收到“名称错误”的原因是因为您的 o_temp 从未在 temp_converter 中的任何位置分配。你传入的变量对你的函数没有价值!
标签: python return global-variables try-catch raw-input