while语句怎么用pythonpython习题,关于while循环的练习
题⽬1:⽤while循环,输出1,2,3,4,5,6,8,9,10的数字!
实例1
# ⽅法⼀
i = 1
while i <= 10:
if i != 7:
print(i, end='-')
i += 1
print()
# ⽅法⼆
i = 1
while i <= 10:
if i == 7:
i += 1
continue
print(i, end='-')
i += 1
# 运⾏结果
# 1-2-3-4-5-6-8-9-10-
# 1-2-3-4-5-6-8-9-10-
题⽬2:⽤while循环,输出1⾄100的和!
实例2
i = 1
s = 0
while i <= 100:
s += i
i += 1
print('1-100的和是:%d' % s)
# 1-100的和是:5050
题⽬3:⽤while循环,输出1⾄100的所有偶数!
实例3
# ⽅法⼀
i = 1
while i <= 100:
if i % 2 == 0:
print(i, end='-')
i += 1
print()
# ⽅法⼆
i = 1
while i <= 100:
if i % 2 != 1:
print(i, end='-')
i += 1
print()
# ⽅法三
i = 1
while i <= 100:
if not i % 2:
print(i, end='-')
i += 1
# 运⾏结果
# 2-4-6-8-10-12-14-16-18-20-22-24-26-28-30-32-34-36-38-40-42-44-46-48-50-52-54-56-58-60-62-64-66-68-70-72-74-76-78-80-82-84-86-88-90-92-94-96-98-100-# 2-4-6-8-10-12-14-16-18-20-22-24-26-28-30-32-34-36-38-40-42-44-46-48-50-52-54-56-58-60-62-64-66-68-70-72-74-76-78-80-82-84-86-88-90-9
2-94-96-98-100-# 2-4-6-8-10-12-14-16-18-20-22-24-26-28-30-32-34-36-38-40-42-44-46-48-50-52-54-56-58-60-62-64-66-68-70-72-74-76-78-80-82-84-86-88-90-92-94-96-98-100-题⽬4:⽤while循环,输出1⾄100的所有奇数!
实例4
# ⽅法⼀
i = 1
while i <= 100:
if i % 2 == 1:
print(i, end='-')
i += 1
print()
# ⽅法⼆
i = 1
while i <= 100:
if i % 2 != 0:
print(i, end='-')
i += 1
print()
# ⽅法三
i = 1
while i <= 100:
if i % 2:
print(i, end='-')
i += 1
# 运⾏结果
# 1-3-5-7-9-11-13-15-17-19-21-23-25-27-29-31-33-35-37-39-41-43-45-47-49-51-53-55-57-59-61-63-65-67-69-71-73-75-77-79-81-83-85-87-89-91-93-95-97-99-# 1-3-5-7-9-11-13-15-17-19-21-23-25-27-29-31-33-35-37-39-41-43-45-47-49-51-53-55-57-59-61-63-65-67-69-71-73-75-77-79-81-83-85-87-89-91-93-95-97-99-# 1-3-5-7-9-11-13-15-17-19-21-23-25-27-29-31-33-35-37-39-41-43-45-47-49-51-53-55-57-59-61-63-65-67-69-71-73-75-77-79-81-83-85-87-89-91-93-95-97-99-题⽬5:求1-2+99的所有数的和!
实例5
i = 1
s = 0
while i <= 99:
if i % 2 == 0:
s -= i
else:
s += i
i += 1
print('1-2+99的和为:%d' % s)
# 1-2+99的和为:50
题⽬6:while循环写⽤户登录界⾯错误提⽰次数(合计3次)
实例6
count = 1
while count <= 3:
username = input('账号:')
password = input('密码:')
if username == 'admin' and password == '123456':
print('登录成功!')
break
else:
print('⽤户名或密码出错,剩余%d次机会' % (3 - count))
count += 1
# 运⾏登录成功结果:
# 账号:admin
# 密码:123456
# 登录成功!
# 运⾏登录错误的结果
# 账号:adfds
# 密码:15122
# ⽤户名或密码出错,剩余2次机会
# 账号:admin
# 密码:45124
# ⽤户名或密码出错,剩余1次机会
# 账号:dfaffd
# 密码:123456
# ⽤户名或密码出错,剩余0次机会
题⽬7:while循环写猜⼤⼩游戏,只有3次猜⼤⼩机会
实例7
count = 0
while count < 3:
num = int(input('输⼊的数字:'))
if num == 66:
print('恭喜你猜对了')
break
elif num < 66:
print('猜⼩了')
else:
print('猜⼤了')
count += 1
else:
print('下次加油噢!')
# 运⾏猜错结果
# 输⼊的数字:50 # 猜⼩了
# 输⼊的数字:70 # 猜⼤了
# 输⼊的数字:65 # 猜⼩了
# 下次加油噢!# 运⾏猜对结果# 输⼊的数字:66 # 恭喜你猜对了
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论