day13

day13
1.使用 while,计算随机数之和,超过 100 的时候,停
止程序。随机数 1-20 的范围产生,要求记录一下产生的随
机数,以及最后的和,以及随机数的个数
>>> import random
>>> count = 0
>>> num = []
>>> num_add = 0
>>> while True:
... n = random.randint(1,20)
... num_add += n
... if num_add > 100:
... print(num_add)
... break
... num.append(n)
... print(n)
count = len(num)
方法2:
import random
count = 0
result = []
while count <= 100:
n = random.randint(1,20)
count += n
result.appen(n)
 
2.遍历字符串、列表,分别基于位置和和基于字符遍历
遍历字符:s = 'adfsad'
for i in range(len(s)):
print(s[i])
for i in s:
print(i)
遍历列表:l = [1,2,3,4,5]
for i in l:
print(i)
for i in range(len(l)):print(l[i])
 
3.遍历一个列表中的嵌套列表和元组的所有元素,将
1-12 的数字进行输出![[[1,2,3],4,5],7,8,(9,10,(11,12))]
注:次解法只针对这个题,能不能自己判断并循环输出?
list1 = [[[1,2,3],4,5],7,8,(9,10,(11,12))]
>>> for i in range(len(s)):
... if isinstance(s[i],list):
... for k in range(len(s[i])):
... print(s[i][k])
... if isinstance(s[i][k],list):
... for m in s[i][k]:
... print(m)
print(s[i][k])
... elif isinstance(s[i],tuple):
... print(s[i])
... for n in s[i]:
... print(n)
if isinstance(s[i][n],tuple):
for b in s[i][n]:
print(b)
print(s[i][n])
... else:
... print(s[i])
 
4.判断一个数是不是素数
math.sqrt() # 平方根
import math
def is_prime(num):
if num == 0:
return Flase
elif num == 1:
return Flase
elif num == 2:
return True
else:
for i in range(2,int(math.sqrt(num))+1):
if num % i == 0:
return Flase
return True
 
5.求100以内的素数之和
result = 0
for i in range(100):
if is_prime(i):
result += i
print(result)

posted @ 2019-12-23 10:01  绝世老中医  阅读(219)  评论(0编辑  收藏  举报