如何在else语句中使用多行代码?
我正在尝试写一个简单的数字相加器,这个功能是一个更复杂程序的一部分。我的代码是在一个if-else语句里面。
else:num1=input("Enter the first number")
num2=input("Enter the second number")
print num1 + num2
但是,这样做会出现错误……
num2=input("Enter the second number")
^
IndentationError: unexpected indent
那么,怎么才能写一个多行的else语句呢?
3 个回答
0
你试过下面这些方法吗?
else:
num1=input("Enter the first number")
num2=input("Enter the second number")
print num1 + num2
4
那么,如何创建一个多行的else语句呢?
和Python中的其他复合语句一样:换行,然后缩进。就像这样:
else:
num1=input("Enter the first number")
num2=input("Enter the second number")
print num1 + num2
(严格来说,else
不是一个独立的语句,它是if
语句的一部分,但我们可以暂时不考虑这个。)
具体的细节可以在文档中的复合语句部分找到,但我觉得除非你想自己写一个Python解析器,不然你可能不想去看那些内容。基本规则是,在冒号后面,你可以有以下两种情况:
- 在同一行上写一个简单的语句(没有自己的冒号)。
- 这一行没有其他内容,然后在下面缩进写出你想要的简单和复合语句(至少要有一个)。
11
在else:
后面加一个换行,并把你所有的代码往右缩进,像这样:
else:
num1 = input("Enter the first number")
num2 = input("Enter the second number")
print num1 + num2