【问题标题】:Why is the print() function not printing what I ask it to in Windows?为什么 print() 函数没有打印我在 Windows 中要求的内容?
【发布时间】:2011-04-02 19:48:33
【问题描述】:

只是为了好玩,我正在用 Python 3.2 构建一个非常简单的基于文本的游戏。我的开发机器运行的是 Windows 7,我正在使用PyScripter IDE 开发这个游戏。

我遇到了print() 函数没有正确打印字符串的小问题。当您开始游戏时,程序会显示一个带有 3 个选项的小菜单:LoginRegisterExit。当我去注册时,程序会从我创建的名为Character 的自定义类中创建一个对象。该字符接受name 变量,然后使用名称变量打印出一条小消息。这是我必须这样做的代码:

user_choice = int(input("Please select a command: "))
if user_choice == 1:
    print("Sorry, this function isn't currently implemented.",
    "Please check back later.\n")
elif user_choice == 2:
    hero_name = input("Please choose a name for yourself, adventurer: ")
    hero = Character(hero_name)
    print("I see, so your name is", hero.name + "... Very well. We shall begin your journey immediately!\n")

代码应该可以正常工作,当我在 PyScripter 中运行程序时,我得到了一个不错的输出:

我明白了,所以你的名字是(我选择的名字)......很好。我们将立即开始您的旅程!

但是,当我从 cmd 提示符运行程序时,我得到:

...很好。我们将立即开始您的旅程!

我在这里做错了吗?或者这是 Windows 的错误?

【问题讨论】:

  • 我在这两种情况下都得到了确切的信息,即“未定义名称'字符'”。您可能需要输入一个完整的示例。您在此处粘贴的代码没有任何问题。
  • print函数会自动在末尾添加换行符(除非你指定参数end=''),所以这里不需要这些'\n'(当然,如果你不'不想在输出后有一个空行)。关于这个问题……我同意 Lennart 的评论。

标签: windows-7 python-3.x


【解决方案1】:

我认为您的 print() 声明中有错字:

# You have this:
print("I see, so your name is", hero.name + "... Very well. We shall begin your journey immediately!\n")

# Did you mean this?
print("I see, so your name is" + hero.name + "... Very well. We shall begin your journey immediately!\n")

【讨论】:

  • 哦,你好,无常先生!我修正了错字,但错误仍然存​​在。谢谢你指出我!
  • 该死,我讨厌那些赞成这个的人。我看到赞成票的数量主要取决于问题的简单程度,而不是答案的好坏。
  • @BlaXpirit:不幸的是,它对 1n73rn37_j3d1 的错误没有帮助,但这并没有错,因为字符串连接需要+,并且 OP 承认这一点。
【解决方案2】:

以下内容在 Python 3.2 和 Eric5 IDE 中有效:

heroname = "Joe Cool"
print("I see, so your name is", heroname + "... Very well. We shall begin your journey immediately!\n")

【讨论】:

    猜你喜欢
    • 2019-10-11
    • 1970-01-01
    • 2022-01-09
    • 2022-12-02
    • 2021-11-23
    • 2021-01-05
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多