whlie循环

格式

while 结束条件:

执行语句


break 结束

if 条件:

break


小游戏案例

猜拳小游戏

import random

ren =0
ji = 0
print('-'*12 + '欢迎玩猜拳小游戏' + '-'*12)
print('本游戏实行三拳两胜制')
n = 0
while n <3:
    ran = random.randint(0,2)
    guess = int(input('请输入 剪刀(0) 石头(1) 布(2):\n'))
    if ran==0 and guess==1 or ran == 1 and guess==2 or ran ==2 and guess ==0:
        print('本轮赢了')
        ren += 1
        n+= 1
        if ren == 2:
            break
    elif guess==0 and ran==1 or guess == 1 and ran==2 or guess ==2 and ran ==0:
        print('本轮机器赢了')
        ji += 1
        n+=1
        if ji == 2:
            break
    elif guess==1 and ran==1 or guess == 2 and ran==2 or guess ==0 and ran ==0:
        print('本轮平局')

    else:print('瞎输入什么,重新输去')
    print(ren,ji)
if ren == 2:
    print('恭喜你赢了')
elif ji ==2:
    print('你输了')


猜数字小游戏

import random

print('-'*6 + '欢迎来到猜数字小游戏' + '-'*6)
num = random.randint(1,50)
print(num)
ci = 0
while True:
        cai = input('请输入要猜的数字(1-50):')
        ci += 1
        if num == int(cai):
            print('恭喜你,猜对了')
            break
        elif int(cai) > num:
             print('猜大了')
        else:print('猜小了,请重新猜')
if ci == 1:
    print('猜对了,赶紧去买彩票吧,运气爆了')
elif 2 <= ci <=5:
    print('猜对了,运气还可以')
else:
    print('猜对了,运气一般')



print('猜数字结束')

For循环

格式:

for i in range(n):

循环体中的内容


range(n):默认从零开始取值到n-1结束

range(start,stop):[start,stop)

python基础 while,for循环_ci

for i in range(1,10,2)://第三个数表示步长(增量)

1-50累加和

sum = 0
for i in range(1,51):
    n += i
    print(sum)
for ...else

for i in range(3):

循环体

else:for循环没有被打断就会进else ////while中断后else不执行,中断则执行

for i in range(3):
    name = input('用户名:')
    password = input('密码:')
    if name == 'admin' and password=='1234':
        print('登陆成功')
        break
    else:print('账户名或密码错误')
else:
    print('账号已锁定')

while与for区别

for i in range(n): ----------》肯定有固定次数的

pass

while 条件 : -----------》固定次数的循环 2.不确定次数的循环

pass

掷骰子小游戏

import random

coins = 0
count = 0
if coins < 5:
    money = int(input('请输入充值金额:'))
    while money % 10 == 0 and money > 0:
        coins += money * 2
        print('您的金币为%d' % coins)
        kaishi = input('是否开始游戏 y/n:')
        while kaishi == 'y' and coins >= 5:
            print('--------开始游戏----------')
            coins -= 5
            coins += 1
            ran1 = random.randint(1, 6)
            ran2 = random.randint(1, 6)
            cai = input('猜大小(大/小)')
            if ran1 + ran2 > 6 and cai == '大' or ran1 + ran2 <= 6 and cai == '小':
                print('恭喜你猜对了')
                coins += 2
            elif ran1 + ran2 <= 6 and cai == '大' or ran1 + ran2 > 6 and cai == '小':
                print('很遗憾,您输了')
            else:
                print('请不要胡乱输入')
            count += 1
            kaishi = input('是否继续游戏 y/n:')
        print('您一共完了%d次剩余%d金币' % (count, coins))
        break
    else:
        print('充值失败')

跳转语句continue结束

条件成立跳过本次循环下面的语句,继续下一次的循环

python基础 while,for循环_for循环_02

区别

break 跳出循环结构

continue 跳过本次循环下面的语句