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 = "")
What I want to do is giving a random integer count
for each iteration i
, then using a while
loop to append the log of num
to nums
until the length of nums
equals to count
. Here num
is a random integer between -10 and 100, and if num
is given as 0 or below, I want to start the loop again from the very beginning of for i in range(start, stop):
, which is time.sleep(1)
, so that I can designate new count
and make new nums
.
So I executed the code above, and it starts the loop again from the beginning of while len(nums) < count:
.
For example, what I expected was something like
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]
and so on
And what I got is
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]
and so on
Put it all in a function and call it again whenever num
is less than or equal to 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()
This is where the loop will start again if num
is less than or equal to 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.