【问题标题】:Python - Require input from a print functionPython - 需要来自打印函数的输入
【发布时间】:2017-01-13 14:58:36
【问题描述】:

我正在测试一个打印功能,它看起来好像提示正在输入,定义为 type()

我想使用 type 函数存储原始输入:

from time import sleep
import sys
from random import uniform

def type(s):
    for c in s:
    sys.stdout.write('%s' % c)
    sys.stdout.flush()
    sleep(uniform(0, 0.3))

name = raw_input(type("What is your name? "))
type("Hello " + name +"\n")

这是代码的输出:

你叫什么名字?无

仍然允许用户输入,在“无”之后,输出将正确打印,没有“无”。有没有办法绕过这个?

在这个提示中,我想使用 type 函数打印所有内容。

【问题讨论】:

  • 问题是您将type() 传递给raw_inputtype 隐式返回 None,因为您没有给它明确的返回值。也许尝试将raw_input 放入type返回结果。顺便说一句,名称type 已经属于内置函数type,隐藏它是不好的做法。为您的函数选择一个不同的名称,而不是 type
  • Python 已经有一个函数type()。将您的重命名为 type_() 或其他名称

标签: python python-2.7


【解决方案1】:

raw_input 将您传递的 arg 转换为字符串并将其用作提示。您将 raw_input 传递给您的类型函数的返回值,并且该函数返回默认值 None,这就是打印“无”的原因。所以只需在调用raw_input 和调用raw_input 之前使用你的函数之前 不带arg。

顺便说一句,您应该使用type 作为变量或函数名,因为那是内置函数的名称。

from time import sleep
import sys
from random import uniform

def typer(s):
    for c in s:
        sys.stdout.write('%s' % c)
        sys.stdout.flush()
        sleep(uniform(0, 0.3))

typer("What is your name? ")
name = raw_input()
typer("Hello " + name + "\n")

【讨论】:

    【解决方案2】:
    type("What is your name? ")
    name = raw_input()
    type("Hello " + name +"\n")
    

    给你。 Python 中没有定义 return 语句的任何函数,默认返回 None - 它会显示在您的提示符中。

    【讨论】:

    • name = raw_input("What is your name? ") type("Hello " + name +"\n")
    • @ASR 将多行 Python 代码放入 cmets 是没有用的,因为缩进会丢失。
    • 老实说,我不知道我为什么要让这件事复杂化。谢谢你的帮助。出于某种原因,我认为输入将从新行开始。
    【解决方案3】:

    函数的默认返回类型是无。因此,发生的事情是您的类型函数在函数末尾返回 None ,然后 raw_input 将其放入 stdout 流中。只需让 type 函数返回一个空白字符串即可解决问题:

        return ''
    

    除了 type 之外,您可能还想使用不同的函数名称,因为 type 是内置的,有时很有用。

    【讨论】:

      猜你喜欢
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      相关资源
      最近更新 更多