【问题标题】:How can i pull out input variables that is in def, to print function that in main?如何提取 def 中的输入变量,以打印 main 中的函数?
【发布时间】:2021-05-09 12:07:09
【问题描述】:

def inputs():
  key = input("What is your name?: ")
  value = input("What's your bid? ")
  choice = input("Are there any other bidders? Type 'yes' or 'no'.")

print("Welcome to the secret auction program.")
inputs()
print(key, value, choice)

我想在主屏幕中重复输入()。所以我做了一个名为“输入”的新函数。但是我的代码不起作用:(我怎样才能使它正确?

【问题讨论】:

    标签: python variables input


    【解决方案1】:

    您可以使用return

    def inputs():
        return [input("What is your name? "), 
                input("What's your bid? "), 
                input("Are there any other bidders? Type 'yes' or 'no'.")]
    
    print("Welcome to the secret auction program.")
    x = inputs()
    print(x[0])
    

    另一种方法是使用global关键字。

    def inputs():
        global key, value, choice
        key = input("What is your name?: ")
        value = input("What's your bid? ")
        choice = input("Are there any other bidders? Type 'yes' or 'no'.")
    
    print("Welcome to the secret auction program.")
    inputs()
    print(key, value, choice)
    

    【讨论】:

    • 哇,这是另一种解决方案。我明白你的代码谢​​谢!
    【解决方案2】:

    key、value 和choice 是函数中的局部变量,因此在外部不可用。执行此操作的正常方法是从函数中返回变量并在外部捕获它们。

    def inputs():
      key = input("What is your name?: ")
      value = input("What's your bid? ")
      choice = input("Are there any other bidders? Type 'yes' or 'no'.")
      return key, value, choice
    
    print("Welcome to the secret auction program.")
    key, value, choice = inputs()
    print(key, value, choice)
    

    【讨论】:

    • 非常感谢!我解决了我的问题并理解了问题所在! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    相关资源
    最近更新 更多