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

过程解析:

1、定义函数:如def add(形参)函数

2、调用函数: add(实参)    别忘记加()

3、在函数调用的时候将实参的值传给形参,代入到函数中进行计算,return 关键字将函数计算的结果再返回给调用它的地方

代码:

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:更多练习

代码:

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_formuls(started):
  jelly_beans = started * 500
  jars = jelly_beans / 1000
  crates = jars / 100
  return jelly_beans, jars, crates

start_point = 10000
beans, jars, crates = secret_formuls(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_formuls(start_point)

结果:

习题27:记住逻辑关系

逻辑术语:

  and   与

  or   或

  not   非

  != (not equal)   不等于

  == (equal)   等于

  >= (greater-than-equal)   大于等于

  <= (less-than-equal)   小于等于

  True   真

  False   假

真值表:

NOT

not False    True
not True    False

OR
True or False   True
True or True   True
False or True   True
False or False   False

AND
True and False   False
True and True    True
False and True   False
False and False   False

NOT OR
not (True or False)   False
not (True or True)   False
not (False or True)   False
not (False or False)   True

NOT AND
not (True and False)   True
not (True and True)   False
not (False and True)   True
not (False and False)   True

!= 
1 != 0    True
1 != 1    False
0 != 1    True
0 != 0    False

==
1 == 0    False
1 == 1    True
0 == 1    False
0 == 0    True

习题29:如果(if)

格式:

  if 布尔表达式  : (“:”后跟一个代码块,每个语句都有4个空格的缩进)

    语句(如果布尔表达式结果为真,则执行该语句,否则跳过该语句)

代码:

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 id 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 dogs."

if people == dogs:
  print "People are dogs."

结果:

习题30:Else 和 If

代码:

people = 20 
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:作出决定

代码:

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 probablt 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!"

结果:

习题32:循环与列表

-- 使用刘表元素所在的位置数(基数)访问列表元素,更多列表相关可上网搜索

代码:

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

# alse we can go through mixes 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(1, 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

结果:

习题33:While循环 --  尽量少用,大部分时候用for循环

代码:

i = 0
numbers = []

while i < 6:
  print "At the top i is %d" % i
  numbers.append(i)

  i += 1
  print "Numbers now: ", numbers
  print "At the bottom i is %d" % i

print "The numbers: "

for num in numbers:
print num

结果:

习题35:分支与函数

代码:

from sys import exit

def gold_room():
  print "This room is 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 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 "Hear 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()

结果:(路径之一)

习题36:设计与调试

If 语句的规则

1. 每一个“if 语句”必须包含一个 else.
2. 如果这个 else 永远都不应该被执行到,因为它本身没有任何意义,那你必须在 else 语句后面
使用一个叫做 die 的函数,让它打印出错误信息并且死给你看,这和上一节的习题类似,这样你
可以找到很多的错误。
3. “if 语句”的嵌套不要超过 2 层,最好尽量保持只有 1 层。 这意味着如果你在 if 里边又有了
一个 if,那你就需要把第二个 if 移到另一个函数里面。
4. 将“if 语句”当做段落来对待,其中的每一个 if, elif, else 组合就跟一个段落的句子组
合一样。在这种组合的最前面和最后面留一个空行以作区分。
5. 你的布尔测试应该很简单,如果它们很复杂的话,你需要将它们的运算事先放到一个变量里,并
且为变量取一个好名字。

循环的规则

1. 只有在循环永不停止时使用“while 循环”,这意味着你可能永远都用不到。这条只有 Python
中成立,其他的语言另当别论。
2. 其他类型的循环都使用“for 循环”,尤其是在循环的对象数量固定或者有限的情况下。

调试(debug)的小技巧

1. 不要使用 “debugger”。 Debugger 所作的相当于对病人的全身扫描。你并不会得到某方面的
有用信息,而且你会发现它输出的信息态度,而且大部分没有用,或者只会让你更困惑。
2. 最好的调试程序的方法是使用 print 在各个你想要检查的关键环节将关键变量打印出来,从而
检查哪里是否有错。
3. 让程序一部分一部分地运行起来。不要等一个很长的脚本写完后才去运行它。写一点,运行一点,
再修改一点。

习题37:复习各种符号

Keywords(关键字)

• and
• del
• from
• not
• while
• as
• elif
• global
• or
• with
• assert
• else
• if
• pass
• yield
• break
• except
• import
• print
• 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
• %s
• %%

操作符号

• +
• -
• *
• **
• /
• //
• %
• <
• >
• <=
• >=
• ==
• !=
• <>
• ( )
• [ ]
• { }
• @
• ,
• :
• .
• =
• ;
• +=
• -=
• *=
• /=
• //=
• %=
• **=

python入门 -- 学习笔记3的更多相关文章

  1. Python入门学习笔记4:他人的博客及他人的学习思路

    看其他人的学习笔记,可以保证自己不走弯路.并且一举两得,即学知识又学方法! 廖雪峰:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958 ...

  2. Python入门学习笔记

    了解 一下Python中的基本语法,发现挺不适应的,例如变量经常想去指定类型或者if加个括号之类的.这是在MOOC中学习到的知识中一点简单的笔记. Python的变量和数据类型: 1.Python这种 ...

  3. python入门学习笔记(三)

    10.函数 求绝对值的函数 abs(x) 也可以在交互式命令行通过 help(abs) 查看abs函数的帮助信息.调用 abs 函数:>>> abs(100)100>>& ...

  4. Python入门 学习笔记 (二)

      今天学习了一些简单的语法规则,话不多说,开始了:      二.数据类型                常用数据类型中的整形和浮点型就不多说了.                1.字符串     ...

  5. python入门 -- 学习笔记1

    学习资料:笨方法学Python 准备: 安装环境----请自行网络搜索(Windows安装很简单,和其他安装程序一样) 找一个自己习惯的编辑器(比如:sublime text 3) 创建一个专门的目录 ...

  6. Python入门 学习笔记 (一)

    原文地址:http://www.cnblogs.com/lujianwenance/p/5939786.html 说到学习一门语言第一步就是先选定使用的工具(环境).因为本人是个小白,所以征求了一下同 ...

  7. python入门学习笔记(二)

    6.6替换元素 7.tuple类型 7.1创建tuple 7.2创建单元素tuple    7.3"可变"的tuple 8.条件判断和循环 8.1,if语句   8.2,if... ...

  8. python入门学习笔记(一)

    写在开头:         A:python的交互式环境                                                                         ...

  9. python入门 -- 学习笔记4

    习题38:列表的操作 当你看到像 mystuff.append('hello') 这样的代码时,你事实上已经在 Python 内部激发了一个连锁反应.以下是它的工作原理: 1. Python 看到你用 ...

随机推荐

  1. linux 怎么上传下载-- 文件

    https://www.cnblogs.com/lynn-li/p/6078595.html yum install lrzsz rz:从本地上传文件至服务器 sz filename:从服务器下载文件 ...

  2. Codeforces1076F. Summer Practice Report(贪心+动态规划)

    题目链接:传送门 题目: F. Summer Practice Report time limit per test seconds memory limit per test megabytes i ...

  3. 转-软件测试人员在工作中如何运用Linux

    从事过软件测试的小伙们就会明白会使用Linux是多么重要的一件事,工作时需要用到,面试时会被问到,简历中需要写到. 对于软件测试人员来说,不需要你多么熟练使用Linux所有命令,也不需要你对Linux ...

  4. Redis占硬盘空间

    转载自:http://blog.csdn.net/qq285744011/article/details/51002409 [问题的原因] Windows版Redis启动后,会在C盘自动创建一个很大的 ...

  5. 第二章 C#语法基础(2.1 C#语言的数据类型一)

    C#的数据类型 [案例]本案例实现3位评委给一位选手评分,通过键盘输入各位评委的打分,通过屏幕输出该选手的平均分. [案例目的] (1)掌握变量的定义方式; (2)掌握常用的数据类型; (3)掌握数据 ...

  6. 关于STL容器

    容器: 概念:如果把数据看做物体,容器就是放置这些物体的器物,因为其内部结构不同,数据摆放的方式不同,取用的方式也不同,我们把他们抽象成不同的模板类,使用时去实例化它 分类: 序列容器.关联容器.容器 ...

  7. [转]Python依赖打包发布详细

    Python依赖打包发布详细   http://www.cnblogs.com/mywolrd/p/4756005.html 将Python脚本打包成可执行文件   Python是一个脚本语言,被解释 ...

  8. JDK / JRE zip

    Server JRE与JRE的区别: Server JRE一般用于服务器上安装,只有64bit版本,不会安装浏览器插件.自动更新,有监视工具.没有Java Fx和其他开发工具:有安装程序,只是一压缩目 ...

  9. 枚举、反射等 GetEnumName GetEnumDescription

    /// <summary> /// Retrieves the name of the constant in the specified enumeration that has the ...

  10. 移植Valgrind检测Android JNI内存泄漏

    1.相关工具 Valgrind:从Valgrind官网下载最新的源码包,我这里用的是:valgrind 3.14.0 (tar.bz2) [17MB] - 9 October 2018. Ubuntu ...