简体   繁体   中英

How can I make this construction simpler, like with classes or functions in python?

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")

I have 26 statements like these and I wonder if I can make it simpler with classes,
functions, lists or something I can't find a way??

You can create a class with Question and answer. Also add function in the class to check if the input is same as the Answer and return the result accordingly. You can use the regular expression to fetch the value of right answer from the Question text.

I would suggest using something like this:

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)

This now checks the input to ensure that it is valid - that it's numeric, and that it's between 1 and the number of parts.

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")

I have 26 statements like these and I wonder if I can make it simpler with classes,
functions, lists or something I can't find a way??

If you really want an extra function

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM