【问题标题】:in python i cant execute functions with user inputs在 python 中,我无法使用用户输入执行函数
【发布时间】:2020-10-15 08:49:38
【问题描述】:

所以基本上我想在 cmd 中为 python aand 构建一个自动星形字母打印机 ValueZ() 是一个例子,还有 27 个,我想根据用户输入打印它们,但它只打印“Value + 用户想要的字母”,但我希望它像函数一样返回

def valueZ():
    for row in range(7):
        for col in range(4):
            if col == 0 or row % 3 == 0:
                print('.', end='')
            else:
                print(end=' ')
        print()


while True:
    def answerfind():
        answer = input("enter the letter which you want it to be printed with stars :")
        newAnswer = "value{deger}".format(deger=answer + "()")
        return (newAnswer)
    answerfind()

顺便说一句,如果我打错了,我很抱歉,英语是我的第二语言,我 16 岁,只是想学习这个 python 东西

编辑:字母看起来像这样

..... .
.
...... .
.
.
(看起来它已损坏,但它不像 cmd 中的那样)

【问题讨论】:

  • edit您的问题并显示您想要的输入和输出示例。

标签: python function for-loop if-statement format


【解决方案1】:

我想我明白你想要做什么。 在您的 answerfind() 函数中,您从用户那里获取输入并生成函数的名称。这里的问题是,当您返回 newAnswer 时:

def answerfind():
        answer = input("enter the letter which you want it to be printed with stars :")
        newAnswer = "value{deger}".format(deger=answer + "()")
        return (newAnswer)

您实际上是在返回变量的字符串值。 您实际上想要执行该字符串,因为它是函数的名称。 要完成此操作,请替换

return(newAnswer)

exec(newAnswer)

exec 命令执行字符串。也可以直接传递print("Hello World!")之类的语句来执行函数。

此外,您输入的输入可以是小写的,因此您还应该将其转换为大写,因为函数名称中包含大写字母,请使用

newAnswer = "value{deger}".format(deger=answer.upper() + "()") 这会将字母转换为大写,您将获得正确的函数名称。

【讨论】:

  • 非常感谢
  • 我做到了,这条消息出现了Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score.
猜你喜欢
  • 2017-12-14
  • 2015-10-19
  • 1970-01-01
  • 2020-03-09
  • 1970-01-01
  • 2017-08-22
  • 1970-01-01
  • 2014-06-06
  • 2019-11-05
相关资源
最近更新 更多