Day_02-Python的循环结构

循环结构

应用场景

  如果在程序中我们需要重复的执行某条或某些指令,例如用程序控制机器人踢足球,如果机器人持球而且还没有进入射门范围,那么我们就要一直发出让机器人向球门方向奔跑的指令。当然你可能已经注意到了,刚才的描述中其实不仅仅有需要重复的动作,还有我们上一个章节讲到的分支结构。再举一个简单的例子,比如在我们的程序中要实现每隔1秒中在屏幕上打印一个"hello, world"这样的字符串并持续一个小时,我们肯定不能够将print('hello, world')这句代码写上3600遍,如果真的需要这样做那么编程的工作就太无聊了。因此,我们需要了解一下循环结构,有了循环结构我们就可以轻松的控制某件事或者某些事重复、重复、再重复的发生。在Python中构造循环结构有两种做法,一种是for-in循环,一种是while循环。

for-in循环

练习:

1.

# for循环 while用于死循环
import time
sum_ = 0
s = time.time()
for i in range(10000000):
sum_ *= i
e = time.time()
print(e - s)
 
# for i in range(1,101,2):
# print(i)

# 银行卡密码
# pwd = '123456'
# user_pwd = input('请输入密码:')
# count = 0
# for i in range(5):
# count += 1
# if user_pwd == pwd:
# print('Login!')
# break
# elif count <= 2:
# print('Error')
# user_pwd = input('请输入密码:')
# else:
# print('锁定')
# break
 
 
# 验证码
# import numpy as np
# import random
# computer1 = ''
# for i in range(4):
# computer = random.choice('abcdefghijklmnopqrstuvwxyz')
# computer1 += computer
# print(computer1,end='')
# user_check = input('请输入验证码:')
# if user_check == computer1:
# print('验证成功')
# else:
# print('验证失败')

# 验证码2
# import random
# computer1 = ''
# for i in range(4):
# computer = random.choice('abcdefghijklmnopqrstuvwxyz1234567890')
# computer1 += computer
# print(computer1,end='')
# for j in range(3):
# user_check = input('请输入验证码:')
# if user_check == computer1:
# print('验证成功')
# break
# else:
# print('验证失败')

# 密码爆破 爆破一个6位数的银行卡密码

# 银行卡密码 while
# pwd = '123456'
# user_pwd = input('请输入密码:')
# i = 0
# while i <= 1:
# i += 1
# if user_pwd == pwd:
# print('Login')
# break
# else:
# print('Error,重新输入')
# user_pwd = input('请输入密码:')

# 验证码 while
# import random
# computer1 = ''
# i = 0
# while i <= 3:
# i += 1
# computer = random.choice('abcdefghijklmnopqrstuvwxyz1234657890')
# computer1 += computer
# print(computer1,end='')
# user_check = input('请输入验证码:')
# if user_check == computer1:
# print('验证成功')
# else:
# print('验证失败')

# 阶乘
# m = float(input('m = '))
# n = float(input('n = '))
# mn = m - n
# fm = 1
# while m != 1:
# fm *= m
# m -= 1
# fn = 1
# while n != 1:
# fn *= n
# n -= 1
# fmn = 1
# while mn != 1:
# fmn *= mn
# mn -= 1
# print(fm // fn // fmn)

# 函数
# def defineName([params]):
# ........
# ........
# return..
# 带参函数
# def Print(name):
# print('%s say:hello'%name)
# Print('zqq')

# m = int(input('m = '))
# n = int(input('n = '))
# fm = 1
# for num in range(1, m + 1):
# fm *= num
# fn = 1
# for num in range(1, n + 1):
# fn *= num
# fmn = 1
# for num in range(1, m - n + 1):
# fmn *= num
# print(fm // fn // fmn)
posted @ 2019-08-02 08:52  KAJIA1  阅读(222)  评论(0编辑  收藏  举报