有什么问题?

时间:2015-02-01 20:39:05

标签: python python-3.x

我做了一个简单的西蒙说游戏并不完整。 我的问题是,IDLE 3.4说当我看不到它会有什么问题时我会遇到问题。

我的代码(演练):

#Simple pattern repeating game
#Randomly chooses a pattern then user has to repeat

import random

poss = [int(1), int(2), int(3), int(4)]
#Sets possible choices
pattern = []
#Sets an array for the pattern to be contained in
plyr = []
#Sets an array for the players pattern to be contained in

def game ():
#Makes a function for the game to be played
    pattern.append(random.choice(poss))
    #Adds a new value to the game pattern every time
    for i in pattern:
    #Loops through the pattern
        print(i)
        #Prints the pattern you need to copy
        #For testing it sticks but this is to be change


    for i in pattern :
    #Loops through the pattern so you can give your value
        plyr[i] = int(input("Pattern part " + (i + 1) + " is?")
        #Gets your input of that value in the pattern

if(plyr == pattern):
#Checks if your pattern is right
    game()
    #Continues the game 

我的问题出现在if语句中,结果是冒号(:)错误。

有人知道问题是什么吗?

2 个答案:

答案 0 :(得分:2)

您错过了前一行的右括号:

plyr[i] = int(input("Pattern part " + (i + 1) + " is?")
#            1     2                  3     3         2?

int()来电未正确关闭。因为Python允许将逻辑行扩展到下一个右括号,所以下一行是表达式的一部分,并且只有到达冒号时才会出现明显的错误。

您接下来会发现i + 1生成一个整数,不能用字符串求和。您想要添加str()来电:

plyr[i] = int(input("Pattern part " + str(i + 1) + " is?"))

或使用字符串格式:

plyr[i] = int(input("Pattern part {} is?".format(i + 1))

由于plyr为空,这会引发IndexError;你不能改变列表中没有的索引。您可能打算将追加新元素添加到列表中:

player_guess = int(input("Pattern part {} is?".format(i + 1))
plyr.append(player_guess)

这会将玩家猜测变为新变量(更易于阅读)并将结果附加到plyr列表。

答案 1 :(得分:1)

你的代码有一些错误,缺少一些紧密的括号。我为你做了一个版本:

import random

poss = [int(1), int(2), int(3), int(4)]
# Sets possible choices
pattern = []
# Sets an array for the pattern to be contained in
plyr = []
# Sets an array for the players pattern to be contained in

def game():
    # Makes a function for the game to be played
    pattern.append(random.choice(poss))
    # Adds a new value to the game pattern every time
    for i in pattern:
        # Loops through the pattern
        print(i)
        # Prints the pattern you need to copy
        # For testing it sticks but this is to be change

    for i in pattern:
        # Loops through the pattern so you can give your value
        plyr[i] = int(input("Pattern part {} is?".format(i + 1)))
        # Gets your input of that value in the pattern

if plyr == pattern:
    # Checks if your pattern is right
    game()