0%

python基础52道题

习题1

文件名:ex1.py

1
2
3
4
5
6
7
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay!Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'

你应该看到的结果:

# 习题2:注释和井号 ## 文件名:ex2.py
1
2
3
4
5
6
# A comment, this is so you can ead your program later.
# Anything after the # is ignore by python.
print "I could have code like this."
# and the comment after is ignore
# you can also use a comment to disable" or comment out a piece of code:
print "This will run."
## 你应该看到的结果:

习题3:数字和数学计算

文件名:ex3.py

  • “+” 加号
  • “-“ 减号
  • “/“ 斜杠
  • “*” 星号
  • “%” 百分号
  • “<” 小于号
  • “>” 大于号
  • “<=” 小于等于号
  • “>=” 大于等于号
1
2
3
4
5
6
7
8
9
10
11
12
13
print "I will noew count my chickens:"
print "Hans", 25+30/6
print "Roosters", 100-25*3%4
print "Now I will count the eggs:"
print 3+2+1-5+4%2-1/4+6
print "Is it true that 3+2<5-7?"
print 3+2<5-7
print "What is 3+2?", 3+2
print "what is 5-7?", 5-7
print "How about some more."
print "Is it greater?", 5>-2
print "Is it greater or equal?",5>=-2
print "Is it less or equal?", 5<=-2

你应该看到的结果:

习题4:变量(variable)和命名

文件名:ex4.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#-*- coding:utf-8 -*-
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
#有100辆车可用
print "There are ", cars, " cars available."
#仅有30名驾驶员
print "There are only ", drivers, "drivers available."
#今天将有70辆车没有驾驶员
print "There will be", cars_not_driven, "empty cars tody."
#今天可以运送120人
print "We can transport", carpool_capacity, "people today."
print "We have",passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."

你应该看到的结果:

习题5:更多的变量和打印

文件名:ex5.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'blue'
my_teeth = 'White'
my_hair = 'Brown'

print "Let's talk about %s."% my_name
print "He's %d inches tall."% my_height
print "He's %d pounds heavy."% my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair."%(my_eyes,my_hair)
print "His teeth are usually %s depending no the coffee." %my_teeth
# this line is tricky, try to get it exactly right
print "if I add %d,%d,and %d I get %d."%(my_age, my_height, my_weight, my_age+my_height+my_weight)

你应该看到的结果:

习题6:字符串(string)和文本

文件名:ex6.py

1
2
3
4
5
6
7
8
9
10
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary,do_not)

print x
print y

print "I said:%r." % x
print "I also said:'%s'." % y

你应该看到的结果:

习题7:更多打印

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
print "Mary had a little lamb."
print "Its fleece was white as %s." % 'snow'
print "And everywhere that Mary went."
print "." * 10 # what'd that do?

end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that comma at the end. try removing it to see what happens
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 + end12

你应该看到的结果:

习题8:打印,打印

文件名:ex8.py

1
2
3
4
5
6
7
formatter = "%r %r %r %r"

