EduCoder实践课程——Python程序设计入门答案

记:由于疫情暂时返不了校,然后学校大四毕业年级布置了在线实训的任务,我选择了实践课程Python程序设计入门。以前没有学过,但是感觉Python挺好入门的,把自己学习过程中的代码记录下来,一是为了自己写报告方便,二来大家可以作为参考代码,如果有更好的代码可以留言,大家相互学习。

1、Python初体验

    第1关:Hello Python,我来了!

# coding=utf-8

# 请在此处添加代码完成输出“Hello Python”,注意要区分大小写!
########## Begin ##########
print("Hello Python")
########## End ##########

2、 Python 入门之字符串处理

    第1关:字符串的拼接:名字的组成

# coding=utf-8

# 存放姓氏和名字的变量
first_name = input()
last_name = input()

# 请在下面添加字符串拼接的代码,完成相应功能
########## Begin ##########
full_name=first_name+" "+last_name
print(full_name)

########## End ##########

    第2关:字符转换

# coding=utf-8

# 获取待处理的源字符串
source_string = input()

# 请在下面添加字符串转换的代码
########## Begin ##########
source_string1=source_string.strip()
transform_string=source_string1.title()
print(transform_string)
lenth=len(transform_string)
print(lenth)
########## End ##########

    第3关:字符串查找与替换

# coding = utf-8
source_string = input()

# 请在下面添加代码
########## Begin ##########
print(source_string.find('day'))
new_string=source_string.replace('day','time')
print(new_string)
new_string2=new_string.split(' ')
print(new_string2)
########## End ##########

3、Python 入门之玩转列表

    第1关:列表元素的增删改:客人名单的变化

# coding=utf-8

# 创建并初始化Guests列表
guests = []
while True:
    try:
        guest = input()
        guests.append(guest)
    except:
        break

    
# 请在此添加代码,对guests列表进行插入、删除等操作
########## Begin ##########
lenth=len(guests)
deleted_guest=guests.pop()
print(deleted_guest)
guests.insert(2,deleted_guest)
guests.pop(1)
print(guests)
########## End ##########

    第2关:列表元素的排序:给客人排序

# coding=utf-8

# 创建并初始化`source_list`列表
source_list = []
while True:
    try:
        list_element = input()
        source_list.append(list_element)
    except:
        break
    
# 请在此添加代码,对source_list列表进行排序等操作并打印输出排序后的列表
########## Begin ##########
source_list.sort(reverse=False)
print(source_list)

########## End ##########

    第3关:数值列表:用数字说话

# coding=utf-8

# 创建并读入range函数的相应参数
lower = int(input())
upper = int(input())
step = int(input())

# 请在此添加代码,实现编程要求
########## Begin ##########
sourse_list=list(range(lower,upper,step))
lenth=len(sourse_list)
print(lenth)
min_value=min(sourse_list)
max_value=max(sourse_list)
print(max_value-min_value)
########## End ##########

    第4关:列表切片:你的菜单和我的菜单

# coding=utf-8

# 创建并初始化my_menu列表
my_menu = []
while True:
    try:
        food = input()
        my_menu.append(food)
    except:
        break

# 请在此添加代码,对my_menu列表进行切片操作
########## Begin ##########
lenth=len(my_menu)
list_slice=my_menu[:lenth:3]
print(list_slice)
list_slice2=my_menu[-3:]
print(list_slice2)
########## End ##########

4、 Python 入门之元组与字典

    第1关:元组的使用:这份菜单能修改吗?

# coding=utf-8

# 创建并初始化menu_list列表
menu_list = []
while True:
    try:
        food = input()
        menu_list.append(food)
    except:
        break

# 请在此添加代码,对menu_list进行元组转换以及元组计算等操作,并打印输出元组及元组最大的元素
###### Begin ######
print(tuple(menu_list))
print(max(menu_list))
#######  End #######

    第2关:字典的使用:这份菜单可以修改

