嵌套循环的组合为;至于;及;而"; 我的Python脚本: 预期产出:

嵌套循环的组合为;至于;及;而"; 我的Python脚本: 预期产出:,python,python-2.7,pexpect,Python,Python 2.7,Pexpect,请指导我如何实现这个输出。提前感谢。while循环中的这些变量没有更改,因此它们的值永远不会更改,循环也永远不会退出 这应该起作用: apps = ['google', 'facebook', 'yahoo'] for i in xrange(4): print 'test' + str(i) + 'is...' for app in apps: print "The word is " + app + " precedence %d" % i while循环

请指导我如何实现这个输出。提前感谢。

while循环中的这些变量没有更改,因此它们的值永远不会更改,循环也永远不会退出

这应该起作用:

apps = ['google', 'facebook', 'yahoo']

for i in xrange(4):
    print 'test' + str(i) + 'is...'
    for app in apps:
        print "The word is " + app + " precedence %d" % i

while循环中的这些变量没有更改,因此它们的值永远不会更改,循环也永远不会退出

这应该起作用:

apps = ['google', 'facebook', 'yahoo']

for i in xrange(4):
    print 'test' + str(i) + 'is...'
    for app in apps:
        print "The word is " + app + " precedence %d" % i

一个问题是循环没有嵌套。接下来就是你的第一个循环

while test < 4 :
    print "The test is test%d" % (test)

一个问题是循环没有嵌套。接下来就是你的第一个循环

while test < 4 :
    print "The test is test%d" % (test)

好的,我试图通过尽可能少地修改原始代码来修复它

首先,每当你使用while循环时,你都需要确保它可以被打破。而循环的基本意思是“运行此任务直到达到某个条件”。在您的情况下,while循环将一直运行,直到test大于或等于4。因此,为了中断,我在循环的开头添加了以下代码

test += 1
+=只是test=test+1的简写

一旦测试达到4,程序将退出while循环

代码中不需要第二个while循环,因为您已经有了一个在字符串上迭代的for循环。在这种情况下,只需移除第二个while并将prec计数器放置在for循环内部就简单多了。为了确保为每个循环重置计数器,我将prec=0移动到while循环内部,但移动到for循环外部。每次for循环运行时都是这样,prec从0开始,然后递增到1,2,3,然后返回到0

希望有帮助

#!/usr/bin/python
app = "google facebook yahoo"
test = 0
while test < 4 :
    test += 1
    print "The test is test%d" % (test)
    prec = 0
    for i in app.split():
        prec = prec + 1
        print "The word is " + (i) + " precedence %d" % (prec)
#/usr/bin/python
app=“谷歌facebook雅虎”
测试=0
当试验<4时:
测试+=1
打印“测试为测试%d%”(测试)
prec=0
对于应用程序中的i.split():
prec=prec+1
打印“单词是”+(i)+“优先级%d”%(prec)

好的,我试图通过尽可能少地修改原始代码来修复它

首先,每当你使用while循环时,你都需要确保它可以被打破。而循环的基本意思是“运行此任务直到达到某个条件”。在您的情况下,while循环将一直运行,直到test大于或等于4。因此,为了中断,我在循环的开头添加了以下代码

test += 1
+=只是test=test+1的简写

一旦测试达到4,程序将退出while循环

代码中不需要第二个while循环,因为您已经有了一个在字符串上迭代的for循环。在这种情况下,只需移除第二个while并将prec计数器放置在for循环内部就简单多了。为了确保为每个循环重置计数器,我将prec=0移动到while循环内部,但移动到for循环外部。每次for循环运行时都是这样,prec从0开始,然后递增到1,2,3,然后返回到0

希望有帮助

#!/usr/bin/python
app = "google facebook yahoo"
test = 0
while test < 4 :
    test += 1
    print "The test is test%d" % (test)
    prec = 0
    for i in app.split():
        prec = prec + 1
        print "The word is " + (i) + " precedence %d" % (prec)
#/usr/bin/python
app=“谷歌facebook雅虎”
测试=0
当试验<4时:
测试+=1
打印“测试为测试%d%”(测试)
prec=0
对于应用程序中的i.split():
prec=prec+1
打印“单词是”+(i)+“优先级%d”%(prec)

Kumar您需要在第一个while循环中增加测试变量。实际上,这是行不通的-在Python中无法连接字符串和整数<代码>打印“测试”,测试“是…”也可以<代码>打印“test{}is…”。格式(test)会更好。Kumar您需要在第一个while循环中增加test变量。实际上,这不起作用-您不能在Python中连接字符串和整数<代码>打印“测试”,测试“是…”也可以
print“test{}is…”格式(test)
更好。您还可以向他演示如何在内部循环中使用
enumerate
。您还可以向他演示如何在内部循环中使用
enumerate