python - 退回多件贵重元素,然后分别调用这些贵重元素

标签 python

我在允许函数调用另一个函数设置的变量时遇到问题。我相信我知道如何使用单个变量来完成此操作,但我的代码要求它使用多个变量来完成,这是我几个小时以来一直在努力解决的挑战。我读过很多关于其他人似乎已经做到这一点的方法,但我找不到成功实现它们的方法。

#gathers the user's requests
def ask():
    userw = int(input('How wide? '))
    userh = int(input('How tall? '))
    userc = input('What string to use? ')
    userc_len = int(len(userc))
    return (userw, userh, userc, userc_len)

#draws the rows of the box. First the top with the topbot function, then the body with body(), then the bottom with topbot again
def draw(w, h, c, c_len):
    def topbot(w_, c_):
        for x in range(w_):
            print (c_, end ='')
            print ('\n')
    def body(w_, h_, c_, c_len_):
        for x in range(h_-2):
            print (c_, end = '')
            for x in range(w_-2):
                print(' ' * c_len_, end = '')
            print (c_)

    topbot(w, c)
    body(w, h, c, c_len)
    topbot(w, c)

#begins draw    
draw(userw, userh, userc, userc_len)   

draw函数尝试以userw、userh、userc、userc_len的参数开始,但找不到它们时,问题就开始了:

NameError: name 'userw' is not defined

当我尝试运行它时返回。

  1. draw 函数中定义 topbotbody 并按照我的方式管理参数是否正确?
  2. 如何从 ask 返回四个变量,以便 draw 可以将它们用作参数?

最佳答案

ask() 是一个将返回 4 个值的函数。所以,

returnValues = ask()
draw = draw(*returnValues) 
or simply, draw = draw(*ask())

此外,end = ' ' 也不正确。相反,您可以只使用 print(c_,'')。 必要时包括验证。就像如果我在“多宽?”中输入“hi”会怎样。在这种情况下,程序应该告诉我这是错误的。

关于python - 退回多件贵重元素,然后分别调用这些贵重元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37894036/

相关文章:

python - 在 matplotlib 中拆分图例

python - __new__ 在分数模块中

python - ReportLab 变量 nextPageTemplate 的

python - 保存使用 BatchNorm 的 Tensorflow 模型

python - 减去存储在两个单独列表中的 datetime.time 对象

python - 按 dtype 和列名选择 Pandas 列

python - 如何在 python 中进行矩阵计算而不进行舍入?

jquery - Django + jQuery + Ajax

python - wxPython 处理 SIGTERM/SIGINT

python - 在 __init__ 方法中设置初始 Django 表单字段值