《笨办法学python》习题26-30

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

下载链接:https://learnrubythehardway.org/book/exercise26.txt

代码

先贴上错误的代码吧

  # This function will break up words for us.
  def Ex25.brak_words(stuff)
    words = stuff.split(' ')
    return word
  end

  # Sorts the words.
  def Ex25.sortwords(words)
    return words.sort
  end

  # Prints the first word after popping it off.
  df Ex25.print_first_word(words)
    word = words.pop(1)
    puts wor
  end

  # Prints the last word after popping it off.
  def Ex25:print_last_word(words)
    word = words.pop
    put word
  end

  # Takes in a full sentence and returns the sorted words.
  def Ex25.sort_sentence(sentence)
    words = Ex25.break_words(sentence)
    return Ex25.sort_words(words)
  ed

  # Prints the first and last words of the sentence.
  def Ex25.print_first_and_last(sentence
    words = Ex25.break_words(sentenc)
    Ex25.print_first_wrd(word)
    Ex25.print_last_word(words)
  end

  # Sorts the words then prints the first and last one.
  def Ex25.print_first_and_last_sorted(sentence)
    words = Ex25.sort_sentence(sentence)
    Ex25.print_fist_word(words)
    Ex25.print_last_word(words)
  end



puts "Let's practice everything."
puts 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'

poem = <<END
\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.
ENDED

puts "--------------"
puts poem
puts "--------------"


five = 10 - 2  3 - 6
puts "This should be five: #{five"

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


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

puts "With a starting point of: #{start_point}"
puts "We'd have #{beans beans, #{jars} jars, and #{crates} crates."

start_point = start_point / 10

sentence = "All good things come to those who wait."
words = Ex25.break_words(sentence)
sorted_words = Ex25.sort_words(words)
Ex25.print_first_word(wrds)
Ex25.print_last_word words)
Ex25.print_first_word(sort_words)
Ex25.print_last_word(sorted_words)
sorted_words = Ex25.sort_sentenc(sentence)
Ex25.print_first_and_last(sentence)
Ex25:print_first_and_last_sorted(sentence)

因为要修改的东西 太多了,索性一次性修改完贴上来了。
我估计一下,修改最多就是变量名是否统一,缩进是否对,标志符是否缺():
诸如此类的。

# This function will break up words for us.
def ex25_break_words(stuff):
    words = stuff.split(' ')
    return words

# Sorts the words.
def ex25_sort_words(words):
    return sorted(words)

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

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

# Takes in a full sentence and returns the sorted words.
def ex25_sort_sentence(sentence):
    words = ex25_break_words(sentence)
    return ex25_sort_words(words)

# Prints the first and last words of the sentence.
def ex25_print_first_and_last(sentence):
    words = ex25_break_words(sentence)
    ex25_print_first_word(words)
    ex25_print_last_word(words)

# Sorts the words then prints the first and last one.
def ex25_print_first_and_last_sorted(sentence):
    words = ex25_sort_sentence(sentence)
    ex25_print_first_word(words)
    ex25_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 explanation
