【问题标题】:elif statement won't run in Pythonelif 语句不会在 Python 中运行
【发布时间】:2017-04-30 00:43:44
【问题描述】:

这是我的代码。从 codeacademy 实验室运行时,它一直说的最后一个 ELIF 语句是错误的 - BATTLESHIP GAME EXERCISE!

from random import randint

    board = []
#
# All code functions here

    for x in range(0, 5):
        board.append(["O"] * 5)

    def print_board(board):
        for row in board:
            print " ".join(row)

    print_board(board)

    def random_row(board):
        return randint(0, len(board) - 1)

    def random_col(board):
        return randint(0, len(board[0]) - 1)

# All game variables for row and col guessing

    ship_row = random_row(board)
    ship_col = random_col(board)
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))

# Prints the variable chosen randomly
    print ship_row
    print ship_col

#
    if guess_row == ship_row and guess_col == ship_col:
        print "Congratulations! You sank my battleship!"

本声明。 CODEACADEMY 一直说是错误的,即使它运行了

它有什么问题?

    elif guess_row not in range(0, len(board)-1) or guess_col not in        
        range(0, len(board)-1):
         print "Oops, that's not even in the ocean"

# final else statement. Prints missed battleship msg 
# end of code   
    else:
        print "You missed my battleship!" # msg lost game
        board[guess_row][guess_col]="X"   # shows guess var
        print_board(board)    

# end of code. Last else statement.         

【问题讨论】:

  • 那是因为 stackOverFlow 编辑器。 elif 验证在我的终端中都在一行中

标签: python-2.7 if-statement


【解决方案1】:

我不知道你是怎么让它运行的,因为 python 对空格很挑剔。

也许就是这样,但由于某种原因,codecademy 允许您在他们的控制台中运行它,如果您在 PC 上安装了 python 调用该文件,它不会运行。

from random import randint

board = []

# All code functions here

for x in range(0, 5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

# All game variables for row and col guessing

ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

# Prints the variable chosen randomly
print ship_row
print ship_col


if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"

# THIS STATEMENT. CODEACADEMY KEEPS SAYING IS WRONG EVEN THOUGH IT 
# RUNS
# WHAT'S WRONG WITH IT?

elif guess_row != (0, len(board)-1) or guess_col != range(0, len(board)-1):
    print "Oops, that's not even in the ocean"

【讨论】:

    猜你喜欢
    • 2017-07-03
    • 2017-08-17
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 2022-11-23
    相关资源
    最近更新 更多