I have implemented a working script. You should return the required value in the function and handling it on the caller side (when you call the function with the parameter).
The below script generates a random string and it returns "no" or "yes" based on if "a" is in the string (And prints your original "yay").
Code:
# Import modules for random string generation.
import random
import string
x = "no"
y = "no"
z = "no"
def generate_random_chars(number_of_chars):
"""
Generating a random string.
:param number_of_chars: Number of generated chars
:return: The string with random chars.
"""
return "".join(random.choice(string.ascii_letters) for _ in range(number_of_chars)).lower()
def xyz(arg):
# Global variables are not needed. These are not used inside the function.
# global x, y, z
# Define the return value.
return_value = "no"
random_chars = generate_random_chars(10)
print("Random characters: {}".format(random_chars))
if "a" in random_chars:
print("'a' is in generated chars")
if arg == "no":
print("yay")
return_value = "yes"
else:
print("not yay")
else:
print("'a' is NOT in generated chars")
print("not yay")
# The following line is not needed because the default value of return in "no"
# arg = "no"
return return_value
# Only test in a 10th for loop Not in infinite while loop
for _ in range(10):
print("X - Input: '{}' Output: '{}'".format(x, xyz(x)))
print("Y - Input: '{}' Output: '{}'".format(y, xyz(y)))
print("Z - Input: '{}' Output: '{}'".format(z, xyz(z)))
Output:
>>> python3 test.py
Random characters: nbqrezimym
'a' is NOT in generated chars
not yay
X - Input: 'no' Output: 'no'
Random characters: ldbymrkarr
'a' is in generated chars
yay
Y - Input: 'no' Output: 'yes'
Random characters: cwlglelcqt
'a' is NOT in generated chars
not yay
Z - Input: 'no' Output: 'no'
Random characters: irjanpwnvh
'a' is in generated chars
yay
X - Input: 'no' Output: 'yes'
Random characters: rlvszdglqu
'a' is NOT in generated chars
not yay
Y - Input: 'no' Output: 'no'
Random characters: dnmvsjciwg
'a' is NOT in generated chars
argis being reassigned, and sincex, y, zare strings i.e. immutable, it's irrelevant.arg = ...you simply bind the nameargin that scope to a new value. It will not affectarg's old value...void f(int &c)syntax in C++), which is not applicable to Python.