while statement
while [break][continue]
Exit break the current cycle
continue to exit the current cycle, and re-cycle.
Execute statement may be a single statement or a block. Determination condition can be any expression, in any non-zero value, or a non-empty (null) are true.
When the determination condition false false, the cycle ends.
while 判断条件:
执行语句……
# 1~100的数相加
count = 1
val = 0
while count <= 100:
val = val + count
count = count + 1
print(val)
# 1-2+3-4+5-6```-100的算法
val = 0
count = 1
while count <= 100:
val_1 = count % 2 # val_1 这个变量是为了比较奇偶数,同时也给val_1赋值为1.
if val_1 == 1:
val = val + count #所以这里不用val_1 + count,而用val
else:
val = val - count
count = count + 1
print(val)
# ### 练习题 ###
''' 1. 猜数字,设定一个理想数字比如:66,
让用户输入数字,如果比66大,则显示猜测的结果大了;
如果比66小,则显示猜测的结果小了;
只有等于66,显示猜测结果正确,然后退出循环。
给用户三次猜测机会,
如果三次之内猜测对了,则显示猜测正确,退出循环,
如果三次之内没有猜测正确,则自动退出循环,并显示‘大笨蛋’
'''
value = 66
count = 1
content = """欢迎来到猜数字游戏
你有三次机会哟"""
print(content)
while count <= 3:
val = input('请输入你猜的数字:')
val = int(val)
if val < value:
print('你猜的数字小了。')
elif val > value:
print('你猜大了')
elif val == value:
print('恭喜你猜对了')
break
else:
print("请输入纯数字")
count += 1
if count > 3:
print('大笨蛋')
# 用户登录(三次重试机会)
username = '张三'
password = '123456'
count = 1
count_1 = 3
while count <= 4:
user = input('请输入用户名:')
pass_word = input('请输入密码:')
content = '''用户名或密码错误!
请重新登陆,你还有%s次机会''' %(count_1,)
if user == username and pass_word == password:
print('登陆成功!')
break
elif count == 4 :
print("您无法登陆请1000天后重试!")
else:
print(content)
count += 1
count_1 -= 1
- The use of format characters% s, (content = '' 'user name or password wrong!
Please login again, you have the opportunity to% s' ''% (count_1,) and finally must be added ","