app = "google facebook yahoo"
prec = 0
test = 0
while test < 4 :
print "The test is test%d" % (test)
while prec < 4 :
prec = prec + 1
for i in app.split():
print "The word is " + (i) + " precedence %d" % (prec)
不断印刷以下
The test is test0
The test is test0
The test is test0
The test is test0
The test is test0
The test is test0
The test1 is
The word is google precedence 1
The word is facebook precedence 2
The word is yahoo precedence 3
The test2 is
The word is google precedence 1
The word is facebook precedence 2
The word is yahoo precedence 3
The test3 is
The word is google precedence 1
The word is facebook precedence 2
The word is yahoo precedence 3
The test4 is
The word is google precedence 1
The word is facebook precedence 2
The word is yahoo precedence 3
请指导我如何实现此输出。提前谢谢。
答案 0 :(得分:2)
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
答案 1 :(得分:2)
一个问题是你的循环没有嵌套。接下来是你的第一个循环
while test < 4 :
print "The test is test%d" % (test)
是一个无限循环,因为你的变量&#34; test&#34;设置为0并且循环中永远不会更改。所以测试&lt; 4总是如此。
你可以这样做。
apps = "google facebook yahoo"
for i in range (1,4):
print 'test' + str(i) + 'is...'
precedence = 1
for app in apps.split():
print "The word is " + app + " precedence " + str(precedence)
precedence += 1
答案 2 :(得分:1)
好的我尝试通过尽可能少地修改原始代码来修复它。
首先,当你使用while循环时,你需要确保它可以被打破。虽然循环基本上意味着“运行此任务,直到达到某个条件”。在你的情况下,你的while循环将运行,直到test大于或等于4.所以为了打破我在循环开始时添加了以下代码。
test += 1
+ =只是test = test + 1
的简写一旦测试达到4,程序将退出while循环。
代码中不需要第二个while循环,因为你已经有一个遍历字符串的for循环。在这种情况下,只需删除第二个并将预计数器放在for循环内就更简单了。为了确保为每个循环重置计数器,我在while循环内移动了prec = 0但在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)