我想知道是否有办法让这段代码更有效率?只是说我对python和编程整体都不熟悉。任何提示都会很棒。谢谢你的到来。
以下是我从中获取任务的地方:http://www.101computing.net/how-old-is-your-cat/
该计划只是将猫的年龄转换为人类年龄。
convertedAge = 0
stage = 0
question = input("Is you cat under 1 year old?.. Y/N")
if ((question.lower() == "y") or (question.lower() == "yes")):
ageOfCat = int(input("How old is your cat (in months)?")) #cat < 1 year old
if 1 <= ageOfCat <= 2:
convertedAge = "9 to 10 months"
elif ageOfCat == 3:
convertedAge = "2 to 3 years"
elif ageOfCat == 4:
convertedAge = "5 to 6 years"
elif ageOfCat == 5:
convertedAge = "8 to 9 years"
elif ageOfCat == 6:
convertedAge = "10 years"
elif 7 <= ageOfCat <= 8:
convertedAge = "13 years"
elif 8 <= ageOfCat <= 11:
convertedAge = "14 years"
print("In human years your cat is the equivalent of " + str(convertedAge) + " old.")
else:
ageOfCat = int(input("How old is your cat (in years)?")) #cat > 1 year old
if ageOfCat == 1:
convertedAge = 15
elif ageOfCat == 2:
convertedAge = 15 + 9
else:
convertedAge = 15 + 9 + ((ageOfCat-2) * 4)
print("In human years your cat is the equivalent of " + str(convertedAge) + " years old.")
答案 0 :(得分:4)
首先,您可以尝试使用字典来消除所有if / else块:
convertedAges = {
1: "9 to 10 months",
2: "9 to 10 months",
3: "2 to 3 years", # and so on
}
然后使用字典:
convertedAge = convertedAges[ageOfCat]
老实说,你应该专注于可读性,特别是如果你刚开始的话。就像你的第一个if
可能只是
if question.lower() in "yes": # "y" is in "yes", so is "yes" (a string is a substring of itself)
如果你开始看到自己一遍又一遍地重复相同(或非常相似)的行,请停下来思考你想要完成的事情。
答案 1 :(得分:3)
您可以使用list
代替if
结构:
if ((question.lower() == "y") or (question.lower() == "yes")):
ageOfCat = int(input("How old is your cat (in months)?")) #cat < 1 year old
ages = [None,
'9 to 10 months',
'9 to 10 months',
'2 to 3 years',
'5 to 6 years',
'8 to 9 years',
'10 years',
'13 years',
'13 years',
'14 years',
'14 years',
'14 years']
convertedAge = ages[ageOfCat]
然后您可以向print()
发送多个参数而不是连接(并且您不需要将字符串转换为字符串):
print("In human years your cat is the equivalent of", convertedAge, "old.")
您可以为年龄较大的猫添加convertedAge
:
else:
ageOfCat = int(input("How old is your cat (in years)?")) #cat > 1 year old
convertedAge = 15
if ageOfCat > 1:
convertedAge += 9
if ageOfCat > 2:
convertedAge += (ageOfCat-2) * 4
print("In human years your cat is the equivalent of", convertedAge, "years old.")