一、第一题:
'''编程实现迭代法求a的开平方根'''
import math
a = int(input("请输入任意实数a(>=0):"))
y = math.sqrt(a)
x = a/2
while(abs(y-x) >= pow(10,-6)):
x = 0.5*(x + a/x)
print(str.format("{0}的算数平方根={1}",a,x))
二、第二题:
'''计算机Sn=1+11+111+1111+.....'''
import random
n = random.randint(1,10)
x = 1
s = 0
for i in range(1,n+1):
s += x
x = 10*x+1
print("n = {0},Sn = {1}".format(n,s))
'''实现鸡兔同笼问题'''
h = int(input("请输入总头数:"))
f = int(input("请输入总脚数:"))
def fun1(h,f):
rabbits = f/2-h
chicken = h-rabbits
if(chicken < 0 or rabbits < 0):
return '无解'
return chicken,rabbits
def fun2(h,f):
for i in range(0,h+1):
if(2*i + 4*(h-i) == f):
return i,h-i
return '无解'
if(h>0 and f>0 and f % 2 == 0):
if fun1(h,f)=='无解':
print("无解")
else:
print("方法一:鸡:{0}只,兔:{1}只".format(fun1(h,f)[0],fun1(h,f)[1]))
print("方法二:鸡:{0}只,兔:{1}只".format(fun2(h,f)[0],fun2(h,f)[1]))
else:
print('输入错误,请重新输入!')
#文件读取方式实现猜单词游戏:
import random
import sys
f=open("F:/python/python.txt",'r',encoding='UTF-8')
WORDS=list()
while True:
line=f.readline().replace('\n','') #读取一行,进行去掉后面的换行符
if line:
WORDS.append(line)
else:
break
f.close()
right = 'Y'
print("欢迎参加猜单词游戏!")
while right=='Y' or right=='y':
word=random.choice(WORDS)
correct=word
newword = ''
while word:
pos=random.randrange(len(word))
newword+=word[pos]
word = word[:pos]+word[(pos+1):]
print("你要猜测的单词为:",newword)
guess = input("请输入你的答案:")
count=1
while count<5:
if guess!=correct:
guess = input("输入的单词错误,请重新输入:")
count+=1
else :
print("输入的单词正确,正确单词为:",correct)
break
if count == 5:
print("您已猜错5次,正确的单词为:",correct)
right = input("是否继续,Y/N:")
F:/python/python.txt内容:
math
english
china
history
python
运行结果: