Python程序设计基础(第九章 字典和集合 练习记录)

继续之前的练习

本章介绍字典和集合数据结构,学习将数据结构存储为字典中的键值对、索引值、更改现有值、添加新键值对以及编写字典序列。接下来讨论如何将值存储为集合中的唯一元素,并执行常见的集合操作,例如并集、交集、差集和对称差集,还讨论了集合解析。最后对对象序列进行讨论,并介绍了Python pickle模块。

#1课程信息
def main():
    values=[]
    values.append(['3004','Haynes','8:00 a.m.'])
    values.append(['4951','Alvarado','9:00 a.m.'])
    values.append(['6755','Rich','10:00 a.m.'])
    values.append(['1244','Burke','11:00 a.m.'])
    values.append(['1411','Lee','1:00 p.m.'])
    dic=dict()
    dic['CS101']=values[0]
    dic['CS102']=values[1]
    dic['CS103']=values[2]
    dic['NT110']=values[3]
    dic['CM241']=values[4]
    num=input("Please enter a course number:")
    try:
        print("According information is")
        print("The teacher number is", dic[num][0])
        print("The teacher name is", dic[num][1])
        print("The time of course is", dic[num][2])
    except KeyError:
        print("The number is non-exist")
if __name__=="__main__":
    main()
#2程序首府考试
import random
def main():
    dic={'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas': 'Little rock', 'California': 'Sacramento',
         'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
         'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis',
         'Iowa': 'Des Moines', 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta',
         'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'St. Paul',
         'Mississippi': 'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada': 'Carson City',
         'New hampshire': 'Concord', 'New jersey': 'Trenton', 'New mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
         'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City', 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg',
         'Rhode island': 'Providence', 'South carolina': 'Columbia', 'South dakota': 'Pierre', 'Tennessee': 'Nashville', 'Texas': 'Austin',
         'Utah': 'Salt Lake City', 'Vermont': 'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West Virginia': 'Charleston',
         'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne', 'American Samoa': 'Pago Pago', 'Guam': 'Hagatna', 'Puerto Rico': 'San Juan',
         'Northern Marianas': 'Saipan', 'U.S. Virgin Islands': 'Charlotte Amalie'}
    problem=list(dic.keys())
    i=random.randint(0,len(problem))
    print(problem[i],'\'s state capital is ?',end='')
    answer=input()
    the_real=dic[problem[i]]
    if the_real==answer:
        print("you are right!")
    else:
        print("The answer is wrong.")
if __name__=="__main__":
    main()
#3文件加密与解密
def encode(codes,path1,path2):
    file1=open(path1,'r')
    file2=open(path2,'w')
    line1=file1.readline()
    while line1!='':
        line1=line1.strip()
        res=''
        for i in line1:
            try:
                ch=codes[i]
            except KeyError:
                ch=i
            finally:
                res+=ch
        file2.write(res+'\n')
        line1=file1.readline()
    file1.close()
    file2.close()
def decode(codes,path1):
    print("The decode result:")
    file1=open(path1,'r')
    line1=file1.readline()
    while line1!='':
        line1=line1.strip()
        res=''
        for i in line1:
            try:
                ch=codes[i]
            except KeyError:
                ch=i
            finally:
                res+=ch
        print(res)
        line1=file1.readline()
    file1.close()
def the_dictionary():
    codes=dict()
    index=33
    for i in range(65,91):
        codes[chr(i)]=chr(index)
        codes[chr(index)]=chr(i)
        index+=1
    for i in range(97,123):
        while index in codes:
            index+=1
        codes[chr(i)]=chr(index)
        codes[chr(index)]=chr(i)
        index+=1
    return codes
def main():
    codes=the_dictionary()
    encode(codes,'normal.txt','to_encode.txt')
    decode(codes,'to_encode.txt')
if __name__=="__main__":
    main()

normal.txt内容:
在这里插入图片描述
to_encode.txt内容:
在这里插入图片描述

#4唯一单词
import re
def main():
    file=open('draft.txt','r')
    dic=dict()
    line=file.readline()
    while line!='':
        line.rstrip('\n')
        word=re.split(' |,',line)
        #print(word)
        for i in word:
            if i=='':
                continue
            if i[-1]=='\n':
                i=i[:-1]
            if i[-1]=='.':
                i=i[:-1]
            i=i.lower()
            if i not in dic:
                dic[i]=1
            else:
                dic[i]+=1
        line=file.readline()
    file.close()
    ans=[]
    for i in dic:
        if dic[i]==1:
            ans.append(i)
    print("The only word in the article includes:")
    print(ans)