# coding=utf-8

# 创建并初始化menu_dict字典
menu_dict = {}
while True:
    try:
        food = input()
        price = int(input())
        menu_dict[food]= price
    except:
        break

# 请在此添加代码,实现对menu_dict的添加、查找、修改等操作,并打印输出相应的值
########## Begin ##########
menu_dict['lamb']=50;
print(menu_dict['fish'])
menu_dict['fish']=100
del menu_dict['noodles']
print(menu_dict)
########## End ##########

    第3关:字典的遍历:菜名和价格的展示

# coding=utf-8

# 创建并初始化menu_dict字典
menu_dict = {}
while True:
    try:
        food = input()
        price = int(input())
        menu_dict[food]= price
    except:
        break

# 请在此添加代码,实现对menu_dict的遍历操作并打印输出键与值
########## Begin ##########
for key in menu_dict.keys():
    print(key)
for value in menu_dict.values():
    print(value)
########## End ##########

    第4关:嵌套 - 菜单的信息量好大

# coding=utf-8

# 初始化menu1字典,输入两道菜的价格
menu1 = {}
menu1['fish']=int(input())
menu1['pork']=int(input())

# menu_total列表现在只包含menu1字典
menu_total = [menu1]

# 请在此添加代码,实现编程要求
########## Begin ##########
menu2={}
menu2['fish']=menu1['fish']*2
menu2['pork']=menu1['pork']*2
menu_total=[menu1,menu2]
########## End ##########

# 输出menu_total列表
print(menu_total)

5、Python 入门之运算符的使用

    第1关:算术、比较、赋值运算符

# 定义theOperation方法,包括apple和pear两个参数,分别表示苹果和梨子的数量
def theOperation(apple,pear):
    # 请在此处填入计算苹果个数加梨的个数的代码,并将结果存入sum_result变量
    ########## Begin ##########
    sum_result=apple+pear
    ########## End ##########
    print(sum_result)

    # 请在此处填入苹果个数除以梨的个数的代码,并将结果存入div_result变量
    ########## Begin ##########
    div_result=apple/pear
    ########## End ##########
    print(div_result)
    
    # 请在此处填入苹果个数的2次幂的代码,并将结果存入exp_result变量
    ########## Begin ##########
    exp_result=apple**2
    ########## End ##########
    print(exp_result)
    
    # 请在此处填入判断苹果个数是否与梨的个数相等的代码,并将结果存入isequal变量
    ########## Begin ##########
    isequal=(apple==pear)
    ########## End ##########
    print(isequal)
    
    # 请在此处填入判断苹果个数是否大于等于梨的个数的代码,并将结果存入ismax变量
    ########## Begin ##########
    ismax=(apple>=pear)
    ########## End ##########
    print(ismax)
    
    # 请在此处填入用赋值乘法运算符计算梨个数乘以2的代码,并将结果存入multi_result变量
    ########## Begin ##########
    multi_result=pear*2
    ########## End ##########
    print(multi_result)

    第2关:逻辑运算符

# 定义逻辑运算处理函数theLogic,其中tom与Jerry分别代表两个输入参数
def theLogic(tom,jerry):

    # 请在此处填入jerry的布尔“非”代码,并将结果存入到not_result这个变量
    ########## Begin ##########
    not_result=not jerry
    ########## End ##########
    print(not_result)

    # 请在此处填入tom,jerry的逻辑与代码,并将结果存入到and_result这个变量
    ########## Begin ##########
    and_result=tom and jerry
    ########## End ##########
    print(and_result)

    第3关:位运算符

