您的位置:首页 > 编程语言 > Python开发

think python学习心得-(5)迭代与字符串的使用

2016-03-26 18:40 525 查看
for while return break等语句,用法同C语言很像。

m=5.0
def sqr(a):
x=a
y=(x+m/x)/2
if abs(y-x)<0.00001:
print y
else:
sqr(y)

def sq(a):
x=a
y=(x+m/x)/2
flag= abs(y-x)
if flag < 0.00001:
return y
else:
sqr(y)
sq(m)


练习题7-3

import math
def sqr(a):
x=a
y=(x+m/x)/2
if abs(y-x)<0.00001:
print y
return y
else:
sqr(y)

def sq(a):
x=a
y=(x+m/x)/2
flag= abs(y-x)
if flag < 0.00001:
return y
else:
sqr(y)

for i in range(9):
j=float(i+1)
m=j
print j,math.sqrt(j),sq(j)
练习题7-4

import math
def eval_loop():
while True:
line = raw_input('>')
if line == 'done':
break
print eval(line)
eval_loop()
print 'Done!'
eval_loop()
练习题7-5

略。

8.字符串

练习8-1

word='fruit'
length=len(word)
for i in range(length):
print word[length-i-1]


练习8-2

prefixs='JKLMNP'
suffix = 'ack'

for letter in prefixs:
print letter+suffix


练习8-3

表示fruit中的全体字符

练习8-4

def find(word,letter,i):
index = i
while index < len(word):
if word[index]==letter:
return index
index = index+1
return -1
print find('Hellowordthisiszhangchangle!','s',2)
练习8-5

def count(word,letter):
count1 = 0
length = len(word)
for i in range (length):
if word[i] == letter:
count1=count1+1
return count1
print ('Please input a world and a letter to be counted')
word1=raw_input('>')
letter1=raw_input('>>')
print count(word1,letter1)


练习8-7

word='banana'
index=word.count('a')
print index
练习8-9
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: