2017-03-06 154 views
1

我要做的就是打印出5 4 3 2 1 然后4 3 2 1在那之下然后3 2 1依此类推,现在我所拥有的就是第一行所以我会得到5 4 3 2 1或6 5 4 3 2 1,但我似乎无法得到它试图让它继续,直到达到1Python循环随机数

from random import choice 
    i=choice([5,6,7,8,9,10]) 
    while i: 
     print(i, end=" ") 
     i -= 1 
     if(i <1): 
      break 
+0

听起来像你需要两个循环,而不仅仅是一个。 – khelwood

回答

1

一个紧凑的方法:

import random as rnd 

length = rnd.choice([5, 6, 7, 8, 9, 10]) 
lst = [str(x) for x in range(length, 0, -1)] 
while lst: 
    print(" ".join(lst)) 
    lst.pop(0) 

更换rangexrange如果你正在使用Python 2.7。

0

你需要两个循环的权利时,一个做最初的倒计时(5,4,3,2,1),另一个循环遍历你需要产生的每个列表。例如:

from random import choice 
i=choice([5,6,7,8,9,10]) 
for j in [*range(i,0,-1)]: 
    for k in [*range(j,0,-1)]: 
     print(k, end=" ") 
    print('') 
0

您可以试试这个。

from random import choice 
x = choice([5,6,7,8,9,10]) 
while x > 0: 
    y = x 
    while y > 0: 
     print y, 
     y = y-1 
    print "\n" 
    x = x-1 
+0

你好,这是我寻找的代码的类型,但是当我尝试运行时,它有一个错误,由y和“\ n”,我一直在编辑它,所以它运行,但不能似乎得到它100% –