如何使脚本停止无效输入

时间:2014-02-14 22:14:26

标签: python input

一旦评估输入错误,需要学习如何停止脚本

继续我的问题14/19“测试运行”对于codeacademy中的python指南它要求你仔细检查你的代码并尝试所有无效的输入,我的代码适用于用户可以输入的任何数字,但输入一个单词会回复错误。所以我试图修复它,我的问题是现在它评估我的输入不是一个数字并打印出我的无效输入错误“这不是一个数字”但它继续脚本的其余部分,直到它到达我的其他无效输入错误“即使它只是在海洋中”,即使它只是一个字而不是数字。 所以基本上它现在告诉我“它不是一个数字”和“它不在海洋中”但我希望它只是停在它不是一个数字。继承我的代码

from random import randint

board = []

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)

ship_row = random_row(board)
ship_col = random_col(board)

print ship_row
print ship_col

guess_row = raw_input("Guess Row:")
guess_col = raw_input("Guess Col:")

if guess_row.isdigit() == True and guess_col.isdigit() == True:
    guess_row = int(guess_row)
    guess_col = int(guess_col)
elif guess_row.isdigit() == False or guess_col == False:
    print "Thats not a number!" 

#如果输入不是数字,希望脚本停在这里。

if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
elif guess_row >= 5 and guess_col >= 5:
    print_board(board) 
    print "Oops, that's not even in the ocean."
elif board[int(guess_row)][int(guess_col)] == "X":
    print "You guessed that one already."
else:
    print "You missed my battleship!"
    board[int(guess_row)][int(guess_col)] = "X"
    print_board(board)

我感谢任何反馈,批评是什么有助于你学习,对吧?并谢谢。

1 个答案:

答案 0 :(得分:1)

我认为你真的不需要停止脚本,只需再次询问一个号码:

guess_row = ""
guess_col = ""
while not (guess_row.isdigit() and guess_col.isdigit()):
    guess_row = raw_input("Guess Row:")
    guess_col = raw_input("Guess Col:")

    if guess_row.isdigit() and guess_col.isdigit():
        guess_row = int(guess_row)
        guess_col = int(guess_col)
    else:
       print "Thats not a number! Try again!" 

了解我如何编辑你的if-else语句。 guess_row.isdigit() == True等同于guess_row.isdigit(),因为它返回一个布尔值。与== False相同,它相当于not guess_row.isdigit()。另外,您不需要elif,因为如果其中一个语句或两者都是False,那么您无论如何都会进入else语句。

如果你真的想结束该计划,那么:

import sys
sys.exit()