python - 我有什么办法可以提高效率吗?

标签 python coding-efficiency

我想知道是否有办法让这段代码更高效?只是说我对 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.")

最佳答案

首先,您可以尝试使用字典来消除所有这些 if/else block :

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)

如果您开始看到自己一遍又一遍地重复相同(或非常相似)的台词,请停下来想想您想要完成的事情。

关于python - 我有什么办法可以提高效率吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212811/

相关文章:

java - 在 Java 中声明 double - 本地一次或从 ArrayList<Double> 重复声明?

python - 一种更有效的使用 if 条件的 pythonic 方式

performance - 提高我的 PowerShell 脚本的效率

检查矩阵中单元值的邻居

iphone - 将 ASIHTTPRequest 帖子设置为 SimpleHTTPServer Python 服务器?

java - Gson流关闭

Python - 用指数函数拟合数据

python - 即使是 .00 如何保持小数点后 2 位

python - python 中的 zip(),如何使用静态值

python - 以元组为键将字典转换为数据框