python----“死”循环
如何编写
在代码中写下这一串:while True:(while 1: 也是可以的)
有什么作用
让某种东西一直保持这样的状态。
如何应用
可以一直打印数n,然后n加上一,并保存在n里。 (注意要提前赋值)
n = 0
while True:
print(n)
n += 1
输出
0
1
2
3
4
5
6
7
… …
他是永远这样下去吗
当然不是。有一种方法可以让他停止下来,他就是break。
break在什么时候应用
比如模拟QQ:
test = 'niu'
password = '1024'
while True:
t = input('输入账号:')
p = input('输入密码:') #input命令是交互功能,可以将你输入的值存到变量里(它的值是str类型)。
if t == test and p == password:
print('hello,niu')
break
输入&输出:
输入账号:niuniu
输入密码:1024
输入账号:niu
输入密码:1024
hello,niu
小结
今天我们知道了python“死”循环-----while True,并用它打印出了不断增加的自然数,还知道了他的“克星”-----break,他会打破循环,让程序继续往下执行。