将用户input()从main()函数传递到下一个函数中的字符串中

时间:2019-06-11 00:20:17

标签: python python-3.x

我很难将我在主函数中输入时提示的用户名传递到下一个函数中的字符串中。

我已经构建了一个函数程序,该函数程序将预先确定的名称传递给下一个函数字符串消息。但是,既然我已经尝试着提高它的速度并使用输入法,那么我将要在下一个函数中将其传递给字符串消息的时间真是太麻烦了。

def main():
    someMessage = input("Enter your name:")
    return someMessage

def buildGreeting (someMessage):
    message = "Greetings " +input(someMessage)+ " you have been hacked! This message will self destruct in ten seconds!"
    return message
def printMessage(aMessage):
    print(aMessage)

if __name__ == '__main__':
    main()

我要说“问候雷夫,您已被黑!这则消息将在十秒钟内自动销毁!”

这是我目前的结果。它提示输入我的名字,然后再无其他操作。这是我运行程序时读取的内容。

输入您的名字:莱夫

以退出代码0结束的过程

3 个答案:

答案 0 :(得分:5)

您将要这样做,因为main需要调用其他函数才能打印任何内容:

def buildGreeting():
    name = input("Enter your name:")
    message = "Greetings " + name + " you have been hacked! This message will self destruct in 10 seconds."
    return message

def printMessage(aMessage):
    print(aMessage)

def main():
    message = buildGreeting()
    printMessage(message)

if __name__ == '__main__':
    main()

运行时:

[dkennetz fun]$ python destruct.py
Enter your name:Dennis
Greetings Dennis you have been hacked! This message will self destruct in 10 seconds.

PS消息不会自毁。

答案 1 :(得分:4)

尝试一下:

def main():
    someMessage = input("Enter your name:")
    buildGreeting(someMessage)

def buildGreeting (someMessage):
    message = "Greetings " +someMessage +" you have been hacked! This message will self destruct in ten seconds!"
    printMessage(message)

def printMessage(aMessage):
    print(aMessage)

if __name__ == '__main__':
    main()

+input(someMessage)函数中的buildGreeting也是不必要的,因为您已经将该输入传递给了函数。

答案 2 :(得分:0)

另一种方法,

def main():
    someMessage = input("Enter your name:")
    return someMessage
    
someMessage = main()

def buildGreeting(someMessage):
    message = "Greetings " +someMessage+ " you have been hacked! This message will self destruct in ten seconds!"
    return message
    
aMessage = buildGreeting(someMessage)


def printMessage(aMessage):
    print(aMessage)
   

if __name__ == '__main__':
    printMessage(aMessage)