python练习题-3
author:headsen chen
date: 2018-06-01 15:51:05
习题 31: 作出决定(if + raw_input)
[root@localhost py]# cat desition.py
#!/usr/bin/env python
print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input("> ")
if door == "":
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 == "":
print "The bear eats your face off. Good job!"
elif bear == "":
print "The bear eats your legs off. Good job!"
else:
print "Well, doing %s is probably better. Bear runs away." % bear elif door == "":
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 == "" or insanity == "":
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!"
[root@localhost py]# python desition.py
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 1
There's a giant bear here eating a cheese cake. What do you do?
1. Take the cake.
2. Scream at the bear.
> 2
The bear eats your legs off. Good job!
习题 32: 循环和列表
[root@localhost py]# cat list-for.py
#!/usr/bin/env python
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
# append is a function that lists understand
elements.append(i)
# now we can print them out too for i in elements:
print "Element was: %d" % i
[root@localhost py]# python list-for.py
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got 'pennies'
I got 2
I got 'dimes'
I got 3
I got 'quarters'
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5
习题 33: While 循环
[root@localhost py]# cat while.py
#!/usr/bin/env python
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
[root@localhost py]# python while.py
At the top i is 0
Numbers now: [0]
At the bottom i is 1
At the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5
习题 35: 分支和函数
[root@localhost py]# cat func-if.py
#!/usr/bin/env python
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if "" in next or "" 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 through it now."
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
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()
[root@localhost py]# python func-if.py
You are in a dark room.
There is a door to your right and left.
Which one do you take? > left
There is a bear here.
The bear has a bunch of honey.
The fat bear is in front of another door.
How are you going to move the bear? > taunt bear
The bear has moved from the door. You can go through it now. > open door
This room is full of gold. How much do you take? > asf
Man, learn to type a number. Good job!
习题 36: 复习各种符号
关键字
and
del
from
not
while
as
elif
global
or
with
assert
else
if
pass
yield
break
except
import
class
exec
in
raise
continue
finally
is
return
def
for
lambda
try 数据类型
True
False
None
strings
numbers
floats
lists 字符串转义序列(Escape Sequences) \\
\'
\"
\a
\b
\f
\n
\r
\t
\v 字符串格式化(String Formats)
%d -------》 数字
%i
%o
%u
%x
%X
%e
%E
%f --------》 小数
%F
%g
%G
%c
%r ----------》%r 调用 rper函数打印字符串,repr函数返回的字符串是加上了转义序列,是直接书写的字符串的形式
%s ----------》%s 调用 str函数打印字符串,str函数返回原始字符串
%% 操作符号
+
-
*
**
/
//
%
<
>
<=
>=
==
!=
<>
( )
[ ]
{ }
@
,
:
.
=
;
+=
-=
*=
/=
//=
%=
**=
习题37:列表
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there's not 10 things in that list, let's fix that."
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn","Banana", "Girl", "Boy"] while len(stuff) != 10:
next_one = more_stuff.pop()
print "Adding: ", next_one
stuff.append(next_one)
print "There's %d items now." % len(stuff)
print "There we go: ", stuff
print "Let's do some things with stuff."
print stuff[1]
print stuff[-1] # whoa! fancy
print stuff.pop()
print ' '.join(stuff) # what? cool!
print '#'.join(stuff[3:5]) # super stellar! [root@localhost py]# python ex
ex15_sample.txt ex39.py
[root@localhost py]# python ex39.py
Wait there's not 10 things in that list, let's fix that.
Adding: Boy
There's 7 items now.
Adding: Girl
There's 8 items now.
Adding: Banana
There's 9 items now.
Adding: Corn
There's 10 items now.
There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
Let's do some things with stuff.
Oranges
Corn
Corn
Apples Oranges Crows Telephone Light Sugar Boy Girl Banana
Telephone#Light
习题 40: 字典
[root@localhost py]# cat dict.py
#!/usr/bin/env python
cities = {'CA': 'San Francisco', 'MI': 'Detroit','FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
print cities
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found."
# ok pay attention!
cities['_find'] = find_city
while True:
print "State? (ENTER to quit)",
state = raw_input("> ")
if not state: break
# this line is the most important ever! study!
city_found = cities['_find'](cities, state)
print city_found
习题 41: 来自 Percal 25 号行星的哥顿人
[root@localhost py]# cat gothons.py
#!/usr/bin/env python
from sys import exit
from random import randint def death():
quips = ["You died. You kinda suck at this.",
"Nice job, you died ...jackass.",
"Such a luser.",
"I have a small puppy that's better at this."]
print quips[randint(0, len(quips)-1)]
exit(1) def central_corridor():
print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
print "your entire crew. You are the last surviving member and your last"
print "mission is to get the neutron destruct bomb from the Weapons Armory,"
print "put it in the bridge, and blow the ship up after getting into an "
print "escape pod."
print "\n"
print "You're running down the central corridor to the Weapons Armory when"
print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
print "flowing around his hate filled body. He's blocking the door to the"
print "Armory and about to pull a weapon to blast you." action = raw_input("> ")
if action == "shoot!":
print "Quick on the draw you yank out your blaster and fire it at the Gothon."
print "His clown costume is flowing and moving around his body, which throws"
print "off your aim. Your laser hits his costume but misses him entirely. This"
print "completely ruins his brand new costume his mother bought him, which"
print "makes him fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats you."
return 'death'
elif action == "dodge!":
print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon's blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "bang your head on the metal wall and pass out."
print "You wake up shortly after only to die as the Gothon stomps on"
print "your head and eats you."
return 'death'
elif action == "tell a joke":
print "Lucky for you they made you learn Gothon insults in the academy."
print "You tell the one Gothon joke you know:"
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
print "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
print "While he's laughing you run up and shoot him square in the head"
print "putting him down, then jump through the Weapon Armory door."
return 'laser_weapon_armory'
else:
print "DOES NOT COMPUTE!"
return 'central_corridor'
def laser_weapon_armory():
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It's dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There's a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can't"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" % (randint(1,9), randint(1,9),randint(1,9))
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death' def the_bridge():
print "You burst onto the Bridge with the neutron destruct bomb"
print "under your arm and surprise 5 Gothons who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don't want to set it off."
action = raw_input("> ")
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge" def escape_pod():
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pods, which one"
print "do you take?"
good_pod = randint(1,5)
guess = raw_input("[pod #]> ")
if int(guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space,then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet,you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
exit(0) ROOMS = {
'death': death,
'central_corridor': central_corridor,
'laser_weapon_armory': laser_weapon_armory,
'the_bridge': the_bridge,
'escape_pod': escape_pod
} def runner(map, start):
next = start
while True:
room = map[next]
print "\n--------"
next = room() runner(ROOMS, 'central_corridor')
习题 42: 类(高级的函数)
[root@localhost py]# cat class.py
#!/usr/bin/env python
class TheThing(object):
def __init__(self):
self.number = 0
def some_function(self):
print "I got called."
def add_me_up(self, more):
self.number += more
return self.number
# two different things
a = TheThing()
b = TheThing() a.some_function()
b.some_function() print a.add_me_up(20)
print a.add_me_up(20) print b.add_me_up(30)
print b.add_me_up(30) print a.number
print b.number
[root@localhost py]# python class.py
I got called.
I got called.
20
40
30
60
40
60
总结:
参数里的 self 了吧?你知道它是什么东西吗?对了,它就是 Python 创建的额外的一个参数,有了它你才能实现 a.some_function()
__init__ 函数是为Python class 设置内部变量的方式。你可以使用.将它们设置到self上面。你的__init__不应该做太多的事情,这会让 class 变得难以使用。
class 使用 “camel case(驼峰式大小写)”,例如 SuperGoldFactory
普通函数应该使用 “underscore format(下划线隔词)”, my_awesome_hair ,
永远永远都使用 class Name(object) 的方式定义 class
python练习题-3的更多相关文章
- Python练习题 028:求3*3矩阵对角线数字之和
[Python练习题 028] 求一个3*3矩阵对角线元素之和 ----------------------------------------------------- 这题解倒是解出来了,但总觉得 ...
- Python练习题 027:对10个数字进行排序
[Python练习题 027] 对10个数字进行排序 --------------------------------------------- 这题没什么好说的,用 str.split(' ') 获 ...
- Python练习题 026:求100以内的素数
[Python练习题 026] 求100以内的素数. ------------------------------------------------- 奇怪,求解素数的题,之前不是做过了吗?难道是想 ...
- Python练习题 025:判断回文数
[Python练习题 025] 一个5位数,判断它是不是回文数.即12321是回文数,个位与万位相同,十位与千位相同. ---------------------------------------- ...
- Python练习题 024:求位数及逆序打印
[Python练习题 024] 给一个不多于5位的正整数,要求:一.求它是几位数,二.逆序打印出各位数字. ---------------------------------------------- ...
- Python练习题 004:判断某日期是该年的第几天
[Python练习题 004]输入某年某月某日,判断这一天是这一年的第几天? ---------------------------------------------- 这题竟然写了 28 行代码! ...
- Python练习题-1.使用匿名函数对1~1000求和,代码力求简洁。
Python 练习 标签(空格分隔): Python Python练习题 Python知识点 一.使用匿名函数对1~1000求和,代码力求简洁. 答案: In [1]: from functools ...
- PYTHON练习题 二. 使用random中的randint函数随机生成一个1~100之间的预设整数让用户键盘输入所猜的数。
Python 练习 标签: Python Python练习题 Python知识点 二. 使用random中的randint函数随机生成一个1~100之间的预设整数让用户键盘输入所猜的数,如果大于预设的 ...
- python 基础 2.8 python练习题
python 练习题: #/usr/bin/python #coding=utf-8 #@Time :2017/10/26 9:38 #@Auther :liuzhenchuan #@File ...
- Python练习题2
如果真的想学精,学什么都不是好学的,如果真的想把Python学的出神入化,几乎自己想做什么都可以,就要下定恒心,坚持下去. 接下来继续更新Python练习题2,通过更新前一部的练习题让自己也学到了不少 ...
随机推荐
- VS2010 DLL库生成和使用
一.生成dll文件(VS2010 Win32 程序) CreateDll.h // 下列 ifdef 块是创建使从 DLL 导出更简单的// 宏的标准方法.此 DLL 中的所有文件都是用命令行上定义的 ...
- java开源内容管理系统J4CMS支持真正静态化
原理非常easy,使用httpclient请求遍历整个站点的菜单.文章链接.请求下来以后,生成html文件.即静态化了 把它们稍作调整,直接扔在88元购买的阿里云主机上.站点就完毕了 这是我的 静态站 ...
- C#中将图片转化成base64字符串
厂址:http://www.cnblogs.com/yunfeifei/p/4165351.html 1.在C#中将图片转化成base64字符串: using System; using System ...
- django admin 如何去掉s 如何去掉django admin 各个模块后面的s
其中加上红色标记的内容,业务管理员后面就不会有 s 了 class UsrMngUser(models.Model): user_name = models.CharField("用户名称& ...
- 自己是个菜鸟 自己查找的简单的适合初学的Makefile
工程中的代码分别存放在add/add_int.c.add/add_float.c.add/add.h.sub/sub_int.c.sub/sub_float.c.sub/sub.h.main.c中. ...
- 使用JSTL的xml:parse标签(或者说x:parse)出现异常NoSuchMethodError,找不到doc的setter method
症状: 如题 <c:import var="hz" url="/xyz/abc.xml" charEncoding="UTF-8"/& ...
- TOTP:Time-based One-time Password Algorithm(基于时间的一次性密码算法)
TOTP:Time-based One-time Password Algorithm(基于时间的一次性密码算法) TOTP - Time-based One-time Password Algori ...
- Unix系统编程()进程内存布局
每个进程所分配的内存由很多部分组成,通常称之为"段(segment)". 文本段包含了进程运行的程序机器语言指令.文本段具有只读属性,以防止进程通过错误指针意外修改自身指令. 因为 ...
- Android——Bundle savedInstanceState的作用
写过Android程序的都知道Activity中有一个名称叫onCreate的方法.该方法是在Activity创建时被系统调用,是一个Activity生命周期的开始.可是有一点容易被忽视,就是onCr ...
- 百度JS模板引擎
1. 应用场景 前端使用的模板系统 或 后端Javascript环境发布页面 2. 功能描述 提供一套模板语法,用户可以写一个模板区块,每次根据传入的数据,生成对应数据产生的HTML片段,渲染不同 ...