# 定义位运算处理函数bit, 其中bitone和bittwo两个参数为需要进行位运算的变量,由测试程序读入。
def bit(bitone,bittwo):
    # 请在此处填入将bitone,bittwo按位与的代码,并将运算结果存入result变量
    ########## Begin ##########
    result=bitone & bittwo
    ########## End ##########
    print(result)
    # 请在此处填入将bitone,bittwo按位或的代码,并将运算结果存入result变量
    ########## Begin ##########
    result=bitone | bittwo
    ########## End ##########
    print(result)
    # 请在此处填入将bitone,bittwo按位异或的代码,并将运算结果存入result变量
    ########## Begin ##########
    result=bitone ^ bittwo
    ########## End ##########
    print(result)
    # 请在此处填入将bitone按位取反的代码,并将运算结果存入result变量
    ########## Begin ##########
    result=(~bitone)
    ########## End ##########
    print(result)
    # 请在此处填入将bittwo左移动两位的代码,并将运算结果存入result变量
    ########## Begin ##########
    result=(bittwo<<2)
    ########## End ##########
    print(result)
    # 请在此处填入将bittwo右移动两位的代码,并将运算结果存入result变量
    ########## Begin ##########
    result=(bittwo>>2)
    ########## End ##########
    print(result)

    第4关:成员运算符

# 定义成员片段函数member,参数me为待判断的人名,member_list为成员名单
def member(me,member_list = []):
    # 请在if后面的括号中填入判断变量me是否存在于list中的语句
    ########## Begin ##########
    if( me in member_list):
        print("我是篮球社成员")
    else:
        print("我不是篮球社成员")
    ########## End ##########
    
    
    # 请在if后面的括号中填入判断变量me是否存在于list中的语句
    ########## Begin ##########
    if(me not in member_list):
        print("我不是篮球社成员")
    else:
        print("我是篮球社成员")
   ########## End ##########

    第5关:身份运算符

# 定义addressone和addresstwo两个变量,并为其赋值
addressone = 20
addresstwo = 20
addressthree = 12

# 在if后面的括号中填入判断变量addressone与变量addresstwo是否有相同的存储单元的语句
########## Begin ##########
if(addressone is addresstwo):
    print("变量addressone与变量addresstwo有相同的存储单元")
else:
    print("变量addressone与变量addresstwo的存储单元不同")
########## End ##########


# 在if后面的括号中填入判断变量addresstwo与变量addressthree是否没有相同的存储单元的语句
########## Begin ##########
if(addresstwo is not addressthree):
       print("变量addresstwo与变量addressthree的存储单元不同")
else:
       print("变量addresstwo与变量addressthree有相同的存储单元")
########## End ##########

第6关:运算符的优先级

# 定义并实现优先级运算函数theProirity
def thePriority(var1,var2,var3,var4):
    # 先将var1左移两位,然后计算var1与var2的和,最后后将这个值乘以var3,并将最终结果存入result变量
    ########## Begin ##########
    result=((var1<<2)+var2)*var3
    ########## End ##########
    print(result)
    # 先将var1与var2按位与,然后计算得到的值与var3的和,最后后将这个值乘以var4,并将最终结果存入result变量
    ########## Begin ##########
    result=((var1 & var2)+var3)*var4
    ########## End ##########
    print(result)

6、 Python 入门之控制结构 - 顺序与选择结构

    第1关:顺序结构

changeOne = int(input())
changeTwo = int(input())
plus = int(input())

# 请在此添加代码,交换changeOne、changeTwo的值,然后计算changeOne、plus的和result的值
########## Begin ##########
temp=changeOne
changeOne=changeTwo
changeTwo=temp
result=changeOne+plus
########## End ##########
print(result)

    第2关:选择结构:if-else

workYear = int(input())
# 请在下面填入如果workYear < 5的判断语句
########## Begin ##########
if(workYear<5):
########## End ##########
    print("工资涨幅为0")
# 请在下面填入如果workYear >= 5 and workYear < 10的判断语句
########## Begin ##########
elif(workYear>=5 and workYear<10):
########## End ##########
    print("工资涨幅为5%")
# 请在下面填入如果workYear >= 10 and workYear < 15的判断语句
########## Begin ##########
elif(workYear>=10 and workYear<15):
########## End ##########
    print("工资涨幅为10%")
