gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:02:11 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com