练习 1:写函数,求n个随机整数均值的平方根,整数范围在m与k之间。
In [13]:
import random,math
def Square():
m=int(input('plz input the min '))
k=int(input('plz input the max '))
n=int(input('plz input n : '))
i=0
total=0
while i<n:
i+=1
temp=random.randint(m,k)
total+=temp
print (math.sqrt(total/n))
Square()
练习 2:写函数,共n个随机整数,整数范围在m与k之间,求西格玛log(随机整数)及西格玛1/log(随机整数)
In [14]:
import random,math
def total():
m=int(input('plz input the min '))
k=int(input('plz input the max '))
n=int(input('plz input n :'))
i=0
Sum1=0
Sum2=0
while i<n:
i+=1
temp=random.randint(m,k)
Sum1+=math.log10(temp)
Sum2+=1/(math.log10(temp))
print(Sum1,Sum2)
total()
练习 3:写函数,求s=a+aa+aaa+aaaa+aa...a的值,其中a是[1,9]之间的随机整数。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘输入。
In [1]:
import random,math
def Sum():
a=random.randint(1,9)
n=int(input('plz input n: ' ))
i=0
Sum=0
total=0
while i<n:
i+=1
temp=10**(i-1)
Sum=Sum+temp*a
total+=Sum
print(a)
print(total)
Sum()
挑战性练习:将猜数游戏改成由用户随便选择一个整数,让计算机来猜测的猜数游戏。
In [3]:
import random,math
def guess():
n=int(input('plz input n (n:1-10) : '))
r=random.randint(1,10)
print(r)
an=int(input('''
1,bigger
2,smaller
3,u win
'''
))
if(an==3):
print('u win!')
else:
while an!=3:
if(an==1):
print(r)
an=int(input('''
1,bigger
2,smaller
3,u win
'''
))
r=random.randint(1,r)
elif(am==2):
print(r)
an=int(input('''
1,bigger
2,smaller
3,u win
'''
))
r=random.randint(r,10)
guess()