【问题标题】:Python invalid syntax on a string?字符串上的Python无效语法?
【发布时间】:2016-01-23 23:06:58
【问题描述】:

我对编码很陌生,所以我希望我的问题有意义/格式正确。

这是我的代码:

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

例如python shell 中的introduction("George","Washington") 将返回为"Hello. My name is George. I love the weather in Washington."

我的问题是我的代码没有这样做。相反,我收到以下错误:

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

下面有一个红色的摆动。我不确定我做错了什么......我知道“name”和“town”是字符串而不是变量,但我真的不知道如何解决它。

感谢任何帮助/cmets。

【问题讨论】:

标签: python python-2.7 syntax


【解决方案1】:

你不能使用字符串字面量作为函数参数,不。您只能使用变量名。去掉所有的双引号:

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

调用函数时传入字符串:

introduction("George", "Washington") 

然后将它们分别分配给nametown

【讨论】:

  • 啊,我要学的东西太多了!非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2020-01-12
  • 2022-01-26
  • 2022-11-20
  • 1970-01-01
相关资源
最近更新 更多