python测试题2_python 练习题2

# 习题1:

# 设定一个用户名和密码,用户输入正确的用户名和密码,

# 则显示登录成功,否则提示登录失败,用户最多失败3次,

# 否则退出程序。

username="test"

password="test1234"

for i in range(3):

user_name=input("input the username:")

pass_word=input("input the password")

if user_name==user_name and pass_word==password:

print("login successfully!")

break

else:

print("wrong username or password!")

else:

print("input time is used out!")

方法2:

username="test"

password="test1234"

for i in range(3):

user_name=input("input the username:")

pass_word=input("input the password")

if user_name==user_name and pass_word==password:

print("login successfully!")

break

else:

print("wrong username or password!")

if i==2:

print("input time is used out!")

习题2:

# 自己实现一个函数,在一句话中查找某个单词的算法,

# 存在返回索引号,否则返回False

#

# 提示:使用句子中的坐标遍历句子的每一个位置,

# 使用查找单词的长度结合使用切片来查找单词。

# 例如:s[i:i+len(单词)]

sentence="I am a boy."

def find_word_index(sentence,word):

word_length = len(word)

for i in range(len(sentence)-word_length+1):

if sentence[i:i+word_length] == word:

return i

return -1

print(find_word_index(sentence,"boy"))

# 判断的标准,你找到的位置,单词开始和单词结束的位置,判断单词的开始是0或者它的前面不是字母,且结束诶之的后面不是字母或者是句子的最后一个位置、

# 方法二:判断一个完整的单词

sentence = "I am good good good boy!"

def find_word_index(sentence,word):

position_list =[]

word_length = len(word)

for i in range(len(sentence)-word_length+1):

for j in range(word_length):

if sentence[i+j] != word[j]:

break

else:

position_list.append(i)

return position_list

print(find_word_index(sentence,"good"))

# 练习题:

# 随机生成一个整数,1-100之间

# 你最多猜5次,如果猜大了,提示大了

# 小了,提示小了,

# 猜对了,提示猜中。

# 5次都没猜中,就猜没猜中。

import random

i=random.randint(1,100)

print(i)

for j in range(5):

a = int(input("input a number"))

if a==i:

print("guess it right")

print("use",j+1, "times")

break

elif a>i:

print("it is too big")

continue

elif a

print("it is too small")

continue

else:

print("input time is used out ,game over")

# 使用while,计算随机数之和,超过100的时候,停止程序。

# # 随机数1-20的范围产生,要求记录一下产生的随机数,以及

# # 最后的和,以及随机数的个数。

import random

s=[]

sum=0

while 1:

i =random.randint(0,20)

print(i)

s.append(i)

sum+=i

print(sum)

if sum>100:

break

print("一共产生了%s 个随机数"%len(s))

print(sum)

print(s)

s="asdf"

for i in range(len(s)):

print("基于长度遍历",s[i])

for j in s:

print("基于字符串遍历",j)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值