Difference between code and function?


#1

I am trying to understand why is this happening when i’m doing this code:

text = "hey hey hey"
word = "hey"
txt_w = text.split()
for i in txt_w:
  if i == word:
    i = "*" * len(i)
  print i,

Output is simple: *** *** ***

But when im doing the same code but in function:

def censor(text,word):
  txt_w = text.split()
  for i in txt_w:
    if i == word:
      i = "*" * len(i)
    print i,

censor("hey hey hey", "hey")

Output like this: *** *** ***the password is **** *** *** ***
Why is this happen?


#2

Something weird happend or i don’t know how this test works

del text 
del word
def censor(text, word):
  txt_w = text.split()
  for i in txt_w:
    if i == word:
      i = "*" * len(i)
      print word

Even when i deleted all my variables output is:

Traceback (most recent call last):
File “python”, line 1, in
NameError: name ‘text’ is not defined
spam

Where are the “spam” comes from?
It prints some variable that does not exist in the code and also why is the function execute my print function, when i don’t call my censor function?
Is this how functions in python works? Sorry if this questions are stupid, i’m generally writing in C++/C# and have not seen that kind of stuff


#3

The exercise calls the function with different strings to see if it works correctly

why are you using del?

Your first code was pretty good, but you need to return the censored string, you only print it


#4

I got this error message:
Your function fails on censor(“hey hey hey”,“hey”). It returns “(’’,)” when it should return " ".


#5

So my code is:

def censor(text,word):
  answer = ""
  txt_w = text.split()
  for i in txt_w:
    if i == word:
      i = "*" * len(i)
    answer += i + " "
  return answer

#print(censor("hey hey hey", "hey"))

Your function fails on censor(“hey hey hey”,“hey”). It returns “(’’,)” when it should return " ".


#6

i might a slight modification to your code:

def censor(text,word):
  answer = ""
  txt_w = text.split()
  for i in txt_w:
    if i == word:
      i = "*" * len(i)
    answer += i + "_"
  return answer

print(censor("hey hey hey", "hey"))

I replaced the spaces with underscores, which allows you to see you have a trailing space that shouldn’t be.


#7

Ok, thanks. answer[:-1] is worked well. I didn’t know that last space symbol is an issue


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.