How could I modify a variable inside of a function? (Python)

Question:

I am trying to make a function that takes a variable, a string, and an output variable. It should look and see if the string is in the variable, and it works perfectly (I used different code where it would just print an output string if the target string is found), except for the fact that I can’t get the value of the output variable to change. Instead, the output variable is not changed.

Here is my code:

import random
import os
import sys
import time
from time import sleep
def IfIn(var, string, output):
    if string in var:
        output = True
        return output

out = False
string = "Banana"
IfIn(string, "na", out)
print(out)

Expected it to output "True", but instead it outputted "False"

Asked By: Fuery

||

Answers:

You do not have to input the variable into the function parameters in order to modify it, although I do not recommend doing this. Here is the answer to your problem:

def IfIn(var, string):
    global output
    if string in var:
        output = True
        return output

output = False
string = "Banana"
IfIn(string, "na")
print(output)

Although, I recommend doing this instead:

def IfIn(var, string):
    if string in var:
        output = True
        return output

output = False
string = "Banana"
output = IfIn(string, "na")
print(output)
Answered By: Novial
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.