您的位置:首页 > 编程语言 > Python开发

Think Python :Chapter 5: Conditionals and Recursion 笔记

2015-04-22 22:26 525 查看

目录

这是麻省理工大学(MIT)官方编程教程中Python Tutorial的内容,教材为《Think Python: How to Think Like a Computer Scientist》。这是我的学习笔记,因为水品有限,请大家多多包涵。如果有一起学习的同学可以一起交流。如笔记中错误,请一定要告诉我啊,我肯定及时改正。所有笔记的目录详见:MIT:Python Tutorial目录

这是MIT官方编程教程中Python TutorialUsing if, else, and while的内容。本篇博客为《 Think Python: How to Think Like a Computer Scientist》的第5章 Conditionals and Recursion的笔记内容。(Think Python :Chapter 5: Conditionals and Recursion

Python Tutorial[3]:Using if, else, and while

Before starting these problems, please read(学习材料):

- Think Python, Chapter 5: Conditionals and Recursion, through section 5.7

- Think Python, Chapter 7: Iteration

Chapter 5 Conditionals(条件语句) and recursion(循环递归语句)

5.1 Modulus operator(模数运算符)

modulus operator(模数运算符): An operator, denoted with a percent sign (%), that works on integers and yields the remainder(余数) when one number is divided by another.

5.2 Boolean expressions(布朗运算表达)

boolean expression: An expression whose value is either True or False.

relational operator: One of the operators that compares its operands: == , != , > , < , >= , and <=.

A common error is to use a single equal sign (=) instead of a double equal sign (==). Remember that = is an assignment operator and == is a relational operator. There is no such thing as =< or =>.(=代表数学任务运算,==代表相关运算)

5.3 Logical operators(逻辑运算)

logical operator: One of the operators that combines boolean expressions: and , or , and not .

5.4 Conditional execution(条件运算)

conditional statement: A statement that controls the flow of execution depending on some condition.

condition: The boolean expression in a conditional statement that determines which branch is executed.

compound statement: A statement that consists of a header and a body. The header ends with a colon (:). The body is indented relative to the header.

5.5 Alternative execution(可选择的运行方式)

branch: One of the alternative sequences of statements in a conditional statement.

#5.5 案例
if x%2==0:
print(x+'is even')
else:
print(x+'is odd')


5.6 Chained conditionals(链状条件语句)

chained conditional: A conditional statement with a series of alternative branches.

def compare_xy(x,y):
if x<y:
print(x,'is less than',y)
elif x>y:
print(x,'is greater than',y)
else:
print(x,'and',y,'are equal')


elif is an abbreviation of “else if.”

5.7 Nested conditionals(嵌入式条件语句)

nested conditional: A conditional statement that appears in one of the branches of another conditional statement.

5.8 Recursion(递归,循环语句)

It is legal for one function to call another; it is also legal for a function to call itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do.

recursion: The process of calling the function that is currently executing.

#5.8 recursion 循环语句
def countdown(n):
if n<=0:
print('Blastoff')
else:
print(n)
countdown(n-1)


案例二:这个语法简洁有功底,要好好学习

#5.8 recursion:print a string n times
def print_n(s,n):
if n<=0:
return
print s
print_n(s,n-1)


5.10 Infinite recursion(无限循环)

base case:(循环终止条件) A conditional branch in a recursive function that does not make a recursive call.

infinite recursion: A recursion that doesn’t have a base case, or never reaches it. Eventually, an infinite recursion causes a runtime error.

5.11 Keyboard input

The programs we have written so far are a bit rude in the sense that they accept no input from the user. They just do the same thing every time.

Python 2 provides a built-in function called raw_input that gets input from the keyboard.In Python 3, it is called input. When this function is called, the program stops and waits for the user to type something. When the user presses Return or Enter, the program resumes and raw_input returns what the user typed as a string.

(python3.0中的输入程序是 input() )

>>> text=input()
hello world
>>> print(text)
hello world
>>>


Before getting input from the user, it is a good idea to print a prompt telling the user what to input, input() can take a prompt as an argument:(在input()中直接填写参数,会当做输出作为提醒)

>>> name=input('HELLO!What is you name?\n')
HELLO!What is you name?
Think python!
>>> print(name)
Think python!


The sequence \n at the end of the prompt represents a newline, which is a special character that causes a line break. That’s why the user’s input appears below the prompt.(\n是换行符)

input()里的参数只能是string,否则会报错.

5.14 Exercises

Exercise 5.3.

Fermat’s Last Theorem says that there are no positive integers a, b, and c such that

an+bn=cn

for any values of n greater than 2.

1. Write a function named check_fermat that takes four parameters—a, b, c and n—and that checks to see if Fermat’s theorem holds. If n is greater than 2 and it turns out to be true that

an+bn=cn

the program should print, “Holy smokes, Fermat was wrong!” Otherwise the program should print, “No, that doesn’t work.”

#exercise 5.3-1 Fermat's Last Theorem
def check_fermat(a,b,c,n):
if n<=2: #排除n小于2
return 'error:n must be greater than 2'
if a<0 or b<0 or c<0:#a,b,c要为正整数
return 'error:a,b,c must be postive integers'
z=a**n+b**n-c**n
if z==0:
print('Holy smokes, Fermat was wrong!')
else:
print('No, that doesn’t work.')


2.Write a function that prompts the user to input values for a, b, c and n, converts them to integers, and uses check_fermat to check whether they violate(违反) Fermat’s theorem.

#exercise 5.3-2
def input_fermat():
a=input('baby please input a\n')
b=input('Now,the b\n')
c=input('input c\n')
n=input('OK,the last one n \n')
print(a,b,c,n)
#转换为整数
a=int(a)
b=int(b)
c=int(c)
n=int(n)
print(check_fermat(a,b,c,n))


Exercise 5.4.

If you are given three sticks(棍), you may or may not be able to arrange them in a triangle.For example, if one of the sticks is 12 inches long and the other two are one inch long, it is clear that you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle:

If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can. (If the sum of two lengths equals the third, they form what is called a “degenerate” triangle.)

Write a function named is_triangle that takes three integers as arguments, and that prints either “Yes” or “No” , depending on whether you can or cannot form a triangle from sticks with the given lengths.

#exercise 5.4-1
def is_triangle(a,b,c):
if a+b-c>=0:
if a+c-b>=0:
if b+c-a>=0:
return 'Yes'
return 'No'


Write a function that prompts the user to input three stick lengths, converts them to integers, and uses is_triangle to check whether sticks with the given lengths can form a triangle.

#exercise 5.4-2
def input_triangle():
a=input()
b=input()
c=input()
#转换为整数
a=int(a)
b=int(b)
c=int(c)
print(a,b,c)
print(type(a))
print(is_triangle(a,b,c))


Exercise 5.5.

需要结合chapter 4的内容来做,先放一下。

Exercise 5.6.

需要结合Exercise 5.5.的内容来做,先放一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 教程