当前位置:   article > 正文

python语法学习三——循环_for i in range len(s)

for i in range len(s)

while循环

  1. #语法
  2. while expression:
  3. suite_to_repeat
  4. #代码
  5. >>> sum=0
  6. >>> j=1
  7. >>> while(j<10):
  8. sum+=j
  9. j+=1
  10. >>> sum
  11. 45
  12. >>> j
  13. 10

for循环

  1. #语法
  2. for iter_var in iterable_object:
  3. suit_to_repeat
  4. >>> for i in range(3,11,2):
  5. print(i,end='')
  6. 3579
  7. >>> s='pyrhon'
  8. >>> for c in s:#遍历序列迭代
  9. print(c,end=' ')
  10. p y r h o n
  11. >>> for i in range(len(s)):#索引每一个元素迭代
  12. print(s[i],end=' ')
  13. p y r h o n

迭代过滤器

  1. >>> x=iter(range(3,11,2))
  2. >>> next(x)
  3. 3
  4. >>> next(x)
  5. 5
  6. >>> next(x)
  7. 7
  8. >>> next(x)
  9. 9
  10. >>> next(x)
  11. Traceback (most recent call last):
  12. File "<pyshell#28>", line 1, in <module>
  13. next(x)
  14. StopIteration
  15. #判断是否为可迭代对象
  16. >>> isinstance(range(10),Iterator)
  17. False
  18. >>> isinstance(iter (range(10)),Iterator)
  19. True

猜数字游戏

  1. #猜五次
  2. from random import randint
  3. x=randint(0,300)
  4. for count in range(5):
  5. digit=int(input('one:'))
  6. if digit==x:
  7. print('bingo')
  8. else:
  9. if digit>x:
  10. print ('too large')
  11. else:
  12. print ('too small')

辗转相除法

  1. x=eval(input('1='))
  2. y=eval(input('2='))
  3. if x<y:
  4. x,y=y,x
  5. while x%y!=0:
  6. r=x%y
  7. x=y
  8. y=r
  9. print('result=',y)

 一元人民币兑换成一分、两分、五分的个数

  1. i,j,k=0,0,0
  2. count=0
  3. for i in range(21):
  4. for j in range(51):
  5. k=100-5*i-2*j
  6. if k>=0:
  7. count+=1
  8. print(count)

break语句

  1. #判断是素数
  2. from math import sqrt
  3. j=2
  4. while j<=100:
  5. i=2
  6. k=sqrt(j)
  7. while i<=k:
  8. if j%i==0:break
  9. i=i+1
  10. if i>k:
  11. print(j,end=' ')
  12. j+=1

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/145146
推荐阅读
相关标签
  

闽ICP备14008679号