简体   繁体   中英

Variables inside function python

When I create a variable and get user input, the program stops until it gets an input from the user. So what I did is I define a function and call it on condition. Now the problem I'm facing is I cannot access the input provided by the user. It says the "VarName" is not defined. I can see it but inside the function.

code example:

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

How do I process the input value? Put it in a variable and use an if statement on a condition using that variable.

Updated question:

I'm having two functions. One gets user input on condition A and the second one gets input on condition B. So only one of them is needed to be shown in the program at a time. This works properly until other place where I want to get the value of the input.

When I try to do return x() and print(y()).. it is calling the function and it is asking for input two times where only one time is needed.

Please tell me how I get the input value without making the program to ask for an inpu.

You can return the variable from inside the function.

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

user_input = math()
print(user_input)

you should make the function return the output what it is supposed to do and you can assign that output to a variable and can use it further

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

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

Your function needs to return a value. Otherwise when you call it, it won't return anything. If you call your function inside the print statement, it will return the value to the print function to be printed.

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

Updated:

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

what you can do is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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