笨办法学python习题21-26

#习题 21:函数可以返回东西
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?")
1. 我们调用函数时使用了两个参数: a 和 b 。 
2. 我们打印出这个函数的功能,这里就是计算加法(adding) 
3. 接下来我们告诉 Python 让它做某个回传的动作:我们将 a + b 的值返回(return)。或者你可以这么说:“我将 a 和 b 加起来,再把结果返回。” 
4. Python 将两个数字相加,然后当函数结束的时候,它就可以将 a + b 的结果赋予一个变量。

加分习题 
1. 如果你不是很确定 return 的功能,试着自己写几个函数出来,让它们返回一些值。你可以将任何可以放在 = 右边的东西作为一个函数的返回值。 
2. 这个脚本的结尾是一个迷题。我将一个函数的返回值用作了另外一个函数的参数。我将它们链接到了一起,就跟写数学等式一样。这样可能有些难读,不过运行一下你就知道结果了。接下来,你需要试试看能不能用正常的方法实现和这个表达式一样的功能。 
3. 一旦你解决了这个迷题,试着修改一下函数里的某些部分,然后看会有什么样的结果。你可以有目的地修改它,让它输出另外一个值。 
4. 最后,颠倒过来做一次。写一个简单的等式,使用一样的函数来计算它。


#习题24:更多练习
print("Let's practice everything.")
print("You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.")
poem = """
\t The 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." %(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))

加分习题

1. 记得仔细检查结果,从后往前倒着检查,把代码朗读出来,在不清楚的位置加上注释。

2. 故意把代码改错,运行并检查会发生什么样的错误,并且确认你有能力改正这些错误。

#练习25:更多更多的练习
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)    # 把参数words中的内容按照升序排列,并生成一个新的列表,返回结果
def print_first_word(words):
    word = words.pop(0) # 拿出words列表中的第一个元素,并返回该元素的值
    print(word)
def print_last_word(words):
    word = words.pop(-1)    # 拿出words列表中的最后一个元素,并返回该元素的值
    print(word)
def sort_sentence(sentence):
    words = break_words(sentence)
    return  sort_words(words)
def print_first_and_last(sentence):
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)
def print_first_and_last_sorted(sentence):
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

 

from ex25 import *
sentence = "All good things come to those who wait."
words = break_words(sentence)   # 对句子划分
print(words)    # 输出划分后的单词
sorted_words = sort_words(words)    # 对单词进行排序
print(sorted_words)     # 输出
print_first_word(words)     # 输出word排序中的第一个单词
print_last_word(words)     # 输出word排序中的最后一个单词
print(words)    # 输出此时的单词
print_first_word(sorted_words)     # 输出sort_words排序中的第一个单词
print_last_word(sorted_words)     # 输出sort_words排序中的最后一个单词
print(sorted_words)    # 输出此时排序完成的单词
sorted_words = sort_sentence(sentence)     # 直接对句子进行排序
print(sorted_words)     # 输出排序后的单词
print_first_and_last(sentence)      # 输出原句子的第一个和最后一个
print_first_and_last_sorted(sentence)     # 输出经过排序后句子的第一个和最后一个

习题 26: 恭喜你,现在可以考试了!

修正别人的代码,试一下吧。

代码基本是前面练习的集合,复习一下。

源代码地址:https://learnpythonthehardway.org/exercise26.txt

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.poop(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(sentence)
    return sort_words(words)

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

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


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 explantion
\n\t\twhere there is none.
"""


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

five = 10 - 2 + 3 - 5
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 jeans, %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 crabapples." % secret_formula(start_pont


sentence = "All god\tthings come to those who weight."

words = ex25.break_words(sentence)
sorted_words = ex25.sort_words(words)

print_first_word(words)
print_last_word(words)
.print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = ex25.sort_sentence(sentence)
prin sorted_words

print_irst_and_last(sentence)

   print_first_a_last_sorted(senence)

更改后的代码
--------------------------------------------------
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(sentence)
    return sort_words(words)

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

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


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 explantion
\n\t\twhere there is none.
"""


print("--------------")
print(poem)
print ("--------------")

five = 10 - 2 + 3 - 5
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 jeans, %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 crabapples." % secret_formula(start_point))

from ex25 import *
sentence = "All god\tthings come to those who weight."

words = break_words(sentence)
sorted_words = sort_words(words)

print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = sort_sentence(sentence)
print(sorted_words)

print_first_and_last(sentence)

print_first_and_last_sorted(sentence)

习题27:记住逻辑关系

这部分b基本问题不大
and:与
or:或
not:非
!=:不等于
==:等于
>=:大于等于
<=:小于等于
True:真
False:假
真值表

NOT    True?
not false     True
not true    False


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


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


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


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


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


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

 

 

#习题28:布尔表达式练习
print(True and True)
print(False and True)
print(1 == 1 and 2 == 1)
print("test" == "test")
print(1 == 1 or 2 !=1)
print(True  and 1 == 1)
print(False and 0 !=0)
print(True or 1 == 1)
print("test" == "testing")
print("test" == 1)
print(not(True and False))
print(not(1 == 1 and 0 !=1))
print(not (10 ==1 or 1000 == 1000))
print(not 1 !=10 or  3 == 4)
print(not ("testing" == "testing" and "Zed" == "Cool Guy"))
print(1 == 1 and not ("testing" == 1 or 1 == 0))
print("chunky" == "bacon" and not(3 == 4 or 3 == 3))
print(3 == 3 and not ("testing" == "testing" or "Python" == "Fun"))

加分习题

 1. Python 里还有很多和 != 、 == 类似的操作符. 试着尽可能多地列出 Python 中的等价运算符。例如 < 或者 <= 就是。

2. 写出每一个等价运算符的名称。例如 != 叫 “not equal(不等于)”。

3. 在 python 中测试新的布尔操作。在敲回车前你需要喊出它的结果。不要思考,凭自己的第一感就可以了。把表达式和结果用笔写下来再敲回车,最后看自己做对多少,做错多少。

4. 把习题 3 那张纸丢掉,以后你不再需要查询它了。

 

#习题 29:如果(if)
people = 20
cats = 30
dogs = 15

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

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

加分习题

猜猜“if语句”是什么,它有什么用处。在做下一道习题前,试着用自己的话回答下面的问题:

1. 你认为 if 对于它下一行的代码做了什么?

if后面是布尔表达式是true继续执行下面的语句,否则跳出该if

2. 为什么 if 语句的下一行需要 4 个空格的缩进?

表示下面的语句属于if

3. 如果不缩进,会发生什么事情?

不缩进,该语句就不受if管控,就会依次执行下面的语句

4. 把习题 27 中的其它布尔表达式放到``if语句``中会不会也可以运行呢?试一下。

会运行,如下图:

5. 如果把变量 people, cats, 和 dogs 的初始值改掉,会发生什么事情?

输出的内容会根据初始值变化.

 

#习题 30:Else 和If
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 cant'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.")

 

加分习题

1. 猜想一下 elif 和 else 的功能。

2. 将 cars, people, 和 buses 的数量改掉,然后追溯每一个 if 语句。看看最后会打印出什么来。

3. 试着写一些复杂的布尔表达式,例如 cars > people and buses < cars。

 

主要其中if成立 就不走elif了

4. 在每一行的上面写注解,说明这一行的功用。

 

建了一个大数据运维群,各位大数据运维的同学可以一起讨论 群号584912368  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值