Python上机作业(常用内置数据类型)

一、第一题:
'''编程实现迭代法求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

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小Java开发者

“是一种鼓励,你懂的”

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值