猜拳游戏

import random #随机数库

while True:
    punches = ['石头','剪刀','布'] #用列表封装石头剪刀布
    computer_choice = random.choice(punches) #电脑出拳使用random.choice()来随机选择
    user_choice = '' 
    user_choice = input('使出 (剪刀! 石头! 布!)')  # 请用户输入选择
    while user_choice not in punches:  # 当用户输入错误,提示错误,重新输入
        print('输入有误,请重新出拳')
        user_choice = input()

    #过程
    print() #空行
    print('—————出拳过程—————') 
    print('电脑使出:' + computer_choice)
    print('你使出:' + user_choice)
 
    #结果
    print() #空行
    print('—————谁输谁赢?—————') 
    if user_choice == computer_choice:  # 使用if进行条件判断
        print('平局!') 
    elif (user_choice == '石头' and computer_choice == '剪刀') or (user_choice == '剪刀' and computer_choice == '布')or (user_choice == '布' and computer_choice == '石头'):
        print('你赢了!') 
    else:
        print('你输了!')

    print() #空行
    a1 = input('开始下一局游戏请按任意键,退出请安n!') 
    if a1 == 'n':
        print('【GaemOver!】') 
        break 

运行结果

210915课堂代码(猜拳&分组 练习)_条件判断

分组

现有10名学生,分三个组,要求随机分配到各组中

'''
FilePath: \PythonProject\GroupExample.py
Author: Liu Xingyu
Date: 2021-09-15
Version: 1.0
Contact: 18423475135@163.com
Descripttion注释/说明: 
现有10名学生,分三个组,要求随机分配到各组中
'''
import random

list_stu = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]  # 定义一个学生名单列表

# 通过随机数函数将列表打乱排序
random.shuffle(list_stu)

# 定义三个组
group = 3

# 分成gruop组
m = int(len(list_stu)/group)

# 每组成员
list_fz = []

# 创建分组列表
for i in range(1, len(list_stu), m):
    list_fz.append(list_stu[i:i+m])
    
print("分组列表为:", list_fz)
    
for i in range(len(list_fz)):
    print("第%d组名单:" % (i+1), end=" ")
    for stu in list_fz[i]:
        print(stu, end=" ")
    print()

运行结果

210915课堂代码(猜拳&分组 练习)_python_02

分组(方法2)

这次限定了条件,每组至少三个人

'''
FilePath: \PythonProject\GroupExample.py
Author: Liu Xingyu
Date: 2021-09-15
Version: 1.0
Contact: 18423475135@163.com
Descripttion注释/说明: 
现有10名学生,分三个组,要求随机分配到各组中
'''
import random

list_stu = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]  # 定义一个学生名单列表

# 通过随机数函数将列表打乱排序
random.shuffle(list_stu)

# 定义三个组
group = 3

# 分成gruop组
m = int(len(list_stu)/group)

# 每组成员
list_fz = []

# 创建分组列表
for i in range(1, len(list_stu), m):
    list_fz.append(list_stu[i:i+m])
    
print("分组列表为:", list_fz)
    
for i in range(len(list_fz)):
    print("第%d组名单:" % (i+1), end=" ")
    for stu in list_fz[i]:
        print(stu, end=" ")
    print()

运行结果

210915课堂代码(猜拳&分组 练习)_封装_03

分组(方法3)

group=[[],[],[]]
names=["a","b","c","d","e","f","g","h","i","j"]
for name in names:
    index=random.randint(0,2)  #0,1,2
    group[index].append(name)

i=1
for group in group:
    print("第%d组的人数为%d"%(i,len(group)))
    i=i+1
    for name in group:
        print("%s"%name,end="\t")
    print("\n")

运行结果

210915课堂代码(猜拳&分组 练习)_随机数_04

其他方法

import random

a=["1","2","3","4","5","6","7","8","9","10"]
random.shuffle(a)
print("分组情况:"+str(a[:3])+str(a[3:6])+str(a[6:]))
print("第一组:"+str(a[:3]))
print("第二组:"+str(a[3:6]))
print("第三组:"+str(a[6:]))

210915课堂代码(猜拳&分组 练习)_条件判断_05