if __name__=="__main__":
    main()

draft.txt的内容是特朗普先生的就职演讲稿,放在最后。

draft2.txt文本内容放在最后

#5单词频率
import re
def main():
    file=open('draft.txt','r')
    line=file.readline()
    dic=dict()
    while line!='':
        line=line.strip()
        word=re.split(',| ',line)
        for i in word:
            if i=='':
                continue
            if i[-1]=='\n':
                i=i[:-1]
            if i[-1]=='.':
                i=i[:-1]
            if i not in dic:
                dic[i]=1
            else:
                dic[i]+=1
        line=file.readline()
    file.close()
    for i in dic:
        print(i," ",dic[i])
if __name__=="__main__":
    main()
#6文件分析
import re
def get_set(path):
    file=open(path,'r')
    line=file.readline()
    the_res=set()
    while line!='':
        line=line.strip()
        res_lis=re.split(',| ',line)
        for i in res_lis:
            i=i.lower()
            if i=='':
                continue
            if i[-1]=='\n':
                i=i[:-1]
            if i[-1]=='.':
                i=i[:-1]
            the_res.add(i)
        line=file.readline()
    file.close()
    return the_res
def main():
    set1=get_set('draft.txt')
    set2=get_set('draft2.txt')
    print("The only word that appears in two texts:")
    print(set1.difference(set2))
    print(set2.difference(set1))

    print('Words that appear in both texts:')
    print(set1.intersection(set2))

    print("Word that appear only in the first of second file:")
    print(set1^set2)
if __name__=="__main__":
    main()
#8姓名与电子邮箱地址
import pickle
dic=dict()
def read_inf():
    file=open('inf.dat','rb')
    global dic
    try:
        dic=pickle.load(file)
    except EOFError:
        pass
    file.close()
def save_inf():
    file=open('inf.dat','wb')
    pickle.dump(dic,file)
    file.close()
def looking():
    s=input("Please enter name you looking for:")
    if s not in dic:
        print("This person is non-exist")
    else:
        print(dic[s])
def adding():
    s=input("Please enter name:")
    s2=input("Please enter mail:")
    if s in dic:
        print("This one has existed")
    else:
        dic[s]=s2
    save_inf()
def editing():
    s=input("Please enter name:")
    if s not in dic:
        print("The name is non-exist")
    else:
        s2=input("Please enter this new mail:")
        dic[s]=s2
        save_inf()
def deleting():
    s=input("Please enter name:")
    if s not in dic:
        print("The name is non-exist")
    else:
        del dic[s]
        save_inf()
def main():
    while True:
        global dic
        if len(dic)==0:
            read_inf()
        print("******-Looking for one's mail please enter   1-******")
        print("******-Adding new name and mail please enter 2-******")
        print("******-Editing mail please enter             3-******")
        print("******-Deleting a name and mail please enter 4-******")
        print("******-Exit this system please enter         0-******")
        try:
            choice = int(input())
            if choice<0 or choice>4:
                print("You enter is wrong")
            else:
                if choice==0:
                    break
                else:
                    if choice==1:
                        looking()
                    elif choice==2:
                        adding()
                    elif choice==3:
                        editing()
                    elif choice==4:
                        deleting()
        except ValueError:
            print("You enter is wrong")
if __name__=="__main__":
   main()
#10单词索引
def main():
    file=open('Kennedy.txt','r')
    file2=open('index.txt','w')
    dic=dict()
    line1=file.readline()
    index=1
    while line1!='':
        line1=line1.strip()
        lis=line1.split(' ')
        for i in lis:
            if i in dic:
                dic[i].append(index)
            else:
                temp= [index]
                dic[i]=temp
        line1=file.readline()
        index+=1
    file.close()
    for i in dic:
        s=i+":"
        for j in dic[i]:
            s+=(' '+str(j))
        file2.write(s+'\n')
    file2.close()
if __name__=="__main__":
    main()

