系统学习 python 的第三天(python while 循环 猜拳游戏 九九乘法表)

2021-01-21 11:12:56 浏览数 (1)

参考链接: Python while循环

真的脑子越学越乱,得好好抽出一个时间来好好地理理思路和学习的内容,还好这个笔记比较好弄 弄完预习预习 好好整理一下脑子  猜拳游戏 if 循环 

import random

computer = random.randint(1, 3)

player = int(input("请输入您的状态代号,石头请输:1、剪子请输:2、布请输:3: "))

if ((player == 1) and (computer == 2)) or ((player == 2) and (computer == 3)) or ((player == 3)

and (computer == 1)):

    print("你赢了")

elif (player == computer):

    print("平局")

else:

    print("你输了")

while–循环 

import random

while True:

    computer = random.randint(1, 3)

    player = int(input("请输入您的状态代号,石头请输:1、剪子请输:2、布请输:3: "))

    if ((player == 1) and (computer == 2)) or ((player == 2) and (computer == 3)) or ((player == 3)

    and (computer == 1)):

    print("你赢了")

    elif (player == computer):

        print("平局")

    elif((player == 1) and (computer == 3)) or ((player == 2) and (computer == 1)) or ((player == 3)

    and (computer == 2)):

        print("你输了")

    else:

        print("请输入数字1或2或3,您输入的 %d 不正确" % player)

break:用来中断循环 

continue: 用来跳出本次循环,直接开始下一次循环。 在使用关键字之前,需要确认循环的计数是否修改, 否则可能会导致死循环 

while 循环嵌套 i = 1 while i < 3: 

    # 被嵌套的循环

    j = 1

    while j < 5:

        print(f'{i} --- {j}')

        # break

        continue

        j = 1

    i = 1

打印:  * ** *** **** ***** 

第一种方法

# while 循环

# i = 1

# while i <= 5:

#     print("*" * i)

#     i =1

# while 嵌套循环

# i = 1

# while i <= 5:

#     j = 1

#     while j <= i:

#         print("*", end = "")

#         j = 1

#     print()

#     i = 1

打印: :* * * * * :* * * * * :* * * * * :* * * * * :* * * * * 

i = 1

# while i <= 5:

#     j = 1

#     while j <= 5:

#         print("*", end = "")

#         j = 1

#     print()

#     i = 1

九九乘法表 

i = 1

while i <= 9:

    j = 1

    while j <= i:

        print("%d * %d = %-3d " % (j,i,j * i), end = " ")

        j = 1

    print()

    i = 1

for-in 循环使用方式 

def test_func1():

#得到字符串中的所有字符

for c in 'abcdefg':

    # 将小写字母变成大写输出

    print(c.upper())

test_func1()

for-in 循环如果需要计数,需要配合 range() 实现 range 有两个参数,参数一是起始值 ,参数二是终止值 得到一个数字区间,是一个左闭右开区间, [start, end) 如果只给一个参数,那么默认是终止值 ,起始值默认是 0 

def test_func2():

    for i in range(10, 20):

        print(i)

test_func2()

def test_func3():

    # 如果需 要计数,但又不需 要用到这个数字时,可以没有循环变量

    for _ in range(5):

        print('hello', _)

test_func3()

0 人点赞