【问题标题】:Why does it ask me to input a string even after guessing the right string为什么即使猜对了字符串,它也要求我输入一个字符串
【发布时间】:2019-04-26 12:28:15
【问题描述】:
secret_word = "giraffe"
guess = ""

while guess != secret_word:
    guess = input("Enter your guess: ")

print("Bravo, you've guessed it right!")

【问题讨论】:

  • 在 Python 3.4 和 3.7.1 中似乎都可以正常工作。你能提供你的代码和终端的图片吗?
  • @Deathraider26 您可以在每行代码前面使用 4 个空格将其格式化为代码。
  • 请编辑您的问题标题。
  • 我尝试在 Spyder 中运行相同的程序,它成功了。奇怪!

标签: python python-3.x loops while-loop


【解决方案1】:

您的原始代码在 python 上对我有用。您可以尝试去掉前导空格和尾随空格以使其更健壮。

secret_word = "giraffe"
guess = ""

while guess.strip() != secret_word:
    guess = input("Enter your guess: ")

print("Bravo, you've guessed it right!")

如果您使用的是 Python 2 解释器,由于语法更改,它将无法正常工作;因此,您可以将代码编辑为与 Python 2 兼容。或者您可能在命令行中调用了错误的终端,以确保它是 python 3,您通常可以执行 python3 my_program.py 来显式使用 python 3。

secret_word = "giraffe"
guess = ""

while guess != secret_word:
    guess = raw_input("Enter your guess: ")

print "Bravo, you've guessed it right!"

干杯!

【讨论】:

  • 我正在使用 Python 3
  • @Deathraider26 你试过python3 my_program.py.
  • 我尝试在 spyder 中运行相同的程序,并且成功了。奇怪!
猜你喜欢
  • 1970-01-01
  • 2012-02-01
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 2020-08-16
相关资源
最近更新 更多