draft.txt:
Chief Justice Roberts, President Carter, President Clinton, President Bush, President Obama, fellow Americans and people of the world, thank you.
We, the citizens of America, are now joined in a great national effort to rebuild our country and restore its promise for all of our people. Together we will determine the course of America and the world for many, many years to come.
We will face challenges. We will confront hardships. But we will get the job done. Every four years, we gather on these steps to carry out the orderly and peaceful transfer of power.
And we are grateful to President Obama and First Lady Michelle Obama for their gracious aid throughout this transition. They have been magnificent. Thank you.
Today’s ceremony, however, has very special meaning. Because today, we are not merely transferring power from one administration to another or from one party to another.
But we are transferring power from Washington D.C. and giving it back to you, the people.
For too long, a small group in our nation’s capital has reaped the rewards of government while the people have borne the cost. Washington flourished, but the people did not share in its wealth. Politicians prospered, but the jobs left. And the factories closed.
The establishment protected itself but not the citizens of our country. Their victories have not been your victories. Their triumphs have not been your triumphs. And while they celebrated in our nation’s capital, there was little to celebrate for struggling families all across our land. That all changes starting right here and right now. Because this moment is your moment. It belongs to you.
It belongs to everyone gathered here today and everyone watching all across America. This is your day. This is your celebration. And this, the United States of America, is your country.
What truly matters is not which party controls our government but whether our government is controlled by the people. January 20th, 2017 will be remembered as the day the people became the rulers of this nation again.
The forgotten men and women of our country will be forgotten no longer.
Everyone is listening to you now. You came by the tens of millions to become part of a historic movement, the likes of which the world has never seen before.
At the center of this movement is a crucial conviction – that a nation exist to serve its citizens. Americans want great schools for their children, safe neighborhoods for their families and good jobs for themselves.
These are just and reasonable demands of righteous people and a righteous public. But for too many of our citizens, a different reality exist. Mothers and children trapped in poverty in our inner cities, rusted out factories scattered like tombstones across the landscape of our nation, an education system flushed with cash but which leaves our young and beautiful students deprived of all knowledge. And the crime, and the gangs, and the drugs that have stolen too many lives and robbed our country of so much unrealized potential. This American carnage stops right here and stops right now.
We are one nation, and their pain is our pain. Their dreams are our dreams, and their success will be our success. We share one heart, one home and one glorious destiny.
The oath of office I take today is an oath of allegiance to all Americans. For many decades, we’ve enriched foreign industry at the expense of American industry, subsidized the armies of other countries while allowing for the very sad depletion of our military.
We defended other nation’s borders while refusing to defend our own.
And spent trillions and trillions of dollars overseas while America’s infrastructure has fallen into disrepair and decay.
We’ve made other countries rich while the wealth, strength, and confidence of our country has dissipated over the horizon. One by one, the factories shuttered and left our shores with not even a thought about the millions and millions of American workers that were left behind.
The wealth of our middle class has been ripped from their homes and then redistributed all across the world.
But that is the past and now we are looking only to the future.
We assembled here today are issuing a new decree to be heard in every city, in every foreign capital and in every hall of power. From this day forward, a new vision will govern our land. From this day forward, it’s going to be only America first – America first.
Every decision on trade, on taxes, on immigration, on foreign affairs will be made to benefit American workers and American families. We must protect our borders from the ravages of other countries making our products, stealing our companies and destroying our jobs.
Protection will lead to great prosperity and strength. I will fight for you with every breath in my body. And I will never, ever let you down.
America will start winning again, winning like never before.
We will bring back our jobs. We will bring back our borders. We will bring back our wealth, and we will bring back our dreams. We will build new roads and highways and bridges and airports and tunnels and railways all across our wonderful nation. We will get our people off of welfare and back to work rebuilding our country with American hands and American labor. We will follow two simple rules – buy American and hire American.
We will seek friendship and goodwill with the nations of the world.
But we do so with the understanding that it is the right of all nations to put their own interests first. We do not seek to impose our way of life on anyone but rather to let it shine as an example. We will shine for everyone to follow.
We will reinforce old alliances and form new ones. And unite the civilized world against radical Islamic terrorism, which we will eradicate completely from the face of the earth.
At the bedrock of our politics will be a total allegiance to the United States of America and through our loyalty to our country, we will rediscover our loyalty to each other. When you open your heart to patriotism, there is no room for prejudice.
The Bible tells us how good and pleasant it is when God’s people live together in unity. We must speak our minds openly, debate our disagreement honestly but always pursue solidarity. When America is united, America is totally unstoppable.
There should be no fear. We are protected, and we will always be protected. And most importantly, We will be protected by the great men and women of our military and law enforcement. We will be protected by God.
Finally, we must think big and dream even bigger. In America, we understand that a nation is only living as long as it is striving. We will no longer accept politicians who are all talk and no action, constantly complaining but never doing anything about it.
The time for empty talk is over. Now arrives the hour of action.
Do not allow anyone to tell you that it cannot be done. No challenge can match the heart and fight and spirit of America. We will not fail. Our country will thrive and prosper again. We stand at the birth of a new millennium, ready to unlock the mysteries of space, to free the earth from the miseries of disease and to harness the energies, industries and technologies of tomorrow. A new national pride will stir ourselves, lift our sights and heal our divisions. It’s time to remember that old wisdom our soldiers will never forget – that whether we are black or brown or white, we all bleed the same red blood of patriots.
We all enjoyed the same glorious freedoms, and we all salute the same great American flag.
And whether a child is born in the urban sprawl of Detroit or the windswept plains of Nebraska, They look up at the same night sky, they build a heart with the same dreams and they are infused with the breath of life by the same Almighty Creator.
So to all Americans in every city near and far, small and large, from mountain to mountain, from ocean to ocean, hear these words – you will never be ignored again.
Your voice, your hopes and your dreams will define our American destiny. Together, And your courage and goodness and love will forever guide us along the way. We will make America strong again. We will make America wealthy again. We will make America proud again. We will make America safe again. And yes, together, thank you. we will make America great again. God bless you. And God bless America. Thank You.

