Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:当出现某个错误时,使用if语句执行某项操作?_Python - Fatal编程技术网

Python:当出现某个错误时,使用if语句执行某项操作?

Python:当出现某个错误时,使用if语句执行某项操作?,python,Python,我正在python上制作一个connect4游戏,当一列已满时,当玩家将一个片段放入整列时,会出现此错误。我如何制作一个if语句来说明如果出现此错误,请打印(“进行有效移动?”) 使用try/except try: # your code here except YourError: # do something 这样做的目的是执行一段代码,并“捕获”给定的异常(如果发生)。例如,检查以下代码: try: num = raw_input('Enter an number

我正在python上制作一个connect4游戏,当一列已满时,当玩家将一个片段放入整列时,会出现此错误。我如何制作一个if语句来说明如果出现此错误,请打印(“进行有效移动?”)


使用
try/except

try:
    # your code here
except YourError:
    # do something
这样做的目的是执行一段代码,并“捕获”给定的异常(如果发生)。例如,检查以下代码:

try:
    num = raw_input('Enter an number: ')  # user enters something
    num = int(num)  # Python tries to convert it to an integer
except ValueError:  # if the input was invalid
    print 'You didn\'t enter an valid number'

在Python中的try-except块中处理异常;当你不知道语言语法时,为什么要写游戏?@ClassStacker:要学习语言语法?愚蠢的问题,真的,制作一个connect4游戏显然是一个练习。@cha0site和练习意味着您既不会获得所需Python概念的介绍,也不会阅读Python.org文档,也不会在web上搜索Python异常?;)
try:
    num = raw_input('Enter an number: ')  # user enters something
    num = int(num)  # Python tries to convert it to an integer
except ValueError:  # if the input was invalid
    print 'You didn\'t enter an valid number'