# 请在下面填入当上述条件判断都为假时的判断语句
########## Begin ##########
else:
########## End ##########
    print("工资涨幅为15%")

第3关:选择结构 : 三元操作符

jimscore = int(input())
jerryscore = int(input())
# 请在此添加代码,判断若jim的得分jimscore更高,则赢家为jim,若jerry的得分jerryscore更高,则赢家为jerry,并输出赢家的名字
########## Begin ##########
winner=('jim' if jimscore>jerryscore else 'jerry')
########## End ##########
print(winner)

7、Python 入门之控制结构 - 循环结构

    第1关:While 循环与 break 语句

partcount = int(input())
electric = int(input())
count = 0
#请在此添加代码,当count < partcount时的while循环判断语句
#********** Begin *********#
while(count<partcount):
#********** End **********#
    count += 1
    print("已加工零件个数:",count)
    if(electric):
        print("停电了,停止加工")
        #请在此添加代码,填入break语句
        #********** Begin *********#
        break
        #********** End **********#

    第2关:for 循环与 continue 语句

absencenum = int(input())
studentname = []
inputlist = input()
for i in inputlist.split(','):
   result = i
   studentname.append(result)
count = 0
#请在此添加代码,填入循环遍历studentname列表的代码
#********** Begin *********#
for student in studentname:
#********** End **********#
    count += 1
    if(count == absencenum):
        #在下面填入continue语句
        #********** Begin *********#
        continue
        #********** End **********#
    print(student,"的试卷已阅")

    第3关:循环嵌套

studentnum = int(input())
#请在此添加代码,填入for循环遍历学生人数的代码
#********** Begin *********#
for student in range(0,studentnum):
#********** End **********#
    sum = 0
    subjectscore = []
    inputlist = input()
    for i in inputlist.split(','):
        result = i
        subjectscore.append(result)
    #请在此添加代码,填入for循环遍历学生分数的代码
    #********** Begin *********#
    for score in subjectscore:
    #********** End **********#
        score = int(score)
        sum = sum + score
    print("第%d位同学的总分为:%d" %(student,sum))

    第4关:迭代器

List = []
member = input()
for i in member.split(','):
    result = i
    List.append(result)
#请在此添加代码,将List转换为迭代器的代码
#********** Begin *********#
IterList=iter(List)
#********** End **********#
while True:
    try:
        #请在此添加代码,用next()函数遍历IterList的代码
        #********** Begin *********#
        num=next(IterList)
        #********** End **********#
        result = int(num) * 2
        print(result)
    except StopIteration:
        break

8、Python 入门之函数结构

    第1关:函数的参数 - 搭建函数房子的砖

# coding=utf-8

# 创建一个空列表numbers
numbers = []

# str用来存储输入的数字字符串,lst1是将输入的字符串用空格分割,存储为列表
str = input()
lst1 = str.split(' ')

# 将输入的数字字符串转换为整型并赋值给numbers列表
for i in range(len(lst1)):
   numbers.append(int(lst1.pop()))

# 请在此添加代码,对输入的列表中的数值元素进行累加求和
########## Begin ##########
def s(*numbers):
    add=0
    for i in numbers:
        add+=i
    return (add)
d=s(*numbers)
########## End ##########

print(d)

    第2关:函数的返回值 - 可有可无的 return

# coding=utf-8

# 输入两个正整数a,b
a = int(input())
b = int(input())

# 请在此添加代码,求两个正整数的最大公约数
########## Begin ##########
def gcd(a,b):
    if(b==0):
        return a
    else:
        return(gcd(b,a%b))
########## End ##########
# 调用函数,并输出最大公约数
print(gcd(a,b))

第3关:函数的使用范围:Python 作用域

# coding=utf-8

# 输入两个正整数a,b
a = int(input())
b = int(input())