draft2.txt
Thank you. Thank you very much, everyone. Sorry to keep you waiting. Complicated business, complicated. Thank you very much.
I’ve just received a call from Secretary Clinton. She congratulated us. It’s about us. On our victory, and I congratulated her and her family on a very, very hard-fought campaign.
I mean she fought very hard. Hillary has worked very long and very hard over a long period of time, and we owe her a major debt of gratitude for her service to our country.
I mean that very sincerely. Now it is time for America to bind the wounds of pision, have to get together, to all Republicans and Democrats and independents across this nation I say it is time for us to come together as one united people.
It is time. I pledge to every citizen of our land that I will be president for all of Americans, and this is so important to me. For those who have chosen not to support me in the past, of which there were a few people, I’m reaching out to you for your guidance and your help so that we can work together and unify our great country. As I’ve said from the beginning, ours was not a campaign but rather an incredible and great movement, made up of millions of hard-working men and women who love their country and want a better, brighter future for themselves and for their family.
It is a movement comprised of Americans from all races, religions, backgrounds and beliefs, who want and expect our government to serve the people, and serve the people it will.
Working together we will begin the urgent task of rebuilding our nation and renewing the American dream. I’ve spent my entire life in business, looking at the untapped potential in projects and in people all over the world.
That is now what I want to do for our country. Tremendous potential. I’ve gotten to know our country so well. Tremendous potential. It is going to be a beautiful thing. Every single American will have the opportunity to realize his or her fullest potential. The forgotten men and women of our country will be forgotten no longer.
We are going to fix our inner cities and rebuild our highways, bridges, tunnels, airports, schools, hospitals. We’re going to rebuild our infrastructure, which will become, by the way, second to none, and we will put millions of our people to work
as we rebuild it. We will also finally take care of our great veterans who have been so loyal, and I’ve gotten to know so many over this 18-month journey.
The time I’ve spent with them during this campaign has been among my greatest honors.
Our veterans are incredible people. We will embark upon a project of national growth and renewal. I will harness the creative talents of our people and we will call upon the best and brightest to leverage their tremendous talent for the benefit of all. It is going to happen. We have a great economic plan. We will double our growth and have the pest economy anywhere in the world. At the same time we will get along with all other nations, willing to get along with us. We will be. We will have great relationships. We expect to have great, great relationships. No dream is too big, no challenge is too great. Nothing we want for our future is beyond our reach.
America will no longer settle for anything less than the best. We must reclaim our country’s destiny and dream big and bold and daring. We have to do that. We’re going to dream of things for our country, and beautiful things and successful things once again.
I want to tell the world community that while we will always put America’s interests first, we will deal fairly with everyone, with everyone.
All people and all other nations. We will seek common ground, not hostility, partnership, not conflict. And now I would like to take this moment to thank some of the people who really helped me with this, what they are calling tonight a very, very historic victory.
First I want to thank my parents, who I know are looking down on me right now. Great people. I’ve learned so much from them. They were wonderful in every regard. I are truly great parents. I also want to thank my sisters, Marianne and Elizabeth who are here with us tonight. Where are they They’re here someplace. They’re very shy actually.
And my brother Robert, my great friend. Where is Robert Where is Robert My brother Robert, and they should be on this stage but that’s okay. They’re great.
And also my late brother Fred, great guy. Fantastic guy. Fantastic family. I was very lucky.
Great brothers, sisters, great, unbelievable parents. To Melania and Don and Ivanka and Eric and Tiffany and Barron, I love you and I thank you, and especially for putting up with all of those hours. This was tough.
This was tough. This political stuff is nasty and it is tough. So I want to thank my family very much. Really fantastic. Thank you all. Thank you all. Lara,
unbelievable job. Unbelievable. Vanessa, thank you. Thank you very much. What a great group.
You’ve all given me such incredible support, and I will tell you that we have a large group of people. You know, they kept saying we have a small staff. Not so small. Look at all of the people that we have. Look at all of these people.
And Kellyanne and Chris and Rudy and Steve and David. We have got tremendously talented people up here, and I want to tell you it’s been very, very special.
I want to give a very special thanks to our former mayor, Rudy Giuliani. He’s unbelievable. Unbelievable. He traveled with us and he went through meetings, and Rudy never changes. Where is Rudy. Where is he
[Chanting “Rudy”]
Gov. Chris Christie, folks, was unbelievable. Thank you, Chris. The first man, first senator, first major, major politician — let me tell you, he is highly respected in Washington because he is as smart as you get, senator Jeff sessions. Where is Jeff A great man. Another great man, very tough competitor. He was not easy. He was not easy. Who is that Is that the mayor that showed up Is that Rudy
Up here. Really a friend to me, but I’ll tell you, I got to know him as a competitor because he was one of the folks that was negotiating to go against those Democrats, Dr. Ben Carson. Where’s been Where is Ben By the way, Mike Huckabee is here someplace, and he is fantastic. Mike and his familiar bring Sarah, thank you very much. Gen. Mike Flynn. Where is Mike And Gen. Kellogg. We have over 200 generals and admirals that have endorsed our campaign and there are special people. We have 22 congressional medal of honor people. A very special person who, believe me, I read reports that I wasn’t getting along with him. I never had a bad second with him. He’s an unbelievable star. He is – that’s right, how did you possibly guess Let me tell you about Reince. I’ve said Reince. I know it. I know it. Look at all of those people over there. I know it, Reince is a superstar. I said, they can’t call you a superstar, Reince, unless we win it. Like secretariat. He would not have that bust at the track at Belmont.
Reince is really a star and he is the hardest working guy and in a certain way I did this. Reince, come up here. Get over here, Reince.
Boy, oh, boy, oh, boy. It’s about time you did this right. My god. Nah, come here. Say something.
Amazing guy. Our partnership with the RNC was so important to the success and what we’ve done, so I also have to say, I’ve gotten to know some incredible people.
The Secret Service people. They’re tough and they’re smart and they’re sharp and I don’t want to mess around with them, I can tell ya. And when I want to go and wave to a big group of people and they rip me down and put me back down in the seat, but they are fantastic people so I want to thank the Secret Service.
And law enforcement in New York City, they’re here tonight. These are spectacular people, sometimes underappreciated unfortunately, we we appreciate them. So it’s been what they call an historic event, but to be really historic, we have to do a great job and I promise you that I will not let you down. We will do a great job. We will do a great job. I look very much forward to being your president and hopefully at the end of two years or three years or four years or maybe even eight years you will say so many of you worked so hard for us, with you you will say that — you will say that that was something that you were — really were very proud to do and I can — thank you very much.
And I can only say that while the campaign is over, our work on this movement is now really just beginning. We’re going to get to work immediately for the American people and we’re going to be doing a job that hopefully you will be so proud of your president. You will be so proud. Again, it’s my honor.
It’s an amazing evening. It’s been an amazing two-year period and I love this country. Thank you.