print formatter % (1, 2, 3, 4)
print formatter % ("one","two","three","four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % ("I had this thing.", "That you could type up right.", "But it didn't sing.", "So I said goodnight.")

你应该看到的结果:

习题9:打印,打印,打印

文件名:ex9.py

1
2
3
4
5
6
7
8
9
10
11
12
13
# Here's some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"

print "Here are the days:", days
print "Here are the months:", months

print """
There's something foning on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""

你应该看到的结果:

习题10:那是什么?

文件名:ex10.py

  • “\n”:在该位置上放入一个新行字符
  • “\“:打印出一个反斜杠
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."

fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""

print tabby_cat
print persian_cat
print backslash_cat
print fat_cat

你应该看到的结果:

习题11:提问

文件名:ex11.py

1
2
3
4
5
6
7
8
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weight?",
weight = raw_input()

print "So, you're %r old, %r tall and %r heavy." % (age,height,weight)

注意到在每行print后面加了一个逗号?这样的话print就不会输出新行符而结束这一行跑到下一行去了。

你应该看到的结果:

习题12:提示别人

文件名:ex12.ppy

1
2
3
4
5
age = raw_input("How old are you?")
height = raw_input("How tall are you?")
weight = raw_input("How much do you weigh?")

print "So, you're %r old, %r tall and %r heavy." % (age,height,weight)

你应该看到的结果:

习题13:参数、解包、变量

文件名:ex13.py

在这个练习中我们讲到另外一种将变量传递给脚本的方法,我们现在要做的就是写一个可以接受参数的脚本

1
2
3
4
5
6
7
8
from sys import argv

script, first, second, third = argv

print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third

‘argv’是所谓的参数变量,这个变量包含了你传递给Python的参数。第3行将argv解包,与其将所有参数放到同一个变量下面,我们将每个参数赋予一个变量名:script, frist, second以及third,这也许看上去有些奇怪,不过解包可能是最好的描述方式了。包的含义很简单:“就是把argv中的东西解包,将所有的参数依次赋予左边的变量名”。
我们把导入(import)进来的功能叫做模组。你将看到类似这样的说法:“你需要把sys模组import进来。”也有人将它们称作“库(libraries)”

你应该看到的结果:

用下面的方法运行你的程序(注意你必须传递3个参数)

1
python ex13.py first 2nd 3rd

习题14:提示和传递

文件名:ex14.py

让我们使用argv和raw_input一起来向用户提一些特别的问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from sys import argv

script, user_name = argv

prompt = '>'

print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)

print "Where do you live %s?" % user_name
lives = raw_input(prompt)

print "What kind of computer do you have?"
computer = raw_input(prompt)

print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)

你应该看到的结果:

用下面的方法运行你的程序

1
python ex14.py Zed

习题15:读取文件

文件名:ex15.py

这节练习涉及到写两个文件。一个正常的ex15.py,另外一个是ex15_sample.txt,第二个文件并不是脚本,而是供你的脚本讯取的文本文件。以下是后者的内容:

我们要做的就是把该文件用我们的脚本“打开(open)”,然后打印出来。然而把文件名ex15_sample.txt写死(hardcode)在代码中不是一个好主意,这些信息应该是用户输入的才对。如果我们碰到其他文件要处理,写死的文件名就会给你带来麻烦了。我们的解决方案是使用argv和raw_input来从用户获取信息,从而知道哪些文件该被处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
from sys import argv

script,filename = argv
txt = open(filename)

print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input(">")

txt_again = open(file_again)

print txt_again.read()

你应该看到的结果:

用下面的方法运行你的程序

1
python ex15.py ex15_sample.txt

习题16:读写文件

文件名: ex16.py

  • close - 关闭文件。跟你用编辑器的文件–>保存一个意思
  • read - 读取文件内容。你可以把结果赋给一个变量
  • readline - 读取文本文件中的一行
  • truncate - 清空文件,请小心使用该命令
  • write(stuff) - 将stuff写入文件

write需要接收一个字符串作为参数,从而将该字符串写入文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C(^C)."
print "If you do want that, hit RETURN."

raw_input("?")
print "Opening the file..."
target = open(filename,'w')

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1:")
line2 = raw_input("line 2:")
line3 = raw_input("line 3:")

print "I'm going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print "And finally, we close it."
target.close()

用下面的方法运行你的程序

1
python ex16.py ex15_sample.txt

习题17:更多文件操作

文件名:ex17.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file,to_file)

# we could do these two on one line too, how?
input = open(from_file)
indata = input.read()

print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

output = open(to_file,'w')
output.write(indata)
print "Alright, all done."

output.close()
input.close()

用下面的方法运行你的程序

1
python ex17.py ex15_sample.txt ex17_sample.txt

习题18:命名、变量、代码、函数

文件名:ex18.py

函数可以做三样事情:

  1. 它们给代码片段命名,就跟“变量”给字符串和数字命名一样。
  2. 它们可以接受参数,就跟你的脚本接受argv一样
  3. 通过#1和#2,它们可以让你创建“微型脚本”或者“小命令”

你可以使用def新建函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# this one is like your scripts with argv

def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1,arg2)

# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)

# this just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1

# this one takes on arguments
def print_none():
print "I got nothin."

print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
  1. 首先我们告诉Python创建一个函数,我们使用到的命令是def,也就是“定义(define)”的意思。
  2. 紧接着def的是函数的名称。本例中它的名称是“print_two”,但名字可以随便取。
  3. 然后告诉函数我们需要*args(asterisk args),这和脚本argv非常相似,参数必须放在圆括号()中才能正常工作
  4. 接着用冒号:结束本行,然后开始下一行缩进
  5. 冒号以下,使用4个空格缩进的行都是属于print_two这个函数的内容。其中第一行的作用是将参数解包,这和脚本参数解包的原理差不多。
  6. 为了演示它的工作原理,我们把解包后的每个参数都打印出来,这和我们在这前脚本练习中所作的类似

用下面的方法运行你的程序

习题19:函数和变量

文件名:ex19.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"

print "We can just give the function numbers directly:"
cheese_and_crackers(20,30)

print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese, amount_of_crackers)

print "We can even do math inside too:"
cheese_and_crackers(10+20,5+6)

print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)

用下面的方法运行你的程序

习题20:函数和文件

文件名:ex20.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from sys import argv

script, input_file = argv

def print_all(f):
print f.read()

def rewind(f):
f.seek(0)

def print_a_line(line_count, f):
print line_count, f.readline()

current_file = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"

current_line =1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)

用下面的方法运行你的程序

1
python ex20.py test.txt

习题21:函数可以返回东西

文件名:ex21.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def add(a,b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a,b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a,b)
return a * b
def divide(a,b):
print "DIVIDING %d / %d" % (a,b)
return a/b

print "Let's do some math with just functions!"
age = add(30,5)
height = subtract(78,4)
weight = multiply(90,2)
iq = divide(100,2)

print "Age:%d, Height:%d, Weight:%d, IQ:%d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
what = add(age,subtract(height,multiply(weight,divide(iq,2))))
print "That becomes:", what, "Can you do it by hand?"

用下面的方法运行你的程序

习题24:更多练习

文件名:ex24.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""

print "--------------"
print poem
print "--------------"

five = 10 - 2 + 3 - 6
print "This should be five:%s" % five

def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars /100
return jelly_beans, jars, crates

start_point = 10000
beans, jars, crates = secret_formula(start_point)

print "With a starting point of:%d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)

start_point = start_point / 10

print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)

用下面的方法运行你的程序

习题25:更多更多的练习

文件名:ex25.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words

def sort_words(words):
"""Sorts the words."""
return sorted(words)

def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word

def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word

def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(setence)
return sort_words(words)

def print_first_and_last(sentence):
"""Prints the first and last words of the sentenct."""
words = break_words(sentenct)
print_first_word(words)
print_last_word(words)

def print_first_and_last_sorted(sentenct):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)

习题27:记住逻辑关系

文件名:ex27.py

  • and
  • or
  • not
  • != 不等于
  • == 等于
  • >= 大于等于
  • <= 小于等于
  • True
  • False

习题29:如果if

文件名:ex29.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs +=5
if people >= dogs:
print "People are greater than or equal to dogs."
if people <= dogs:
print "People are less than or equal to dags."
if people == dogs:
print "People are dogs."

习题30:Else 和 if

文件名:ex30.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
people = 30
cars = 40
buses = 15

if cars > people:
print "We should take the cars."
elif cars > people:
print "We should not take the cars."
else:
print "We can't decide."

if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."

if people > buses:
print "Alright, let's just take the buses."
else:
print "Fine, let's stay home then."

习题31:作出决定

文件名:ex31.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
print "You enter a dark room with two doors. Do you go through door #1 or door #2? "
door = raw_input("> ")
if door == "1":
print "There's a giant bear here eating a cheese cake. What do you do?"
print "1. Take the cake."
print "2. Scream at the bear."
bear = raw_input("> ")
if bear == "1":
print "The bear eats your face off. Good job!"
elif bear == "2":
print "The bear eats your legs off. Good job!"
else:
print "Well, doing %s is probably better. Bear runs away." % bear
elif door == "2"
print "You stare into the endless abyss at Cthulhu's retina."
print "1. Blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."

insanity = raw_input("> ")

if insanity == "1" or insanity == "2":
print "Your body survives powered by a mind of jello. Good job!"
else:
print "The insanity rots your eyes into a pool of muck. Good job!"
else:
print "You stumble around and fall on a knife and die. Good job!"

习题31:循环和列表

文件名:ex32.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print "I got %r" % i
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0,6):
print "Adding %d to the list." % i
element.append(i)
# noew we can print them out too
for i in elements:
print "Element was: %d" % i

习题33:while循环

文件名:ex33.py

接下来是一个更在你意料之外的概念:while-loop,它会一直执行它下面的代码片段,直到它对应的布尔表达式为False时才会停下来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
i = 0
numbers = []

while i < 6 :
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now:", numbers
print "At the bottom i is %d" % i

print "The numbers:"

for num in numbers:
print num

习题34:访问列表的元素

文件名:ex34.py

列表的用处很大,但只有你能访问里边的内容时它才能发挥出来。你已经学会按顺序读出列表的内容,但如果你要得到第5个元素该怎么办呢?你要得第5个元素该怎么办呢?你需要知道如何访问列表中的元素。访问第一个元素的方法是这样的:

1
2
animals = ['bear', 'tigher', 'penguin', 'zebra']
bear = animal[0]

你定义一个animals的列表,然后你用0来获取第一个元素

习题35:分支和函数

文件名:ex35.py

你已经学会了if语句、函数、还用列表。现在需要练习一下思维了。把下面的代码写下来,看你是否能弄懂它实现的是什么功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from sys import exit

def gold_room():
print "This room if full of gold. How much do you take?"
next = raw_input(">")
if "0" in next or "1" in next:
how_much = int(next)
else:
dead("Man, learn to type a number. ")

if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")

def bear_room():
print "There is a bear here. "
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved = False

while True:
next = raw_input(">")
if next == "take honey":
dead("The bear looks at you then slaps your face off.")
elif next =="taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go ghrough is now."
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your legoff. ")
elif next == "open door " and bear_moved:
gold_room()
else:
print "I got no idea what that means."
def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
next = raw_input(">")
if "flee" in next:
start()
elif "head" in next:
dead("Well that was tasty!")
else:
cthulhu_room()

def dead(why):
print why, "Good job!"
exit(0)

def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"

next == raw_input(">")

if next == "left":
bear_room()
elif next == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")

start()