Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
# Set definiton
def rep_words(replace, sentence):
    # Split the words in definition
    words = sentence.split()
    
    # 
    for i in range(0, len(words)):
        # 
        if words[i] in replace:
            # 
            words[i] = replace[words[i]]
    
    # 
    rep_sentence = ' '.join(words)
    # 
    return rep_sentence

# 
rep_input = input().split()

# 
for i in range(0, len(rep_input), 2):
    # 
    first_word = rep_input[i]
    # 
    rep_words = rep_input[i + 1]
    # 
    replace[first_word] = rep_words

# 
sentence = input()
# 
rep_sentence = rep_words(replace, sentence)
# Print the output
print(rep_sentence)


What I have tried:

Here is my most recent error message.

Traceback (most recent call last):
  File "main.py", line 28, in <module>
    replace[first_word] = rep_words
NameError: name 'replace' is not defined
Posted
Updated 6-Aug-23 18:13pm

As the error says Replace is not defined. See this turorial for reference; Python String replace() Method[^]

Below is how it is supposed to be used
C++
x = txt.replace("bananas", "apples")
 
Share this answer
 
In Python, indentation is significant: every contiguous line that is indented to the same level is part of the same block of code.
So when you define a function, the entire block of code needs to be indented to at least the same level:
Python
def foo(bar):
   # in the function
   if (bar == "Hello world"):
      print(bar)
   else:
      print("Not bar")
# Not in the function
foo("Hello World")
In addition to that, there are scope rules: variables only exist while they are in scope - which means within the block of code that they are defined.
Python
def foo(bar):
   # bar exists here
   if (bar == "Hello world"):
      print(bar)
   else:
      print("Not bar")
# Not in the function
# bar is out of scope now
foo("Hello World")
print (bar) # Throws an error because bar doesn't exist.

So in your code, replace is a parameter to the rep_words function, and can't be accessed outside it:
Python
def rep_words(replace, sentence):
    # Split the words in definition
...
    return rep_sentence 

# 
rep_input = input().split()

# 
for i in range(0, len(rep_input), 2):
...
    replace[first_word] = rep_words # "replace" does not exist.
You need to decide what replace is, and where it can be accessed, and call your function with the required parameters!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900