简体   繁体   中英

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") 

Eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM