该程序应该解决转换不同长度单位的问题。由于某种原因,该程序只响应第一个" if"声明并运行" meters_to_inches"和"米_to_centimeters"仅用于功能,即使用户输入它们有英寸或厘米。如果用户输入"米"然后是长度,它返回它应该的东西,即以英寸和厘米为单位的长度。但是如果用户想要从英寸或厘米转换,它仍然使用米功能的数学并且不采用elif语句。有人可以帮助我吗?
#Title
print "Length Conversion"
#Description
print "This application will calculate the conversion of different units of length. There will be different conversion factors as described in the application."
print '\n'
#Directions
print "Hello. This application will help you convert into different units of lenth."
print '\n'
#Question
print "These are the different units to convert to and from:"
list = ["-Meters", "-Inches", "-Centimeters"]
for unit in list:
print unit
print '\n'
#Question
units = raw_input("Which of these units do you have and would like to convert to one or both of the other two?")
print '\n'
amount = int(raw_input("How much of it do you have?"))
#Functions. One of these functions converts meters to inches, and the other converts meters to centimers. The original input gets muultiplied or divided by a certain number in order for it to be converted.
def meters_to_inches(amount):
number = amount / 0.0254
return number
def meters_to_centimeters(amount):
number = amount * 100
return number
#Functions. One of these functions converts inches to meters, and the other converts inches to centimers. The original input gets muultiplied or divided by a certain number in order for it to be converted.
def inches_to_meters(amount):
number = amount * 0.0254
return number
def inches_to_centimeters(amount):
number = amount * 2.54
return number
#Functions. One of these functions converts centimeters to meters, and the other converts centimeters to inches. The original input gets muultiplied or divided by a certain number in order for it to be converted.
def centimeters_to_meters(amount):
number = amount / 100
return number
def centimeters_to_inches(amount):
number = amount / 2.54
return number
if units == "Meters" or "meters":
print meters_to_inches(amount)
print "(inches)"
print'\n'
print meters_to_centimeters(amount)
print "(centimeters)"
elif units == "Inches" or "inches":
print inches_to_meters(amount)
print "(meters)"
print'\n'
print inches_to_centimeters(amount)
print "(centimeters)"
elif units == "Centimeters" or "centimeters":
print centimeters_to_inches(amount)
print "(inches)"
print '\n'
print centimeters_to_meters(amount)
print "(meters)"
else:
print "The unit you have given does not match a conversion this application provides"
答案 0 :(得分:0)
你的条件不对。
以下条件将始终在Python中生成True
:
if variable == 'value' or 'other-value'
我的猜测是你打算这样做:
if variable == 'value1' or variable == 'value2'`
因此,使用upper或lower字符串的方法来避免这些or
。
例如,
if unit.upper() == 'INCHES'
如果您执行以下代码:
if 2:
print 'yes!'
if 0:
print 'no!'
您将看到Python仅打印yes!
。这意味着Python中除0
之外的任何数字的布尔表达式都是True
。
现在,因为您知道or
用于分隔两个布尔表达式,然后使用此if-statement
:
if x == 3 or 2
您知道2
是True
,因为在使用True
执行代码行时,其中一个布尔表达式为or
就足够了与该陈述有关。