繁体   English   中英

在 python 中练习循环时遇到问题

[英]Having problems with practicing loop in python

import time
import random
import math

start = 1
stop = 10

for i in range(start, stop):
    time.sleep(1)
    print("\ni = {}".format(i), end = "")
    count = 3 + random.randint(1,5)
    print(", count = {}".format(count))
    nums = []
    while len(nums) < count:
        for j in range(count):
            time.sleep(0.3)
            try:
                num = random.randint(-10,100)
                log = round(math.log(num),1)
            except:
                time.sleep(2)
                print("\nagain")
                break
            nums.append(log)
            print("\rnums = {}".format(nums), end = "")

我想要做的是为每次迭代i提供一个随机的 integer count ,然后使用while循环到 append numnums的对数,直到nums的长度等于count 这里num是一个介于 -10 和 100 之间的随机 integer,如果num为 0 或更低,我想从for i in range(start, stop):的最开始再次开始循环,即time.sleep(1) ,这样我就可以指定新的count并制作新的nums

所以我执行了上面的代码,它从while len(nums) < count:的开头再次开始循环。

例如,我所期望的是

i = 1, count = 7
nums = [4.2, 4.4, 2.9, 4.4]
again
i = 1, count = 5
nums = [3.5, 3.6, 4.2]
again
i = 1, count = 6
nums = [2.0, 3.2, 3.5, 3.6, 4.2, 4.5]
i = 2, count = 5
nums = [4.5, 4.1, 4.0, 3.9, 3.8]
i = 3, count = 6
nums = [4.3, 3.8]
again
i = 3, count = 5
nums = [3.0, 3.4, 4.6, 3.6, 3.1]

等等

我得到的是

i = 1, count = 7
nums = [4.2, 4.4, 2.9, 4.4, 3.2, 2.6]
again
nums = [4.2, 4.4, 2.9, 4.4, 3.2, 2.6, 4.0, 1.4, 3.5, 3.6, 3.5, 4.4, 2.9]
i = 2, count = 4

again
nums = [4.5, 4.1, 4.0, 3.9]
i = 3, count = 6
nums = [4.3, 3.8]
again
nums = [4.3, 3.8, 3.6, 2.3, 3.4, 4.6, 3.6, 3.1]
i = 4, count = 5
nums = [1.4, 3.0, 4.0, 4.4, 4.0]
i = 5, count = 7
nums = [4.4, 2.9, 3.5, 4.2, 3.6, 4.4, 4.6]

等等

将其全部放入 function 并在num小于或等于 0 时再次调用它

import time
import random
import math

start = 1
stop = 10

def whatever():
    for i in range(start, stop):
        time.sleep(1)
        print("\ni = {}".format(i), end = "")
        count = 3 + random.randint(1,5)
        print(", count = {}".format(count))
        nums = []
        while len(nums) < count:
            for j in range(count):
                time.sleep(0.3)
                num = random.randint(-10,100)

                if num <= 0:
                    time.sleep(2)
                    print("\nagain")
                    whatever()
                else:
                    log = round(math.log(num),1)
                    nums.append(log)

                print("\rnums = {}".format(nums), end = "")

whatever()

如果num小于或等于 0,这是循环将再次开始的地方

if num <= 0:
    time.sleep(2)
    print("\nagain")
    whatever()

Output

i = 1, count = 8
nums = [4.2, 2.9, 3.8, 2.1, 4.0, 4.1, 3.8, 4.4]
i = 2, count = 5
nums = [3.4, 3.2, 3.6, 4.5]
again

i = 1, count = 8
nums = [3.5, 4.2, 4.3, 3.9, 3.5, 4.3, 1.1, 3.2]
i = 2, count = 7

again

i = 1, count = 8
nums = [2.4, 3.0, 4.5, 4.1, 4.2, 4.5, 3.6]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM