当条件永远成立,就会一直执行while代码块的程序,造成死循环。
#!/usr/bin/Python
#-*-codeing:utf-8-*-
import time
while 1:
print('Hello world!', time.time())
print('done')
循环外设变量count初始值1,循环条件:count小于11,循环内判断count不等于7打印count的值。
#!/usr/bin/Python
#-*-codeing:utf-8-*-
count = 1
while count < 11:
if count != 7:
print(count)
count = count + 1
print('finish')
使用count++会报错
while循环一旦条件不成立就会结束循环,所以如需其他判断且不需要结束循环,最好在循环内部进行判断。
while循环外设变量count初始值1,累加变量sum初始值0,循环条件:count小于101,循环内部每执行一次循环重新赋值sum等于前面累加的值加上count,count的值加1。
#!/usr/bin/Python
#-*-codeing:utf-8-*-
count = 1
sum = 0
while count < 101:
sum = sum + count
count = count + 1
print(count, sum)
#101 5050
循环外设变量count初始值1,循环条件count小于101,循环内判断count对2求余不等于0输出count,count的值加1。
#!/usr/bin/Python
#-*-codeing:utf-8-*-
count = 1
while count < 101:
if count % 2 != 0:
print(count)
count = count + 1
循环外设变量count初始值1,循环条件count小于101,循环内判断count对2求余等于0,打印count,count值加1。
#!/usr/bin/Python
#-*-codeing:utf-8-*-
count = 1
while count < 101:
if count % 2 == 0:
print(count)
count = count + 1
审题,1-99的所有奇数的和,减去1-99所有偶数的和。循环外设两个变量,sum1、sum2初始值0,sum1累加1-99的所有奇数和,sum2累加1-99所有偶数的和。再设count,count初始值1,每执行一次循环,count值加1,count大于99结束循环。循环结束,sum3等于sum1减去sum2。
#!/usr/bin/Python
#-*-codeing:utf-8-*-
sum1 = 0
sum2 = 0
count = 1
while count < 100:
if count % 2 == 1:
sum1 = sum1 + count
else:
sum2 = sum2 + count
count = count + 1
sum3 = sum1 - sum2
print(sum3, sum1, sum2)
#50 2500 2450
第二种办法,循环外设变量sum初始值0、count初始值1,循环条件:count小于100,循环内判断count对2求余等于0,sum减去count,否则加上count,count的值加1。
#!/usr/bin/Python
#-*-codeing:utf-8-*-
count = 1
sum = 0
while count < 100:
if count % 2 == 0:
sum = sum - count
else:
sum = sum + count
count = count + 1
print(sum)
#50
循环外设变量count初始值0,循环条件count小于3,每执行一次循环,count加1。
#!/usr/bin/Python
#-*-codeing:utf-8-*-
count = 0
while count < 3:
input('请输入密码:')
count = count + 1
print('密码输入错误次数超过三次,请联系管理员。')
#!/usr/bin/Python
#-*-codeing:utf-8-*-
count = 0
while count < 3:
user = input('请输入用户名:')
pwd = input('请输入用户密码:')
if user == 'alex' and pwd == '123':
print('登录成功!欢迎使用!')
break
else:
print('用户名或密码错误,请重新输入!')
count = count + 1
print('end')
条件同时成立使用and