python - 我怎样才能使这个构造更简单,就像Python中的类或函数一样?

标签 python list function class if-statement

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 个这样的语句,我想知道是否可以通过类使其变得更简单,
函数、列表或其他我找不到方法的东西??

最佳答案

我建议使用这样的东西:

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 和零件数之间。

关于python - 我怎样才能使这个构造更简单,就像Python中的类或函数一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60259446/

相关文章:

python - 按条件将值广播到数据帧组

c - 如何在函数中使用链接列表

c++ - 这是做什么的? C++

php - 将返回的字符串传递给另一个字符串并在 if 语句中使用它

Python - 准确显示 MySQL 数据库中的数据

python - Flask 登录和注销

python - 如何在Python中查找列表行和列索引

list - 如何使用 bind (>>=) 实现一个函数

javascript - 从另一个脚本调用函数?

python - 如何根据 pandas 的第二列删除重复项?