python 中的简单 while 循环问题(缩进)
Problem with simple while loop in python (indentation)
while 1 == 1: line(1)
x = 1 line(2)
print(x) line(3)
x = x + 10 line(4)
我今天开始使用 python,我了解到它不像 java 那样使用方括号 {} 来关闭循环,而是使用缩进。
上面的代码 运行 仅当我删除第 (4) 行时。我应该如何修改代码以使其 运行s 包含最后一行?我使用了 netbeans 的格式,但仍然没有 运行。
python 中的缩进是如何工作的?我觉得它不使用括号很奇怪。
How indentation works in python? I find it very weird that it doesn't use brackets.
像 {
= 缩进,}
= 缩进,但你不能有随机块 "just because" - 每个这样的块都需要一个控制结构来引入它。因此,您的代码将以括号语言编写如下:
while (1 == 1) {
x = 1
print(x)
???? {
x = x + 10
}
}
x = x + 10
的块不对应任何控制结构,因此缩进不应超过print(x)
。
while 1 == 1: line(1)
x = 1 line(2)
print(x) line(3)
x = x + 10 line(4)
Java 等效 ->
while (1 == 1)
{
x = 1
System.out.println(x)
x = x + 10
}
在 Java 中,同一缩进中的所有缩进都被视为括号。
与 Java 相比,缩进在 Python 中非常重要,您可以在不同的代码行中使用不同的缩进。
只需比较 javascript 和 python 之间的语法差异即可。
javascript:
function foo() {
for (var i=0; i<10; i++) {
console.log(i);
}
}
python
def foo():
for i in range(10):
print i
你的情况
你的代码
while 1 == 1:
x = 1
print(x)
x = x + 10
等价javascript代码
while(1==1){
var x=1;
console.log(x) {
x = x + 10 ;
}
}
这没有意义。应该是
while(1==1){
var x=1;
console.log(x);
x = x + 10
}
等价python代码
while 1 == 1:
x = 1
print(x)
x = x + 10
我只是试图纠正你的缩进问题,但实际上如果你正在寻找增量,上面的代码是无效的,因为 x=1 赋值是在循环内,这意味着 print(x) 总是打印 1
更正代码
x = 1
while 1 == 1:
print(x)
x = x + 10
python 不使用括号来声明范围。它改用制表符。
您只需要将您的声明放在同一个选项卡中即可。
正确的代码是:
while 1 == 1:
x = 1
print(x)
x = x + 10
while 1 == 1: line(1)
x = 1 line(2)
print(x) line(3)
x = x + 10 line(4)
我今天开始使用 python,我了解到它不像 java 那样使用方括号 {} 来关闭循环,而是使用缩进。
上面的代码 运行 仅当我删除第 (4) 行时。我应该如何修改代码以使其 运行s 包含最后一行?我使用了 netbeans 的格式,但仍然没有 运行。
python 中的缩进是如何工作的?我觉得它不使用括号很奇怪。
How indentation works in python? I find it very weird that it doesn't use brackets.
像 {
= 缩进,}
= 缩进,但你不能有随机块 "just because" - 每个这样的块都需要一个控制结构来引入它。因此,您的代码将以括号语言编写如下:
while (1 == 1) {
x = 1
print(x)
???? {
x = x + 10
}
}
x = x + 10
的块不对应任何控制结构,因此缩进不应超过print(x)
。
while 1 == 1: line(1)
x = 1 line(2)
print(x) line(3)
x = x + 10 line(4)
Java 等效 ->
while (1 == 1)
{
x = 1
System.out.println(x)
x = x + 10
}
在 Java 中,同一缩进中的所有缩进都被视为括号。 与 Java 相比,缩进在 Python 中非常重要,您可以在不同的代码行中使用不同的缩进。
只需比较 javascript 和 python 之间的语法差异即可。
javascript:
function foo() {
for (var i=0; i<10; i++) {
console.log(i);
}
}
python
def foo():
for i in range(10):
print i
你的情况
你的代码
while 1 == 1:
x = 1
print(x)
x = x + 10
等价javascript代码
while(1==1){
var x=1;
console.log(x) {
x = x + 10 ;
}
}
这没有意义。应该是
while(1==1){
var x=1;
console.log(x);
x = x + 10
}
等价python代码
while 1 == 1:
x = 1
print(x)
x = x + 10
我只是试图纠正你的缩进问题,但实际上如果你正在寻找增量,上面的代码是无效的,因为 x=1 赋值是在循环内,这意味着 print(x) 总是打印 1
更正代码
x = 1
while 1 == 1:
print(x)
x = x + 10
python 不使用括号来声明范围。它改用制表符。 您只需要将您的声明放在同一个选项卡中即可。
正确的代码是:
while 1 == 1:
x = 1
print(x)
x = x + 10