【问题标题】:Passing a value to end message of game将值传递给游戏的结束消息
【发布时间】:2015-10-03 14:53:37
【问题描述】:

我有这个挂人代码,但我想添加参数传递给它

import time

import random


#Procedure
def Username():
    name = raw_input("What is your name?")
    print "Hello, "+ name, "Time to play hangman!"
    print "\n"

def loading():
    #Makes the user wait for 1 second
    time.sleep(1)
    print "Start guessing..."
    time.sleep(0.5)
    return

def randwords():
    global words
    words = ["keyboard", "motherboard", "python", "powersupply"]
    words = random.choice(words)

#Main Program
Username()

loading()


randwords()

guesses =""

turns = 12


#while loop


while turns > 0:

    failed = 0

    for char in words:

        if char in guesses: 

            print char,

        else:

            print"_",

            failed += 1    

    if failed == 0:
        print "\nyou won Well Done"


        break
    print


    guess = raw_input("guess a character:")


    guesses += guess

    if guess not in words:


        turns -= 1


        print "wrong\n"


        print "you have", + turns, "more guesses"

        if turns == 0:

            print "you lose GAME OVER\n"


input()
Username()
waiting()

Random

我希望它采用名称值,用户在开始时输入,然后将该值传递到结束消息中。

例子

print "you have won (NAME) Well Done"

print "you lose (NAME) GAME OVER"

请帮助我,因为我每次尝试都可以解决问题,但我会收到错误消息。

【问题讨论】:

  • 您尝试了哪些操作以及收到了哪些错误消息?

标签: python parameters parameter-passing


【解决方案1】:

您应该将“名称”声明为全局变量。

name = '' # before def Username

在给这个变量赋值之前,请执行以下操作:

global name
name = raw_input("What is your name?")

然后您可以在脚本中的任何位置使用此变量来打印其值。

print name, "you lose GAME OVER\n"

P.S : 要写入全局变量,您必须在前面加上:

global <variable-name>

然而,你可以用正常的方式读取它的值

【讨论】:

    【解决方案2】:

    您可以简单地从函数 'Username()' 中返回名称。

    def Username():
        ...
        return name
    
    def main():
        ...
        name = Username()
        ...
    

    【讨论】:

    • 感谢这个工作并帮助了我很多,所以谢谢你的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多