# 请在此添加代码,求两个正整数的最小公倍数
########## Begin ##########
def gcd(a,b):
    if(b==0):
        return a
    else:
        return(gcd(b,a%b))

def lcm(a,b):
    temp=gcd(a,b)
    return int(a*b/temp)
########## End ##########

# 调用函数,并输出a,b的最小公倍数
print(lcm(a,b))

9、 Python 入门之类的基础语法

    第1关:类的声明与定义

# 请在下面填入定义Book类的代码
########## Begin ##########
class Book(object):
########## End ##########
    '书籍类'
    def __init__(self,name,author,data,version):
        self.name = name
        self.author = author
        self.data = data
        self.version = version

    def sell(self,bookName,price):
        print("%s的销售价格为%d" %(bookName,price))

    第2关:类的属性与实例化

class People:
    # 请在下面填入声明两个变量名分别为name和country的字符串变量的代码
    ########## Begin ##########

    ########## End ##########
    def introduce(self,name,country):
        self.name = name
        self.country = country
        print("%s来自%s" %(name,country))
name = input()
country = input()
# 请在下面填入对类People进行实例化的代码,对象为p
########## Begin ##########
p=People()
########## End ##########
p.introduce(name,country)

    第3关:绑定与方法调用

import fractionSumtest

# 请在下面填入创建fractionSum的实例fs的代码
########## Begin ##########
fs=fractionSumtest.fractionSum()
########## End ##########
n = int(input())
if n % 2 == 0:
    # 请在下面填入调用fractionSumtest类中dcall方法的代码,计算当n为偶数时计算的和
    ########## Begin ##########
    sum=fs.dcall(fs.peven,n)
    ########## End ##########
else:
    # 请在下面填入调用fractionSumtest类中dcall方法的代码,计算当n为奇数时计算的和
    ########## Begin ##########
    sum=fs.dcall(fs.podd,n)
    ########## End ##########
print(sum)

    第4关:静态方法与类方法

class BookSell:
    static_var = 100
    def sell(self,name,author,version,price):
        print("%s的销售价格为%d" %(name,int(price)))
    # 请在下面填入函数修饰符将printStatic()方法声明为静态方法
    ########## Begin ##########
    @staticmethod
    ########## End ##########
    def printStatic():
        print(BookSell.static_var)
    # 请在下面填入函数修饰符将printVersion(cls)方法声明为类方法
    ########## Begin ##########
    @classmethod
    ########## End ##########
    def printVersion(cls):
        print(cls)

    第5关:类的导入

# 从 DataChangetest 模块中导入 DataChange 类,并使用该类中的 eightToten(self,p) 方法,实现将输入的八进制转换成十进制输出。
########## Begin ##########
import DataChangetest
obj=DataChangetest.DataChange()
n=input()
obj.eightToten(n)
########## End ##########

10、Python 入门之类的继承

    第1关:初识继承

import animalstest
# 请在下面填入定义fish类的代码,fish类继承自animals类
########## Begin ##########
class fish(animalstest.animals):
########## End ##########
    def __init__(self,name):
        self.name = name
    def swim(self):
        print("%s会游泳" %self.name)

# 请在下面填入定义leopard类的代码,leopard类继承自animals类
########## Begin ##########
class leopard(animalstest.animals):
########## End ##########
    def __init__(self,name):
        self.name = name
    def climb(self):
        print("%s会爬树" %self.name)

fName = input()
lName = input()
f = fish(fName)
f.breath()
f.swim()
f.foraging()
l = leopard(lName)
l.breath()
l.run()
l.foraging()

    第2关:覆盖方法

class Point:
    def __init__(self,x,y,z,h):
        self.x = x
        self.y = y
        self.z = z
        self.h = h
    def getPoint(self):
        return self.x,self.y,self.z,self.h
class Line(Point):
    # 请在下面填入覆盖父类getPoint()方法的代码,并在这个方法中分别得出x - y与z - h结果的绝对值
    ########## Begin ##########
    def getPoint(self):
        length_one=abs(self.x-self.y)
        length_two=abs(self.z-self.h)
    ########## End ##########
        print(length_one,length_two)

    第3关:从标准类派生

