Search code examples
pythonpython-2.7syntax

Python invalid syntax on a string?


I am very new to coding so I hope my question makes sense/is formatted correctly.

Here is my code:

#this function takes a name and a town, and returns it as the following:
#"Hello. My name is [name]. I love the weather in [town name]." 

def introduction("name","town"):
    phrase1='Hello. My name is '
    phrase2='I love the weather in '
    return ("phrase1" + "name" + "phrase2" + "town") 

E.g. introduction("George","Washington") in the python shell would return as "Hello. My name is George. I love the weather in Washington."

My problem is that my code is not doing that. Instead I get the following error:

Invalid syntax: <string> on line 1". In Wing101 **,"town"): 

has a red swiggle under it. I'm not sure what I did wrong...I know "name" and "town" are strings and not variables, but I really have no idea how to fix it.

Any help/comments are appreciated.


Solution

  • You can't use string literals as function arguments, no. You can only use variable names. Remove all the double quotes:

    def introduction(name, town):
        phrase1='Hello. My name is '
        phrase2='. I love the weather in '
        return (phrase1 + name + phrase2 + town) 
    

    You pass in strings when calling the function:

    introduction("George", "Washington") 
    

    and these then get assigned to name and town respectively.