2

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"

2
  • 1
    Do out = IfIn(string, "na", out). You can also write the body of IfIn as simply return string in var, and remove the output parameter. Commented Oct 25, 2022 at 0:58
  • You'll probably also want IfIn() to return False if the string wasn't found. Commented Oct 25, 2022 at 0:58

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! someone else already gave an answer, but it's still appreciated :) (to be honest it was in the form of a comment instead of an answer, but still)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.