应该定义的未定义变量,但我过于复杂

时间:2014-02-25 00:26:06

标签: python variables undefined

我是Python的新手,也是一般的编程,所以请尽量不要感到沮丧。

我要做一个程序(按照朋友的要求,他付钱给我,所以不要判断),通过选择名字/敢于随机来简化游戏,如真或敢。当我刚从一组两个男孩和两个女孩中选择一个人时,它运作良好,然后从我朋友创建的广泛列表中随机选择一个。但是,我想这样做,你可以输入具体的名字,并决定多少名字,而不是选择1-4人。我可能已经使用Go Goled并且没有花时间去理解的命令使其过于复杂,现在它几乎给我所做的每一个更改都会出错。现在,它说的是变量“boys”是不确定的,当我做的时候(至少我认为我做过)早些时候。我认为,即使我修复“男孩”,“女孩”也会遇到同样的问题。您可以提供的任何和所有帮助,简化,纠正错误,以及其他任何事情将不胜感激。我知道这很长很复杂,但任何帮助都会非常惊人。

import random
print "Now, important note, all answers must be made in quotes. I know, it sucks, but that's the way it is and I cannot change it."

print "Ready? [y/n]"
repeat = input()
while repeat == "y":
    print "Are there any boys playing? [y/n]"
    boys1 = input()
    boys2 = "n"
    boys3 = "n"
    boys4 = "n"
    if boys1 == "n":
        repeat == "n"
    if boys1 == "y":
        print "What is the first boy's name?"
        boy1 = input()
        boy2 = ""
        boy3 = ""
        boy4 = ""
        print "Are there any more?"
        boys2 = input()
        boys3 = "n"
        boys4 = "n"
        if boys2 == "y":
            print "What is his name?"
            boy2 = input()
            boy3 = ""
            boy4 = ""
            print "Are there any more?"
            boys3 = input()
            boys4 = "n"
            if boys3 == "y":
                print "What is his name?"
                boy3 = input()
                boy4 = ""
                print "Are there any more?"
                boys4 = input()
                if boys4 == "y":
                    print "What is his name?"
                    boy4 = input()
                    print "The maximum number of boys is four."

    print "Are there any girls playing? [y/n]"
    girls1 = input()
    girls2 = "n"
    girls3 = "n"
    girls4 = "n"
    if girls1 == "n":
        repeat == "n"
    if girls1 == "y":
        print "What is her name?"
        girl1 = input()
        girl2 = ""
        girl3 = ""
        girl4 = ""
        print "Are there any more?"
        girls2 = input()
        girls3 = "n"
        girls4 = "n"
        if girls2 == "y":
            print "What is her name?"
            girl2 = input()
            girl3 = ""
            girl4 = ""
            print "Are there any more?"
            girls3 = input()
            girls4 = "n"
            if girls3 == "y":
                print "What is her name?"
                girl3 = input()
                girl4 = ""
                print "Are there any more?"
                girls4 = input()
                if girls4 == "y":
                    print "What is her name?"
                    girl4 = input()
                    print "The maximum number of girls is four."

    if not boys1 == "y":
        print "There are no boys. The program cannot work." 
        if not boys2 == "y":
            boys = [boy1]
            if not 'boys3' == "y":
                boys = [boy1, boy2]
                if not boys4 == "y":
                    boys = [boy1, boy2, boy3]
                    if boys4 == "y":
                        boys = [boy1, boy2, boy3, boy4]

    if not girls1 == "y":
        print "There are no girls. Your party sucks."
        if not girls2 == "y":
            girls = [girl1]
            if not girls3 == "y":
                girls = [girl1, girl2]
                if not girls4 == "y":
                    girls = [girl1, girl2, girl3]
                    if girls4 == "y":
                        girls = [girl1, girl2, girl3, girl4]

    print random.sample(boys, 1)
    print "must perform the action on"
    print random.sample(girls, 1)

    actions = ["A very long and extensive list of various actions.", "Each in their own section"]
    print random.sample(actions, 1)

    print "Wanna go again?"
    repeat = input()

input()

3 个答案:

答案 0 :(得分:2)

这是一个应该更容易理解的重组版本:

import random
import sys

if sys.hexversion < 0x3000000:
    # Python 2.x
    inp = raw_input
    rng = xrange
else:
    # Python 3.x
    inp = input
    rng = range

def get_yn(prompt):
    while True:
        res = inp(prompt).strip().lower()
        if res in {'y','yes'}:
            return True
        elif res in {'n','no'}:
            return False

def get_int(prompt):
    while True:
        try:
            return int(inp(prompt))
        except ValueError:
            pass

def get_str(prompt):
    while True:
        res = inp(prompt).strip()
        if res:
            return res

rand = random.choice

actions = [
    "{boy} must compliment {girl}'s hair",
    "{girl} must admire {boy}'s muscles"
]

def main():
    num_boys  = get_int("How many boys are playing? ")
    num_girls = get_int("How many girls are playing? ")

    if num_boys < 1 or num_boys > 4:
        print("Must be one to four boys.")
    elif num_girls < 1 or num_girls > 4:
        print("Must be one to four girls.")
    else:
        print("Let's get this party started!")
        boys  = [get_str("Name of boy {}: " .format(i)) for i in rng(1, num_boys+1) ]
        girls = [get_str("Name of girl {}: ".format(i)) for i in rng(1, num_girls+1)]

        while True:
            act = rand(actions)
            boy = rand(boys)
            girl = rand(girls)
            print(act.format(boy=boy, girl=girl))

            if not get_yn("Want to continue? "):
                break

if __name__=="__main__":
    main()

答案 1 :(得分:0)

欢迎编程!我很高兴听到你正在探索编程!

阅读Don't Repeat Yourself (DRY)

同样在Object Oriented Programming (OOP)(在Python(和大多数语言?)中,“对象”通常被称为:Classes

答案 2 :(得分:0)

为了显示OP,这可能会有多大改善(甚至可以改善,但作为一个例子很好),我花了几分钟来简化事情:

while True:
    try:
        num_girls = raw_input("Number of girls? ")
        num_girls = int(num_girls)
        if num_girls > 4 or num_girls < 0:
            raise Exception("Number of girls must be between 0 and 4")
        if num_girls == 0:
            print "Your party is going to suck"
        break
    except ValueError as e:
        print "You must enter a number 0-4"
    except Exception as e:
        print e

girls = []
for i in range(num_girls):
    girls.append(raw_input("Name of girl #%d: " % (i + 1)))

while True:
    try:
        num_boys = raw_input("Number of boys? ")
        num_boys = int(num_boys)
        if num_boys > 4 or num_boys < 0:
            raise Exception("Number of boys must be between 1 and 4")
        break
    except ValueError as e:
        print "You must enter a number 1-4"
    except Exception as e:
        print e

boys = []
for i in range(num_boys):
    boys.append(raw_input("Name of boy #%d: " % (i + 1)))

然后你可以在最后进行随机抽样。