【问题标题】:Convertions with integer整数转换
【发布时间】:2022-07-15 21:44:52
【问题描述】:

我想输入一个整数,并且我希望 python 通过转换返回我的语句。我不知道如何解决这个问题。代码如下


subjectConversions = {
  "1": "Computer science",
  "2": "Geography",
  "3": "History",
  "4": "French",
  "5": "Drama",
  "6": "Music",
  "7": "Art",
  "8": "Design & Technology",
  "9": "Physical Education",
  "10": "Cooking",
  "11": "Business studies",
}

if year != "y":
  print("Sorry! Year 9 only!")
  quit()

elif year == "y":
  print("Welcome!")

print("Take a look at the list below for GCSE subjects. Once that is done, select four different options at each prompt.\nComputer Science [1], Geography [2], History [3], French [4], Drama [5], Music [6], Art [7], Desingn & Technology [8], Physical Education [9], Cooking [10], Business studies [11]\n")
Op1 = int(input("Option one: "))

print("You have selected" + (subjectConversions[Op1]) + ", is that correct? [y/n]")```

【问题讨论】:

  • 你的字典的键应该是像1这样的整数,而不是像"1"这样的字符串,因为你将用户输入Op1转换为int

标签: python


【解决方案1】:

使用整数作为键而不是str,即replace

subjectConversions = {
  "1": "Computer science",
  "2": "Geography",
  "3": "History",
  "4": "French",
  "5": "Drama",
  "6": "Music",
  "7": "Art",
  "8": "Design & Technology",
  "9": "Physical Education",
  "10": "Cooking",
  "11": "Business studies",
}

使用

subjectConversions = {
  1: "Computer science",
  2: "Geography",
  3: "History",
  4: "French",
  5: "Drama",
  6: "Music",
  7: "Art",
  8: "Design & Technology",
  9: "Physical Education",
  10: "Cooking",
  11: "Business studies",
}

【讨论】:

    【解决方案2】:

    您不能使用字符串作为键,然后尝试使用整数访问值 - 您需要选择一个并保持一致。将键设为整数或将输入保留为字符串。

    【讨论】:

      【解决方案3】:

      变化:

      Op1 = int(input("Option one: "))
      

      收件人:

      Op1 = input("Option one: ")
      

      它有效,这是因为你要求一个整数,而你的键是字符串,所以你应该要求一个字符串

      【讨论】:

      • 默认情况下输入已经是一个字符串 - 无需进行转换。
      • 相应地改变了我的答案
      猜你喜欢
      • 2014-11-01
      • 1970-01-01
      • 2011-10-05
      • 2022-01-06
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      相关资源
      最近更新 更多