我完全是新手。我已经使程序正常运行,但是代码看起来真的很糟糕,我想使用if语句执行某些操作,因此避免重复复制粘贴。我还不知道函数(可以用一个完成吗?),仅循环,if和表。
代码如下:
print("What do you want to do?\n1)Give me just service name\n2)generate a link with service name\n3)do something else")
czynnosc = input()
if czynnosc == "1":
print("which unit id?" )
unitid = input()
unitid = int(unitid)
service = ""
if unitid >= 100 and unitid < 10000:
service= "OneOne"
elif unitid >= 10000 and unitid < 30000:
service= "Awesome20k+"
elif unitid >= 30000 and unitid < 40000:
service= "Great30k+"
elif unitid>= 40000 and unitid < 50000:
service= "Asom40k+"
elif unitid>= 50000 and unitid < 60000:
service= "Amazin50k+"
elif unitid>= 70000:
service= "new"
else:
print("Please validate unit id.")
print(f"Service name is {service}")
我想使用相同的if语句从选项2和3的unitid生成服务名称,而无需复制并再次粘贴整个if语句...
这可能吗?怎么样?
谢谢!
答案 0 :(得分:0)
您可以并且希望在一个单独的函数中多次使用该代码。在这里,将您的if ... elif ... else
放入一个单独的函数(或可能更多):
def get_service_by_unitid(unitid):
service = ""
if unitid >= 100 and unitid < 10000:
service= "OneOne"
elif unitid >= 10000 and unitid < 30000:
service= "Awesome20k+"
elif unitid >= 30000 and unitid < 40000:
service= "Great30k+"
elif unitid>= 40000 and unitid < 50000:
service= "Asom40k+"
elif unitid>= 50000 and unitid < 60000:
service= "Amazin50k+"
elif unitid>= 70000:
service= "new"
else:
print("Please validate unit id.")
return service
print("What do you want to do?\n1)Give me just service name\n2)generate a link with service name\n3)do something else")
czynnosc = input()
if czynnosc == "1":
print("which unit id?" )
unitid = input()
unitid = int(unitid)
service = get_service_by_unitid(unitid)
print(f"Service name is {service}")
elif czynnosc == "2":
print("Which cost id?")
costid = input()
costid = int(costid)
cost = get_service_by_unitid(costid)
print(f"Cost name is {cost}")