一个查询演讲稿的网址:
https://www.haowenwang.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
内容简介 · · · · · · 本书以培养读者以计算机科学家一样的思维方式来理解Python语言编程。贯穿全书的主体是如何思考、设计、开发的方法,而具体的编程语言,只是提供了一个具体场景方便介绍的媒介。 全书共21章,详细介绍Python语言编程的方方面面。本书从基本的编程概念开始讲起,包括语言的语法和语义,而且每个编程概念都有清晰的定义,引领读者循序渐进地学习变量、表达式、语句、函数和数据结构。书中还探讨了如何处理文件和数据库,如何理解对象、方法和面向对象编程,如何使用调试技巧来修正语法错误、运行时错误和语义错误。每一章都配有术语表和练习题,方便读者巩固所学的知识和技巧。此外,每一章都抽出一节来讲解如何调试程序。作者针对每章所专注的语言特性,或者相关的开发问题,总结了调试的方方面面。 本书的第2版与第1版相比,做了很多更新,将编程语言Python 2升级成Python 3,并修改了很多示例和练习,增加了新的章节,更全面地介绍Python语言。 这是一本实用的学习指南,适合没有Python编程经验的程序员阅读,也适合高中或大学的学生、Python爱好者及需要了解编程基础的人阅读。对于首次接触程序设计的人来说,是一本不可多得的佳作。 作者简介 · · · · · · [美] 艾伦 B. 唐尼(Allen B. Downey) Allen Downey是欧林工程学院的计算机科学教授,曾任教于韦尔斯利学院、科尔比学院和加州大学伯克利分校。他是加州大学伯克利分校的计算机科学博士,并拥有MIT的硕士和学士学位。 译者介绍 赵普明 毕业清华大学计算机系,从事软件开发行业近10年。从2.3版本开始接触Python,工作中使用Python编写脚本程序,用于快速原型构建以及日志计算等日常作业;业余时,作为一个编程语言爱好者,对D、Kotlin、Lua、Clojure、Scala、Julia、Go等语言均有了解,但至今仍为Python独特的风格、简洁的设计而惊叹。 目录 · · · · · · 第1章 程序之道 1 1.1 什么是程序 1 1.2 运行Python 2 1.3 第一个程序 3 1.4 算术操作符 3 1.5 值和类型 4 1.6 形式语言和自然语言 5 1.7 调试 6 1.8 术语表 7 1.9 练习 8 第2章 变量、表达式和语句 9 2.1 赋值语句 9 2.2 变量名称 9 2.3 表达式和语句 10 2.4 脚本模式 11 2.5 操作顺序 12 2.6 字符串操作 13 2.7 注释 13 2.8 调试 14 2.9 术语表 15 2.10 练习 16 第3章 函数 17 3.1 函数调用 17 3.2 数学函数 18 3.3 组合 19 3.4 添加新函数 19 3.5 定义和使用 21 3.6 执行流程 21 3.7 形参和实参 22 3.8 变量和形参是局部的 23 3.9 栈图 23 3.10 有返回值函数和无返回值函数 24 3.11 为什么要有函数 25 3.12 调试 26 3.13 术语表 26 3.14 练习 27 第4章 案例研究:接口设计 30 4.1 turtle模块 30 4.2 简单重复 31 4.3 练习 32 4.4 封装 33 4.5 泛化 34 4.6 接口设计 34 4.7 重构 35 4.8 一个开发计划 36 4.9 文档字符串 37 4.10 调试 38 4.11 术语表 38 4.12 练习 39 第5章 条件和递归 41 5.1 向下取整除法操作符和求模操作符 41 5.2 布尔表达式 42 5.3 逻辑操作符 42 5.4 条件执行 43 5.5 选择执行 43 5.6 条件链 44 5.7 嵌套条件 44 5.8 递归 45 5.9 递归函数的栈图 46 5.10 无限递归 47 5.11 键盘输入 47 5.12 调试 48 5.13 术语表 49 5.14 练习 50 第6章 有返回值的函数 53 6.1 返回值 53 6.2 增量开发 54 6.3 组合 56 6.4 布尔函数 57 6.5 再谈递归 58 6.6 坚持信念 59 6.7 另一个示例 60 6.8 检查类型 60 6.9 调试 61 6.10 术语表 63 6.11 练习 63 第7章 迭代 65 7.1 重新赋值 65 7.2 更新变量 66 7.3 while语句 66 7.4 break语句 68 7.5 平方根 68 7.6 算法 70 7.7 调试 70 7.8 术语表 71 7.9 练习 71 第8章 字符串 73 8.1 字符串是一个序列 73 8.2 len 74 8.3 使用for循环进行遍历 74 8.4 字符串切片 75 8.5 字符串是不可变的 76 8.6 搜索 77 8.7 循环和计数 77 8.8 字符串方法 78 8.9 操作符in 79 8.10 字符串比较 79 8.11 调试 80 8.12 术语表 82 8.13 练习 82 第9章 案例分析:文字游戏 85 9.1 读取单词列表 85 9.2 练习 86 9.3 搜索 87 9.4 使用下标循环 88 9.5 调试 90 9.6 术语表 90 9.7 练习 91 第10章 列表 93 10.1 列表是一个序列 93 10.2 列表是可变的 94 10.3 遍历一个列表 95 10.4 列表操作 95 10.5 列表切片 96 10.6 列表方法 96 10.7 映射、过滤和化简 97 10.8 删除元素 98 10.9 列表和字符串 99 10.10 对象和值 100 10.11 别名 101 10.12 列表参数 102 10.13 调试 103 10.14 术语表 104 10.15 练习 105 第11章 字典 108 11.1 字典是一种映射 108 11.2 使用字典作为计数器集合 110 11.3 循环和字典 111 11.4 反向查找 111 11.5 字典和列表 112 11.6 备忘 114 11.7 全局变量 115 11.8 调试 117 11.9 术语表 118 11.10 练习 119 第12章 元组 121 12.1 元组是不可变的 121 12.2 元组赋值 122 12.3 作为返回值的元组 123 12.4 可变长参数元组 124 12.5 列表和元组 124 12.6 字典和元组 126 12.7 序列的序列 127 12.8 调试 128 12.9 术语表 129 12.10 练习 129 第13章 案例研究:选择数据结构 132 13.1 单词频率分析 132 13.2 随机数 133 13.3 单词直方图 134 13.4 最常用的单词 135 13.5 可选形参 136 13.6 字典减法 137 13.7 随机单词 138 13.8 马尔可夫分析 138 13.9 数据结构 140 13.10 调试 141 13.11 术语表 142 13.12 练习 143 第14章 文件 144 14.1 持久化 144 14.2 读和写 144 14.3 格式操作符 145 14.4 文件名和路径 146 14.5 捕获异常 147 14.6 数据库 148 14.7 封存 149 14.8 管道 150 14.9 编写模块 151 14.10 调试 152 14.11 术语表 152 14.12 练习 153 第15章 类和对象 155 15.1 用户定义类型 155 15.2 属性 156 15.3 矩形 157 15.4 作为返回值的实例 158 15.5 对象是可变的 159 15.6 复制 159 15.7 调试 161 15.8 术语表 161 15.9 练习 162 第16章 类和函数 163 16.1 时间 163 16.2 纯函数 164 16.3 修改器 165 16.4 原型和计划 166 16.5 调试 167 16.6 术语表 168 16.7 练习 168 第17章 类和方法 170 17.1 面向对象特性 170 17.2 打印对象 171 17.3 另一个示例 172 17.4 一个更复杂的示例 173 17.5 init方法 173 17.6 _ _str_ _方法 174 17.7 操作符重载 175 17.8 基于类型的分发 175 17.9 多态 177 17.10 接口和实现 177 17.11 调试 178 17.12 术语表 179 17.13 练习 179 第18章 继承 181 18.1 卡片对象 181 18.2 类属性 182 18.3 对比卡牌 183 18.4 牌组 184 18.5 打印牌组 185 18.6 添加、删除、洗牌和排序 185 18.7 继承 186 18.8 类图 188 18.9 数据封装 189 18.10 调试 190 18.11 术语表 191 18.12 练习 191 第19章 Python拾珍 194 19.1 条件表达式 194 19.2 列表理解 195 19.3 生成器表达式 196 19.4 any和all 197 19.5 集合 197 19.6 计数器 199 19.7 defaultdict 200 19.8 命名元组 201 19.9 收集关键词参数 202 19.10 术语表 203 19.11 练习 203 第20章 调试 205 20.1 语法错误 205 20.2 运行时错误 207 20.2.1 我的程序什么都不做 207 20.2.2 我的程序卡死了 207 20.2.3 无限循环 208 20.2.4 无限递归 208 20.2.5 执行流程 208 20.2.6 当我运行程序,会得到一个异常 209 20.2.7 我添加了太多print语句,被输出淹没了 210 20.3 语义错误 210 20.3.1 我的程序运行不正确 211 20.3.2 我有一个巨大而复杂的表达式,而它和我预料的不同 211 20.3.3 我有一个函数,返回值和预期不同 212 20.3.4 我真的真的卡住了,我需要帮助 212 20.3.5 不行,我真的需要帮助 212 第21章 算法分析 214 21.1 增长量级 215 21.2 Python基本操作的分析 217 21.3 搜索算法的分析 218 21.4 散列表 219 21.5 术语表 223 译后记 224
### 回答1: 非常感谢您的提问。Python语言程序设计基础程序练习题是一系列针对Python编程语言基础练习题,旨在帮助初学者掌握Python编程语言的基本语法和编程技巧。这些练习题涵盖了Python编程的各个方面,包括变量、数据类型、条件语句、循环语句、函数、模块等等。通过完成这些练习题,学习者可以逐步提高自己的编程能力,掌握Python编程的基本技能,为以后深入学习Python编程打下坚实的基础。 ### 回答2: Python语言是一种简洁且灵活的脚本语言,已经成为许多计算机科学领域的首选语言Python语言有着丰富的标准库和第三方库,这些库能够轻松地完成各种任务,使得Python语言非常适合学习和使用。 Python语言程序设计基础程序练习题可以帮助初学者提高他们的Python编程技能。下面介绍几个简单的Python程序练习,帮助初学者快速上手,提高Python编程技能。 1. 编写一个程序,求1到100之间的所有偶数之和。 解题思路:使用for循环进行遍历,求出所有偶数的和。 ```python sum = 0 for i in range(2, 101, 2): sum += i print("1到100之间的所有偶数之和 =", sum) ``` 2. 编写一个程序,计算任意两个数字之间的和。 解题思路:输入两个数字,使用循环将它们之间的所有数字加起来。 ```python num1 = int(input("请输入第一个数字:")) num2 = int(input("请输入第二个数字:")) sum = 0 for i in range(num1, num2+1): sum += i print(num1, "到", num2, "之间所有数字之和 =", sum) ``` 3. 编写一个程序,计算任意两个数字之间的乘积。 解题思路:输入两个数字,使用循环将它们之间的所有数字相乘。 ```python num1 = int(input("请输入第一个数字:")) num2 = int(input("请输入第二个数字:")) product = 1 for i in range(num1, num2+1): product *= i print(num1, "到", num2, "之间所有数字的乘积 =", product) ``` 4. 编写一个程序,判断一个数是否为质数。 解题思路:如果一个数只能被1和它本身整除,那么这个数就是质数。 ```python num = int(input("请输入一个数字:")) if num < 2: print(num, "不是质数") else: for i in range(2, num): if num % i == 0: print(num, "不是质数") break else: print(num, "是质数") ``` 5. 编写一个程序,将一个字符串倒序输出。 解题思路:使用字符串切片[::-1]即可实现字符串倒序输出。 ```python str = input("请输入一个字符串:") print("倒序输出字符串 =", str[::-1]) ``` 以上是几个简单的Python程序练习,通过这些练习可以提高初学者的Python编程水平。随着学习的深入,可以逐渐挑战更难的Python编程练习,掌握更多的Python编程技能。 ### 回答3: Python语言程序设计是一门非常有用的编程语言,而程序练习题则是Python语言程序设计中非常重要的一步。通过对基础程序练习题的学习和实践,可以帮助学生更好地掌握Python语言基础知识和编程方法。 在Python语言基础程序练习题中,最基本的要求就是理解Python语言的基本语法和编程方法。这包括变量定义、数据类型、运算符、控制语句和函数等。此外,还需要了解Python语言中的一些库和模块,例如math库、random库、sys库和os库等。 在练习题中,我们需要编写一些简单的Python程序来解决特定问题。这可以包括编写程序来计算一些数学问题,比如计算圆的周长和面积、计算正弦函数值等等。我们还可以编写一些程序来处理字符串问题,比如字符串的拼接、截取和格式化输出等。 除了理论知识外,实践也是非常重要的。在练习中,学生需要根据问题的要求,选择正确的编程语句和方法来编写一个可以正确运行的程序。学生还需要学会调试程序和解决遇到的错误和问题。 总的来说,基础程序练习题是Python语言程序设计学习的一部分,它对于学生掌握Python语言基础知识和编程技巧具有重要作用。通过练习和实践,学生可以更好地理解Python语言的编程方法和应用,在未来的学习和工作中,也能更加游刃有余地应用Python语言进行编程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值