class ChangeAbs(int):
    def __new__(cls, val):
        # 填入使用super()内建函数去捕获对应父类以调用它的__new__()方法来计算输入数值的绝对值的代码
        # 求一个数的绝对值的函数为abs()
        # 返回最后的结果
        ########## Begin ##########
        return super(ChangeAbs,cls).__new__(cls,abs(val))
        ########## End ##########

class SortedKeyDict(dict):
    def keys(self):
        # 填入使用super()内建函数去捕获对应父类使输入字典自动排序的代码
        # 返回最后的结果
        ########## Begin ##########
        return sorted(super(SortedKeyDict,self).keys())
        ########## End ##########

    第4关:多重继承

class A(object):
    def test(self):
        print("this is A.test()")
class B(object):
    def test(self):
        print("this is B.test()")
    def check(self):
        print("this is B.check()")
# 请在下面填入定义类C的代码
########## Begin ##########
class C(A,B):
########## End ##########
    pass
# 请在下面填入定义类D的代码
########## Begin ##########
class D(A,B):
########## End ##########
    def check(self):
        print("this is D.check()")
class E(C,D):
    pass

11、 Python 入门之类的其它特性

    第1关:类的内建函数

import specialmethodtest
sc = specialmethodtest.subClass()
# 请在下面填入判断subClass是否为parentClass的子类的代码,并输出结果
########## Begin ##########
print(issubclass(specialmethodtest.subClass,specialmethodtest.parentClass))
########## End ##########
# 请在下面填入判断sc是否为subClass实例的代码,并输出结果
########## Begin ##########
print(isinstance(sc,specialmethodtest.subClass))
########## End ##########
# 请在下面填入判断实例sc是否包含一个属性为name的代码,并输出结果
########## Begin ##########
print(hasattr(sc,'name'))
########## End ##########
# 请在下面填入将sc的属性name的值设置为subclass的代码
########## Begin ##########
setattr(sc,'name','subclass')
########## End ##########
# 请在下面填入获取sc的属性name的值的代码,并输出结果
########## Begin ##########
print(getattr(sc,'name'))
########## End ##########
# 请在下面填入调用subClass的父类的tell()方法的代码
########## Begin ##########
specialmethodtest.parentClass.tell(sc)
########## End ##########

    第2关:类的私有化

import Bagtest
price = int(input())
bag = Bagtest.Bag(price)
# 请在下面填入输出Bag类中变量__price的代码
########## Begin ##########
print(bag._Bag__price)
########## End ##########
# 请在下面填入输出Bag类中变量_price的代码
########## Begin ##########
print(bag._price)
########## End ##########

    第3关:授权

class WrapClass(object):
    def __init__(self,obj):
        self.__obj = obj
    def get(self):
        return self.__obj
    def __repr__(self):
        return 'self.__obj'
    def __str__(self):
        return str(self.__obj)
    # 请在下面填入重写__getattr__()实现授权的代码
    ########## Begin ##########
    def __getattr__(self,thelist):
        return getattr(self.__obj,thelist)
    ########## End ##########
thelist = []
inputlist = input()
for i in inputlist.split(','):
    result = i
    thelist.append(result)
# 请在下面填入实例化类,并通过对象调用thelist,并输出thelist第三个元素的代码
########## Begin ##########
temp=WrapClass(thelist)
temp_list=temp.get()
print(temp_list[2])
########## End ##########

    第4关:对象的销毁

import delObjecttest
# 请在下面声明类delObject的实例,并将其引用赋给其它别名,然后调用del方法将其销毁
########## Begin ##########
temp=delObjecttest.delObject()
temp2=temp
del(temp)
########## End ##########

全部代码更新完毕~

原创文章 54 获赞 99 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_38938670/article/details/105777501
今日推荐