【问题标题】:BASIC GUESSING GAME [duplicate]基本猜谜游戏[重复]
【发布时间】:2018-02-11 22:25:02
【问题描述】:

大家好,我希望你能解释我做错了什么。我对 python 完全陌生,并且正在尝试基本代码,但它似乎并没有像我想象的那样工作。

该程序应该是一个简单的猜测变量中包含的正确数字的程序,但即使猜测正确,它也会说“不,那是不对的”。

magic_number = 10

input("I am thinking of a number between 1 and 10, can you guess it? ")

if input == magic_number:

    print("WOW! You must be psychic, that is spot on")
else:

    print("Nope, that's not it")

【问题讨论】:

  • 输入给出一个字符串。使用 int(input) 将字符串转换为 int 并比较
  • 如果您尝试隔离当前问题,这将是一个更好的问题。它不需要是关于“猜谜游戏”——它只需要是关于“为什么我来自input() 的号码与我的硬编码号码不匹配?”。

标签: python python-3.x


【解决方案1】:

首先你应该创建一个变量来存储答案,例如。

answer = input("I am thinking of a number between 1 and 10, can you guess it? ")

因此,您还必须将 if input == magic_number: 更改为 if answer == magic_number:

不过,主要问题是当您使用input 方法输入内容时,您的输入会自动转换为字符串。 所以你有两个选择:

  1. 将您的幻数转换为字符串 (magic_number = 10to magic_number = "10") 并使用我建议的修改运行代码
  2. 也将您的输入和 Int 修改为 if answer == magic_number:if int(answer) == magic_number:

这两种方法都很好用,不过要小心第二种方法,因为如果输入的内容不能转换为 int(例如“Hello”,代码将返回错误)

【讨论】:

    【解决方案2】:

    input 不是一个变量,它是一个函数!您应该输入 x=input("Enter a number"),如果 x == magic_number。 input 返回一个值,但您没有将用户的输入存储在任何地方。

    【讨论】:

      【解决方案3】:

      试试这个:

          magic_number = 10
      guess = int(input("I am thinking of a number between 1 and 10, can you guess it? "))
      if guess == magic_number:
          print("WOW! You must be psychic, that is spot on")
      else:
          print("Nope, that's not it")
      

      【讨论】:

      • 这行不通,因为猜测会猜测是一个字符串,而magic_number 是一个整数
      猜你喜欢
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 2020-11-22
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多