python - python中的while循环,输入和字符串有问题

标签 python string input while-loop user-input

我正在学习 python 并练习我制作一个简单的基于文本的冒险游戏的技能。

在游戏中,我想问玩家是否准备好开始。我通过创建一个 begin() 函数来做到这一点:

def begin():

     print(raw_input("Are you ready to begin? > "))

     while raw_input() != "yes":
         if raw_input() == "yes":
            break
            print(start_adventure())
        else: 
            print("Are you ready to begin? > ")

print(begin())

在我的代码下面是函数 start_adventure()

def start_adventure():
     print("Test, Test, Test")

当我运行程序时,它会启动,然后我会询问我是否准备好开始。然后它只是无限循环,如果我完全关闭 Powershell 并重新启动 Powershell,我只能退出程序。我究竟做错了什么?一旦玩家输入"is",我怎样才能让循环停止?

最佳答案

你希望这会做什么?您的问题的解决方案是尝试了解代码的作用,而不是仅仅将东西放在一起。 (别担心;我们中至少有 80% 的人曾经处于那个阶段!)

顺便说一句,我强烈建议使用 Python 3 而不是 Python 2;他们制作了一个新版本的 Python,因为 Python 2 充满了非常奇怪、令人困惑的东西,比如导致安全漏洞的 input10/4 等于 2 .


你想要这个做什么?

  • 反复询问用户是否准备好开始,直到他们回答“yes”
  • 调用start_adventure()

好的。让我们将目前为止的内容放入一个函数中:

def begin():
    while something:
        raw_input("Are you ready to begin? > ")

    start_adventure()

这里有很多空白,但这是一个开始。目前,我们正在获取用户的输入并将其丢弃,因为我们没有将其存储在任何地方。让我们解决这个问题。

def begin():
    while something:
        answer = raw_input("Are you ready to begin? > ")

    start_adventure()

这开始形成。我们只想继续循环 while answer != "yes"...

def begin():
    while answer != "yes":
        answer = raw_input("Are you ready to begin? > ")

    start_adventure()

万岁!让我们看看这是否有效!

Traceback (most recent call last):
  File "example", line 2, in <module>
    while answer != "yes":
NameError: name 'answer' is not defined

嗯...我们还没有为 answer 设置值。为了使循环运行,它必须不等于 "yes"。让我们用 "no":

def begin():
    answer = "no"
    while answer != "yes":
        answer = raw_input("Are you ready to begin? > ")

    start_adventure()

这行得通!

关于python - python中的while循环,输入和字符串有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51788857/

相关文章:

python - 您是否应该在Python的非库代码中使用下划线_作为“访问修饰符指示符”?

python - 在 openerp 中隐藏特定用户组的产品中的编辑按钮?

C++ 子字符串/字符串操作

c++ - Array of arrays of string 正确声明

css - 将 html 输入大小/最大长度与 Bootstrap 的表单控件一起使用

python - 获取指向列表元素的指针

python - 发送 CAN J1939 消息

c - 如何将命令行中传递的选项的效果结合到字符串上?

python - 当它是日期时按字典中的值排序

javascript - 在输入时启动/停止 js 动漫时间轴的最佳方法是什么