繁体   English   中英

function python 内部的变量

[英]Variables inside function python

当我创建一个变量并获取用户输入时,程序会停止,直到它从用户那里得到输入。 所以我所做的是我定义了一个 function 并有条件地调用它。 现在我面临的问题是我无法访问用户提供的输入。 它说“VarName”没有定义。 我可以看到它,但在 function 内部。

代码示例:

def math():
    add = input("Enter value here : ")
math()
print(add)

如何处理输入值? 将它放在一个变量中,并在使用该变量的条件上使用 if 语句。

更新的问题:

我有两个功能。 一个在条件 A 上获得用户输入,第二个在条件 B 上获得输入。因此一次只需要在程序中显示其中一个。 这可以正常工作,直到我想要获取输入值的其他地方。

当我尝试返回 x() 和 print(y()).. 它正在调用 function 并且它要求输入两次,而只需要一次。

请告诉我如何在不让程序请求输入的情况下获得输入值。

您可以从 function 内部返回变量。

def math():
    add = input("Enter value here : ")
    return add

user_input = math()
print(user_input)

你应该让 function 返回 output 它应该做什么,你可以将 output 分配给一个变量并可以进一步使用它

def math():
    add = input("Enter value here : ")
    return add

add = math()
# now you can use add anywhere you want

您的 function 需要返回一个值。 否则当你调用它时,它不会返回任何东西。 如果你在 print 语句中调用你的 function,它会将值返回给要打印的 print function。

def math():
    add = input("Enter value here : ")
    return add
print(math())

更新:

def math(a, b, opr):
    if opr == "*":
        return a * b
    elif operation == "/":
        return a / b
    elif operation == "+":
        return a + b
    elif operation == "-":
        return a - b
    else:
        print("Invalid operation")
        exit(0)


first_num = float(input("What is your first number? "))
operation = input("what operation (*, /, +, -)? ")
second_num = float(input("What is your second number? "))

print(f"Result: {math(first_num, second_num, operation)}")

Output:

What is your first number? 3
What operation (*, /, +, -)? /
What is your second number? 4
Result: 0.75

你能做的是

add = None
def math():
    global add
    add = input("Enter value here : ")
math()
print(add)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM