可以使用random模块中的choice函数来实现从文本文件中随机抽取一个学生的功能。具体代码如下:

import random

def pick_student(): with open('student.txt', 'r') as f: students = f.read().split() return random.choice(students)

keep_picking = True while keep_picking: print(pick_student()) answer = input('Do you want to keep picking? (y/n): ') if answer.lower() != 'y': keep_picking = False

在主程序中,我们首先定义了一个pick_student函数,它打开student.txt文件,读取其中的学生学号,并使用random.choice函数从中随机抽取一个学生,最后返回学生的学号。然后我们使用一个while循环来不断进行抽取学生的操作,每次调用pick_student函数并打印结果。然后询问用户是否要继续抽取,如果用户输入了'n',则将keep_picking变量设为False,退出循环

用python有一个文本文件studenttxt其中包含了学生的学号格式如下。154772 154778 154784 154793 156273 …假设现在老师要随机点几位学生回答问题。编写一个函数每次调用从中抽取一位学生。在主程序中对其连续调用并可以控制是否需要继续抽取。假设每次抽取的学生可以重复

原文地址: https://www.cveoy.top/t/topic/ecJJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录