【问题标题】:How can I make this construction simpler, like with classes or functions in python?我怎样才能使这种构造更简单,例如使用 python 中的类或函数?
【发布时间】:2020-06-01 04:59:42
【问题描述】:
print(
    "1. Engine block \n"
    "2. Pistons \n"
    "3. Crankshaft \n"
    "4. Camshaft \n"
    "5. Cylinder head \n"
    "6. Connecting Rod \n"
)

part = int(input("Choose an engine part to show you details about it: "))

if part == 1:
    print("Engine block")
elif part == 2:
    print("Pistons")
elif part == 3:
    print("Crankshaft")

我有 26 条这样的语句,我想知道是否可以通过类使其更简单,
函数、列表或我找不到方法的东西??

【问题讨论】:

  • 您可以看到这 26 条语句之间的共同点并将其放在函数中
  • 我想到了,但是我想自己输出每个零件,例如活塞,曲轴和凸轮轴与发动机缸体相同,那不会撕掉它们的描述,不会显示 4 个部分的一个描述?
  • 您可以执行一个函数,在其中传递一个 dict 并像下面的答案一样打印信息

标签: python list function class if-statement


【解决方案1】:

您可以创建一个带有问题和答案的课程。还要在类中添加函数来检查输入是否与答案相同并相应地返回结果。您可以使用正则表达式从问题文本中获取正确答案的值。

【讨论】:

  • 这是要考虑的事情,我会尝试用类和函数来玩我的代码-
【解决方案2】:

我建议使用这样的东西:

def info_about(parts):
    info = list(parts.values())
    print("\n".join(f"{i+1}.\t\t{name}" for i, name in enumerate(parts)))

    print()
    while True:
        part = input("Choose an engine part to show you details about it: ")
        if not part.isnumeric():
            print("Please enter a valid number")
            continue

        part = int(part)
        if part > len(info) or part < 1:
            print("Please enter a valid number")
            continue
        break

    print(info[part-1])

parts = {
    "Engine block":         "Info about engine block",
    "Pistons":              "Info about pistons",
    "Crankshaft":           "Info about crankshaft",
    "Camshaft":             "Info about camshaft",
    "Cylinder head":        "Info about cylinder head",
    "Connecting Rod":       "Info about connecting rod",
}

info_about(parts)

现在检查输入以确保它是有效的 - 它是数字的,并且它在 1 和部分数之间。

【讨论】:

  • 投反对票的不是我,但如果我输入“测试”怎么办......你只会得到错误。
  • 好的,已修复。谢谢:)
  • 这太棒了,我想不出任何改进,写得很完美,很有帮助,我想问我如何检查输入但你读懂了我的想法:D
【解决方案3】:

如果你真的想要一个额外的功能

print(
    "1. Engine block\n"
    "2. Pistons\n"
    "3. Crankshaft\n"
    "4. Camshaft\n"
    "5. Cylinder head\n"
    "6. Connecting Rod\n"
)

def list_dict():
    return {1: "Engine block", 2: "Pistons", 3: "Crankshaft"}

def ans(part):
    return list_dict()[part]


part = int(input("Choose an engine part to show you details about it: "))
print(ans(part))

【讨论】:

  • 额外的功能总是一个好主意,我会玩我的代码并尝试把它挤进去,干得好
猜你喜欢
  • 2014-03-31
  • 2019-09-04
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
相关资源
最近更新 更多