\n\t\twhere there is none.
"""

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

five = 10 - 2 + 3 - 6
print(f"This should be five: {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: #{start_point}")
print("We'd have {beans} beans, {jars} jars, and #{crates} crates.")

start_point = start_point / 10

sentence = "All good things come to those who wait."
words = ex25_break_words(sentence)
sorted_words = ex25_sort_words(words)
ex25_print_first_word(words)
ex25_print_last_word (words)
ex25_print_first_word(sorted_words)
ex25_print_last_word(sorted_words)
sorted_words = ex25_sort_sentence(sentence)
ex25_print_first_and_last(sentence)
ex25_print_first_and_last_sorted(sentence)
PS C:\Users\WU\pyfile> python ex26fix.py
Let's practice everything.
'You'd need to know 'bout escapes with \ that do
 newlines and    tabs.
--------------

        The lovely world
with logic so firmly planted
cannot discern
 the needs of love
nor comprehend passion from intuition
and requires an explanation

                where there is none.

--------------
This should be five: 5
With a starting point of: #{start_point}
We'd have {beans} beans, {jars} jars, and #{crates} crates.
All
wait.
All
who
All
wait.
All
who

习题27:记住逻辑关系

这部分和Grasshopper密切相关咧 哈哈
在这里插入图片描述
逻辑代数、布尔代数、命题逻辑、数理逻辑

知识点

逻辑术语

逻辑术语结果
and
or
not
!=不等于
==等于
>=大于等于
<=小于等于
>大于
<小于
True
Talse
in属于

真值表

not真假
not FalseTrue
not TrueFalse
or真假
True or FalseTrue
True or TrueTrue
False or TrueTrue
False or FalseFalse
and真假
True and FalseFalse
True and TrueTrue
False and TrueFalse
False and FalseFalse
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)False
not (True and True)True
not (False and True)False
not (False and False)False
!=真假
1 != 0True
1 != 1False
0 != 1True
0 != 0False
==真假
1 == 0False
1 == 1True
0 == 1False
0 == 0True

习题28:布尔表达式

知识点

  • 参照判断复杂的布尔表达式
    找到“==”和“!=”,写成真值
    找到括号里的and/or,算真值
    找到每一个not,取反真值
    找到剩下的and/or,得到结果
  • 在python中 != 是主流用法,<>将逐渐废弃。应该使用前者。
  • 任何以False开头的and 语句都会被直接处理成False,不会继续检查后面的语句。任何包含True的or语句,只有处理到True,就不会继续往下推算,直接返回True。
  • python和很多编程语言一样,都是给布尔表达式返回两个被操作对象中的一个,而不是True或False。
    使用and的时候:如果and前面是0或Flase,后面的不用看结果也应是0或Flase;如果前面不是这两个,就会检测后面的对象,后面的对象如果是0或者False,就返回0或者False,如果也是真值,那就直接返回这个操作对象了。总的来说,从前面开始搜索,遇到0或Flase则返回0或Flase,否则返回当前操作对象。
PS C:\Users\WU\pyfile> python
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> False and 0
False
>>> 0 and False
0
>>> 1 and True
True
>>> True and 1
1
>>> False and 1
False
SyntaxError: invalid syntax
>>> 1 and False
False
  • 同理,使用or的时候:如果前面的是真值,直接忽略后面的,返回前面的对象;如果前面的是0或者False,就会检测后面的对象,是真值返回真值,否则返回后面的0或者False:
>>> 1 and False
False
>>> 1 or 0
1
>>> 0 or 1
1
>>> 1 or True
1
>>> True or 1
True
>>> 1 or 34
1
>>> 0 or False
False
>>> False or 0
0

Python赋值运算符

运算符描述实例
=简单的赋值运算符c = a + b 将 a + b 的运算结果赋值为 c
+=加法赋值运算符c += a 等效于 c = c + a
-=减法赋值运算符c -= a 等效于 c = c - a
*=乘法赋值运算符c *= a 等效于 c = c * a
/=除法赋值运算符c /= a 等效于 c = c / a
%=取模赋值运算符c %= a 等效于 c = c % a
**=幂赋值运算符c **= a 等效于 c = c ** a
//=取整除赋值运算符c //= a 等效于 c = c // a

习题29:if 语句

代码

people =20
cats = 30
dogs = 15

if people < cats:
    print("Too many cats! The world is doomed!")
if people > cats:
    print("Now 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.")
PS C:\Users\WU> cd pyfile
PS C:\Users\WU\pyfile> python ex29.py
Too many cats! The world is doomed!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.

知识点

  • if 语句为代码创建了一个所谓的“分支”,若布尔表法师为真这允许接下来的代码。行尾冒号(:)作用是告诉python创建一个新的代码块,缩进告诉python这些代码处于该代码中。
  • python中if 语句的语法格式:

if <条件>:
<语句块>
语句块是if条件满足后执行的一个或多个语句序列,语句块中语句通过与if所在行形成缩进表达包含关系。

  • if语句中语句块执行与否 依赖于条件(True or False)判断。但无论什么情况,控制都会转到if语句与该语句同级别的下一条语句。
  • 赋值运算符 +=, x += 1和x =x+1 一样。python 使用 “=” 表示赋值语句,使用“==”表示等于(用于判断)

破坏程序

  • 破坏程序一:不缩进,缩进错误: 期望一个缩进的块 。IndentationError: expected an indented block。
if people == dogs:
print("People are dogs.")
PS C:\Users\WU\pyfile> python ex29.py
  File "C:\Users\WU\pyfile\ex29.py", line 22
    print("People are dogs.")
    ^
IndentationError: expected an indented block

java里面方法后面是用{}来区分是否属于一个方法的,python的是用缩进来识别语法逻辑块的(i.e. if, while, for, def 等)。同一个if逻辑块下面的语句必须要有相同的缩进,同一个逻辑块下面的空格统一就行,可以是2个或者4个空格。Tab键就是4个空格。

  • 破坏程序二:if语句后面是中文: 。假如是英文:,换行的时候直接是tab空格下一句了。
if people == dogs:
    print("People are dogs.")
PS C:\Users\WU\pyfile> python ex29.py
  File "C:\Users\WU\pyfile\ex29.py", line 21
    if people == dogs:
                     ^
SyntaxError: invalid character ':' (U+FF1A)

习题30:else 和 if

代码

people = 20
cars = 30
trucks = 15

if cars > people:                       #如果cars的值大于people的值
    print("We should take the cars")    #就输出字符串
elif cars < people:                     #如果cars的值小于people的值
    print("We should not take the cars") #输出字符串
else:                         #如果cars既不大于又不小于(即等于)people
    print("We can't decide.")  #输出字符串

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

if people > trucks:
    print("Alright, Let's just take the trucks.")
else:
    print("Fine, Let's stay home then.")

if cars>people or trucks < cars:  #复杂布尔表达式
    print("xixi")
PS C:\Users\WU\pyfile> python ex30.py
We should take the cars
Maybe we could take the trucks.
Alright, Let's just take the trucks.
xixi

知识点

  • elif的功能与if一样的;
  • else是在前面if和elif都不执行的情况下,执行else下的代码块。
  • 当有多个elif块都是True,python只会运行他遇到的是True的第一个块,所以只有第一个为True的块会运行。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值