[英]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.