Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this for loop work and the function doesn't?

Can anyone explain to me why this code works:

data = "8 (including George Blake, aged 69, and Robert Reynolds, aged 12)"
chars = "()[]?+"
for ch in chars:
    if ch in data:
        data = data.replace(ch,"")
print(data)

But when i try to create a function to do the same with this code, the output i get is None:

def clean(data):
chars = "()[]?+"
for ch in chars:
    if ch in data:
        data = data.replace(ch," ")
bob = "8 (including George Blake, aged 69, and Robert Reynolds, aged 12)"
print(bob)
output = clean(bob)
print(output)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

when you pass data as a parameter to your function and declare data = data.replace(ch, ""), you are modifying the parameter, not the original data passed to the function.
You should try to return data at the end of your function and then assign its value to output, such as:

def clean(data):
chars = "()[]?+"
for ch in chars:
    if ch in data:
        data = data.replace(ch," ")
return data
bob = "8 (including George Blake, aged 69, and Robert Reynolds, aged 12)"
print(bob)
output = clean(bob)
print(output)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading