我是python编程的初学者。我编写了以下程序,但它没有像我想要的那样执行。这是代码:
b=0
x=0
while b<=10:
print 'here is the outer loop\n',b,
while x<=15:
k=p[x]
print'here is the inner loop\n',x,
x=x+1
b=b+1
有人能帮帮我吗?我将非常感激!
问候,
吉拉尼
答案 0 :(得分:24)
不确定您的问题是什么,也许您想在内循环之前放置x=0
?
你的整个代码看起来并不像Python代码......这样的循环最好这样做:
for b in range(0,11):
print 'here is the outer loop',b
for x in range(0, 16):
#k=p[x]
print 'here is the inner loop',x
答案 1 :(得分:11)
因为你在外部while循环之外定义了x,它的作用域也在外部循环之外,并且在每个外部循环之后它不会被重置。
要修复此移动,外部循环中x的定义:
b = 0
while b <= 10:
x = 0
print b
while x <= 15:
print x
x += 1
b += 1
使用简单边界的简单方法就是使用for循环:
for b in range(11):
print b
for x in range(16):
print x
答案 2 :(得分:0)
运行你的代码如果“'p'没有defind”,那么我会收到一个错误“这意味着你在尝试使用数组p之前就会出现错误。
删除该行可让代码以
的输出运行here is the outer loop
0 here is the inner loop
0 here is the inner loop
1 here is the inner loop
2 here is the inner loop
3 here is the inner loop
4 here is the inner loop
5 here is the inner loop
6 here is the inner loop
7 here is the inner loop
8 here is the inner loop
9 here is the inner loop
10 here is the inner loop
11 here is the inner loop
12 here is the inner loop
13 here is the inner loop
14 here is the inner loop
15 here is the outer loop
1 here is the outer loop
2 here is the outer loop
3 here is the outer loop
4 here is the outer loop
5 here is the outer loop
6 here is the outer loop
7 here is the outer loop
8 here is the outer loop
9 here is the outer loop
10
>>>
答案 3 :(得分:0)
您需要在处理内部循环后重置x变量。否则你的外环将在不触发内环的情况下运行。
b=0
x=0
while b<=10:
print 'here is the outer loop\n',b,
while x<=15:
k=p[x] #<--not sure what "p" is here
print'here is the inner loop\n',x,
x=x+1
x=0
b=b+1