首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python函数功能

Python函数功能
EN

Stack Overflow用户
提问于 2017-05-15 23:16:21
回答 2查看 50关注 0票数 0

我正在冒险进入Python的奇妙世界!准确地说,是Python3。更准确地说,Python3.6?总之,我正在学习Python中的函数,我决定用Python编写一个函数,就像我知道如何编写函数一样,它起了作用!然而,我从未见过Python函数是这样编写的,在文档、书籍或互联网上的随机示例中都是如此。

所以,让我们拿一些小的东西,比如得到一个“玩家的名字”。

在C++中,它应该是这样的:

代码语言:javascript
复制
string getPlayerName(string playerName) {
    output << "What is the name?";
    input >> playerName;

    return playerName;
}

当然,displayPlayerName或showPlayerName还有另一个函数(或不;),但是您必须初始化函数变量:

代码语言:javascript
复制
void displayPlayerName() {
    string playerNameFunction = "";
    string playerNamePlaceHolder = "";

    playerNameFunction = getPlayerName(playerNamePlaceHolder);

    output << "Hello, " << playerNameFunction << "!" << endl;
}

现在,在Python中,我从未见过这样的情况。在我看到的所有例子中,我都看到了变量更难编码的地方。

代码语言:javascript
复制
def _getAge(age):
    print("How old are you?")
    print(age)

_getAge(30)

但!如果我们使用C++示例,这在Python中是完全合法的和合乎逻辑的!

代码语言:javascript
复制
def _getPlayerName(playerName):
    playerName = input("What is the name?")

    return playerName

playerNameFunction = ""
playerNamePlaceHolder = ""

playerNameFunction = _getPlayerName(playerNamePlaceHolder)
print("Hello, " + playerNameFunction + "!")

现在,我知道这看上去可能很糟糕,而且我知道这一切的长期风吹草动很可能违背了Python的目的。但我很想知道,对于Python来说,我使用函数的方法是非常规的,还是我对它的理解不够深入,无法理解一种更流畅的代码编写方式。

有什么想法吗?

谢谢您抽时间见我!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-15 23:29:30

这种模式既不是好的C++也不是好的Python。playerName的论点毫无意义。

在C++中,您应该编写

代码语言:javascript
复制
string getPlayerName() {
    string playerName;

    output << "What is the name?";
    input >> playerName;

    return playerName;
}

并称其为

代码语言:javascript
复制
string playerName = getPlayerName();

而不是不必要地从调用方复制占位符值,然后重写它,或者

代码语言:javascript
复制
void getPlayerName(string& playerName) {
    output << "What is the name?";
    input >> playerName;
}

并称其为

代码语言:javascript
复制
string playerName;
getPlayerName(playerName);

若要将播放机名称直接读入引用传递的字符串,请执行以下操作。

在Python中,你应该写

代码语言:javascript
复制
def getplayername():
    return input("What is the name?")

Python中没有按引用传递的选项。

票数 1
EN

Stack Overflow用户

发布于 2017-05-15 23:28:15

我想您可以在Python中压缩它,同时松散地维护您要使用的结构:

代码语言:javascript
复制
def _getPlayerName():
    return input("What is the name?")

print("Hello, {0}!".format(_getPlayerName()))

如果你喜欢的话,这也可以是一条线:

代码语言:javascript
复制
print("Hello, {0}!".format(input("What's your name?")))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43990178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档