【问题标题】:Making a list and printing definitions制作列表并打印定义
【发布时间】:2021-09-22 17:10:18
【问题描述】:

我正在尝试为我的化学课列出一个术语列表,并能够打印出我所要求的定义。 I.E 我询问了帝国系统的定义,然后我得到了该术语的定义。我已经创建了所有变量并将它们设置为术语的定义,但是当我尝试打印某个定义时,它会打印我拥有的所有定义。


VolumeUnits = "gal, cup, table spoons, teaspoons, quart, ounces, pints"

MetricSystem = "Based on the meter, really just a stick, Based on powers of 10"

PreFixes = """kilo 
hecto 
deka 
base 
deci 
centi 
mili"""

Mass = "the amount of matter in an object, base unit is kilograms"

Weight = "the pull of gravity on a mass"

Volume = "lenght x width x height"

Random = "1L - dm^3.  1ml - cm^3"

Time = "base is seconds"

Temperature = "Celsius, kelvin"

SigFig = "the last number that can be measured with confidence"

Chemistry = "the study of matter and its properties and reactions"

Matter = "anything that takes up space and has mass"

input("What would you like to know?\n")


if "Imperial":
    print(Imperial)



if "VolumeUnits":
     print(VolumeUnits)



if "MetricSystem":
     print(MetricSystem)



if "PreFixes":
     print(PreFixes)



if "Mass":
     print(Mass)



if "Weight":
     print(Weight)



if "Volume":
     print(Volume)
     


if "Random":
     print(Random)



if "Time":
     print(Time)



if "Temperature":
     print(Temperature)



if "SigFig":
     print(SigFig)


if "Chemistry":
     print(Chemistry)



if "Matter":
     print(Matter)```

【问题讨论】:

  • bool("Matter") 始终为True。尝试使用value = input 然后if value == "Matter:"。为了更有效地使用 dict 而不是松散的变量,所以你不需要那么多 ifs
  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: python


【解决方案1】:

所以另一个答案当然是你应该做的。但是为了澄清代码中的错误,您没有将 input() 分配给任何变量,并且您的 if-blocks 始终为真,因为它们并没有真正检查任何内容。

也许你想做这样的事情?!

definition = input("What would you like to know?\n")

if definition == "Imperial":
    print(Imperial)

【讨论】:

    【解决方案2】:

    尝试使用这样的字典

    terms = {
    'mass' : "the amount of matter in an object, base unit is kilograms",
    'weight' : "the pull of gravity on a mass",
    'volume' : "lenght x width x height"
    }
    

    当您必须访问某些内容时,只需使用 ,

    terms[anyterm] #example terms['volume']
    

    用于输入使用

    term = input('What you want to know more about')
    print(terms[term]) # Notice no quotes to use a variable
    

    print(terms.get(term, 'Term not found')) # Second argument is to
    # ensure that if term is not in dictionary then this will be the default value
    

    【讨论】:

    • terms.get() 用于输入但不存在于字典中的值;)
    • @mkrieger1 这段代码只是为了理解。不用于实际使用,我也修复了它
    • 尽管如此,它至少在语法上应该是正确的。当初学者甚至无法区分时,向他们展示无效代码有什么帮助。所以他们会学错。
    猜你喜欢
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多