python基础语法_4_while_else_while

#while_else语句
# while 条件表达式:
#     代码块(循环体)
# else:
#     代码块
# else什么时候执行,注意:如果循环体正常结束的,则结束之后,会执行esle分支
# 如果循环体是不正常结束的,是通过break语句来结束的,则不会执行esle分支
# '''
# 
# '''
# while_while循环的嵌套使用:
# 结构:while 条件表达式1:
#         条件1成立需要执行的代码
#         while 条件表达式2:
#             条件2成立需要执行的代码

案例1:
# 行:row;列:column
# 打印如下图案:
# *
# **
# ***
# ****
# *****
row=1
while row<=5:
    col=1
    while col<=row:
        print('*',end='')
        col+=1
    print('')
    row += 1

案例2:输出2~100之间的素数:
i = 2
while (i < 100):
    j = 2
    while (j <= (i / j)):
        if not (i % j):
            break
        j = j + 1
    if (j > i / j):
        print(i, " 是素数")
    i = i + 1

案例3:
count=1
while (count<5):
    print(count,'小于5')
    count+=1
else:
    print(count,'不小于5')

案例4:打印100以内的偶数的和
count=1
sum=0
while(count<=101):
    if count%2==0:
        sum+=count #sum=sum+count
    count+=1
print('1-100偶数的和是:%d'%sum)

案例5:打印100以内3和5的倍数
count=1
list3=[]
list5=[]
while(count<=101):
    if count%3==0:
        # print(count,'是3的倍数')
        list3.append(count)
    if count%5==0:
        # print(count,'是5的倍数')
        list5.append(count)
    count+=1
print('1-100中3的倍数有:',list3)
print('1-100中5的倍数有:',list5)

案例6:石头剪刀布
# -*- coding:utf-8 -*-
# 实现剪刀石头布
# 随机数生成、input、print、if、elif、while
import random  #引入模块
if __name__ == "__main__":
#定义菜单
    print("欢迎来到我的世界!!!")
    print("1.开始游戏")
    print("2.退出游戏")
    # 获取用户从控制台输入的信息
    option = input("请输入你的选项:")
    while True:
        if option == "1":
            player = input("请出招:1、剪刀;2、石头;3、布;\n")                      #input返回结果是string类型
            computer = random.randint(1,3)                                        #返回的数据类型是int    转换类型 str()
            print('电脑出:%d' % computer)
            computer = str(computer)                                              #将int类型转换为string类型
            if player == computer:
                print("【平手】")
            elif player == "1" and computer == "2":
                print("【你输了】")
            elif player == "1" and computer == "3":
                print("【你赢了】")
            elif player == "2" and computer == "1":
                print("【你赢了】")
            elif player == "2" and computer == "3":
                print("【你输了】")
            elif player == "3" and computer == "1":
                print("【你输了】")
            elif player == "3" and computer == "2":
                print("【你赢了】")
            print("还想继续交手吗?离开请敲*")
            if player == "*":
                break
        else:
            break
            print("退出游戏!!!")

你可能感兴趣的:(python基础语法_4_while_else_while)