博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
决策树编程python_Python如何制定决策:编程中的控制流简介
阅读量:2521 次
发布时间:2019-05-11

本文共 17097 字,大约阅读时间需要 56 分钟。

决策树编程python

by Ivan Leo

伊万·利奥(Ivan Leo)

Python如何制定决策:编程中的控制流简介 (How Python makes decisions: an introduction to Control Flow in programming)

What is control flow?

什么是控制流程?

I find it easy to think of control flow in 3 different categories

我发现很容易想到3个不同类别的控制流

  1. Loops ( While, Do while, for )

    循环(While,Do While,for)
  2. Decision-Making ( if-else)

    决策(if-else)
  3. Exception Handling (Continue, Try-Except, Pass, Break)

    异常处理(继续,试穿,通过,中断)

These 3 categories roughly sum up the different options available to us when we talk about Control Flow in most programming languages.

当我们谈论大多数编程语言中的“控制流”时,这3个类别大致总结了可供我们使用的不同选项。

So let’s jump right in.

因此,让我们直接进入。

循环 (Loops)

Loops are basically a simple set of instructions that gets repeated until a condition is met.

循环基本上是一组简单的指令,可以重复执行直到满足条件。

A good analogy to use for a loop is whisking cake batter:

循环的一个很好的类比是搅拌面糊:

Based on this , if we use a modern day mixer, 3 minutes is the perfect amount of time to mix the batter. If you were to give instructions to someone using this recipe, it would probably look something like this.

根据此 ,如果我们使用现代搅拌机,则3分钟是搅拌面糊的最佳时间。 如果您要向使用此食谱的人提供指导,它可能看起来像这样。

  1. Mix eggs, flour and secret recipe

    混合鸡蛋,面粉和秘方
  2. Start a stopwatch and begin mixing batter

    启动秒表并开始搅拌面糊
  3. Mix the batter until the stopwatch displays 3 minutes

    混合面糊直到秒表显示3分钟

If we were to translate this into psuedo-code, it would probably look something like this

如果我们将其转换为伪代码,则可能看起来像这样

#Start Timer<....code....>time = 0
While(time != 3 minutes):    time = newvalue    mix batter

In this case, we are using time to determine if we continue to mix our batter. But this doesn’t really help us take into account specific situations when we use different ingredients.

在这种情况下,我们将花费时间来确定是否继续搅拌面糊。 但这并不能真正帮助我们在使用不同成分时考虑到特定情况。

In this case, we have a few options

在这种情况下,我们有几种选择

  1. We could monitor the consistency of the batter

    我们可以监视面糊的一致性
  2. OR we could experiment with a whole bunch of ingredients, record the best times for each and then refer to this record each time we mix the cakes.

    或者,我们可以尝试一堆配料,记录每种配料的最佳时间,然后在我们每次混合蛋糕时都参考该记录。

Now stop for a moment and think, when would we use the first option and when would we use the second option?

现在停下来思考一下,何时使用第一个选项,何时使用第二个选项?

< Intentional Blank Left Here . Do stop and think for a while :) >

<有意留在这里的空白。 停下来思考一会儿:)>

The first option is more suited towards situations where we might encounter a lot of unpredictable combinations. It therefore makes sense to not only check time but also to add the safeguard of an additional parameter.

第一种选择更适合于我们可能遇到很多不可预测的组合的情况。 因此,不仅检查时间而且增加附加参数的安全性也是有意义的。

The second option is suited towards situations where we encounter repeated instances of multiple combinations. It’s commonly known as dynamic programming.

第二种选择适用于我们遇到多个组合的重复实例的情况。 通常称为动态编程。

In Dynamic Programming, each value is calculated once and then stored in a lookup table for future access. This helps to reduce the run time of future operations by reducing the lookup time, since the value doesn’t have to be recalculated, just looked up and returned.

在动态编程中,每个值只计算一次,然后存储在查找表中以供将来访问。 通过减少查找时间,这有助于减少将来操作的运行时间,因为不必重新计算该值,只需查找并返回即可。

Now let’s convert what we’ve learnt into code and examine what we can implement in python :)

现在,让我们将学习到的内容转换为代码,并检查可以在python中实现的内容:)

(Code)

In python, we have two main tools to use for looping

在python中,我们有两个主要的循环工具

  1. While Loops

    While循环
  2. For Loops

    对于循环

While循环 (While Loops)

While Loops allows us to run a command indefinitely.

While循环使我们可以无限期地运行命令。

x = 1y = 2
while(x=2):    print("x is looping")
while(y=2):    print("Y is looping")

In the code above, only the second while loop will evaluate while the first will not. When we run the code, we’ll get the following output

在上面的代码中,只有第二个while循环会求值,而第一个不会。 运行代码时,将获得以下输出

>>>python runapp.pyY is loopingY is loopingY is loopingY is looping....

Here’s what happens for the first variable.

这是第一个变量发生的情况。

As seen above, the while loops does not print x since it does not meet the condition stipulated in the first while loop.

如上所述,while循环不打印x,因为它不满足第一个while循环中规定的条件。

How about the second condition? Well it follows something like this:

第二个条件怎么样? 好吧,它遵循这样的东西:

As we can see, the while loop constantly checks if a condition is true and only executes if the specified condition is true.

如我们所见,while循环不断检查条件是否为真,并且仅在指定条件为真时执行。

Here are some common implementations in python:

以下是python中的一些常见实现:

#Asking for User Inputwhile True:    userinput = input("Please Input Your Name: ")    if userinput.isalpha():       break;
print("Hello %s"%(userinput))
#Dealing with dynamic Variables (i.e. Parameters that can change )no = int(input("Please Enter the number of Loops: "))i = 0
while(i

Let’s look through the two examples.

让我们看两个例子。

例子1 (Example 1)

This example code (refer above) is a sample of code we could use to grab some user input. As you code more advanced programs, you’ll be able to code more advanced programs that can check user input or do more things with user input, but for now, we’re gonna print “Hello <userinput>”:

此示例代码(请参见上文)是我们可以用来获取一些用户输入的代码示例。 在编写更高级的程序时,您将能够编写更高级的程序,这些程序可以检查用户输入或使用用户输入执行更多操作,但是现在,我们将打印“ Hello <userinput>”:

While True:

Since True is always true ( I know it’s a bit counterintuitive but bear with me), this loop will run forever. True can never not be True.

由于True始终为true(我知道这有点违反直觉,但请耐心接受),因此此循环将永远运行。 True永远不能不是True

userinput = input("Please Input Your Name: ")

This allows us to get some input from the user and store it as a string. We create a variable called userinput and store a reference to that stored string in memory. (If you’re unsure about what’s happening here, I’ve written an on variables in python, do check it out!)

这使我们能够从用户那里获得一些输入并将其存储为字符串。 我们创建一个名为userinput的变量,并将对该存储字符串的引用存储在内存中。 (如果您不确定这里发生了什么,我已经写了关于python中变量的 ,请检查一下!)

if userinput.isalpha():       break;

Now comes the magic sauce. The .isalpha() method allows us to check if a string solely consists of characters.

现在来了魔术酱。 .isalpha()方法允许我们检查字符串是否仅由字符组成。

#Sample Output"12a".isalpha() #This returns False"12".isalpha() #This returns False"abc".isalpha() #This returns True

Using this function allows us to check if the user has input a proper name that consists solely of characters in the alphabet.

使用此功能,我们可以检查用户是否输入了仅由字母字符组成的专有名称。

If the user has input a proper name, the break function then allows us to exit the loop.

如果用户输入了适当的名称,则break函数将允许我们退出循环。

print("Hello %s"%(userinput))

This then allows us to execute the final line of code, printing out the string “hello <userName>”.

然后,这使我们能够执行代码的最后一行,打印出字符串“ hello <userName>”。

示例2:循环多个循环 (Example 2 : Looping for a number of Loops)

no = int(input("Please Enter the number of Loops: "))

This first line of code allows the user to input a certain value from the command line before converting it to an integer. This is done using the int() value.

该第一行代码允许用户在将其转换为整数之前从命令行输入特定值。 这是使用int()值完成的。

i = 0
while(i

Next we initialise a variable i to 0 to keep track of the number of loops we want to run, printing the value of i each time:

接下来,我们将变量i初始化为0,以跟踪我们要运行的循环数,每次都打印i的值:

#Sample OutputPlease Enter the number of Loops: 501234

It’s helpful to think of a while loop as such

这样考虑一下while循环会很有帮助

while(test_expression):    

For Loops

对于循环

For Loops work a little differently than while Loops. Let’s examine the syntax

For循环的工作方式与while循环有所不同。 让我们检查一下语法

#Normal For LoopFor i in range(1,6,1):    
#Iteration Loopfor i in [1,2,3,4,5]:    

What’s happening here?

这里发生了什么事?

When you declare a For loop as seen in the first case , you are invoking what is known as a generator. This generates a list of numbers using the parameters you have specified.

如第一种情况所示,在声明For循环时,您正在调用所谓的生成器。 这将使用您指定的参数生成数字列表。

It’s helpful to think of the generator as a function that calls a list for now. While that’s not exactly how it works, it’s a close approximation. More to come on this topic!

将生成器视为现在调用列表的函数会很有帮助。 虽然这并不完全是它的工作原理,但这是一个近似值。 有关此主题的更多信息!

#This generates a list with values [1,2,3,4,5]For i in range(1,6,1):    

This generated list can then be iterated using the inbuilt iteration function in python. This just means that we can call each item in this list in the order they are stored in.

然后可以使用python中的内置迭代函数来迭代生成的列表。 这只是意味着我们可以按照存储顺序调用此列表中的每个项目。

The second example functions in a similar way. In this case however, we explicitly specify the list to be iterated over instead of generating it with the range function.

第二个示例以类似的方式运行。 但是,在这种情况下,我们明确指定要迭代的列表,而不是使用range函数生成该列表。

for i in [1,2,3,4,5]:    

Some useful cases

一些有用的案例

#Printing out items in a list
x = [...values...]for i in x:   print(i)
#Iterating Over items in a listy = [x**2 for i in x] #This is also known as list comprehension

Let’s examine these cases in greater detail!

让我们更详细地研究这些情况!

Example 1

例子1

x = [....values...]for i in x:

In this case, we are initialising a list called x with a certain number of variables. We then proceed to iterate over each value in x.

在这种情况下,我们正在初始化一个带有一定数量变量的名为x的列表。 然后,我们继续遍历x中的每个值。

print(i) #This prints out each value of x in its specified order

We call each value in x, in this case referred to as i, and print it out.

我们将x中的每个值(在这种情况下称为i)调用,并将其打印出来。

#Sample Outputx  = [1,2,3,4]for i in x:     print(i)
>>>python app.py1234

Example 2

例子2

y = [x**2 for i in x]

Let’s try to rewrite this in another form

让我们尝试以另一种形式重写它

for i in x:    y.append(x**2)
y = [x**2 for i in x]

These 2 are the same thing! However, list comprehensions tend to be faster.

这两个是同一回事! 但是,列表理解往往会更快。

做决定 (Decision-Making)

What comes to your mind when you think of decision-making while writing a program? For me, it’s definitely decision trees and flowcharts.

当您在编写程序时想到决策时,会想到什么? 对我来说,绝对是决策树和流程图。

While some of these (like the one below) are definitely ridiculous, I think they still offer a useful mental framework to visualise your program flow:

尽管其中一些(如以下示例)绝对是荒谬的,但我认为它们仍然提供了有用的思维框架来可视化您的程序流程:

I’ll use an analogy to talk about this before going on to show how to implement this using if-else and break-continue syntax.

在继续展示如何使用if-else和break-continue语法来实现这一点之前,我将使用一个类比来谈论它。

类比时间 (Analogy-Time)

Imagine that you’re trying to find the perfect restaurant for date night. You want to find something that is affordable and chic

想象一下,您正在寻找约会之夜的最佳餐厅。 您想找到实惠且时尚的东西

While you’re looking through trip advisor, your thought process would be something like this.

当您通过旅行顾问查找时,您的思考过程将是这样的。

You would only consider things that were cheap and chic. So every time you looked at a restaurant, you would check to see if it fit your criteria and eliminate those that did not.

您只会考虑便宜又时尚的东西。 因此,每次查看餐厅时,您都要检查它是否符合您的条件,并剔除不符合条件的人。

Similarly, decision making in a program works the same way. You set a bunch of possible scenarios and your program reacts accordingly.

同样,程序中的决策以相同的方式进行。 您设置了一堆可能的方案,并且程序会做出相应的React。

(code)

Let’s look at a simple program to find numbers which are multiples of two.

让我们看一个简单的程序,查找两个数字的倍数。

import random
x = random.randint(0,1000)
if x%2==0:
print(str(x)+" is a multiple of 2")
else:
print(str(x)+" is not a multiple of 2")

How does this program work?

该程序如何工作?

  1. We first generate a random number from 0 to 1000

    我们首先生成一个从0到1000的随机数
  2. We then divide this random number, x, by 2 and check if there is a remainder. ( % returns the remainder of a division )

    然后,我们将此随机数x除以2,然后检查是否有余数。 (%返回除法的余数)
  3. If there is no remainder, we print the statement “X is a multiple of 2”

    如果没有余数,我们将打印语句“ X是2的倍数”
  4. if there is a remainder, we print the statement “x is not a multiple of 2”

    如果有余数,则打印语句“ x不是2的倍数”

We know that all multiples of 2 follow the formula 2i where i is an integer. Therefore all multiples of 2 have to be divisible by 2. Hence, we use that as a way to evaluate if a number is a multiple of 2.

我们知道2的所有倍数都遵循公式2i,其中i是整数。 因此2的所有倍数必须被2整除。因此,我们将其用作评估数字是否为2的倍数的方法。

This can be visualised as a decision tree, as seen below.

可以将其可视化为决策树,如下所示。

As we can see, an if-else decision loop allows us to account for the values of our variables, allowing our program to return a different output w.r.t their values.

如我们所见,if-else决策循环使我们能够考虑变量的值,从而使程序可以通过其值返回不同的输出。

We can also use an if-else loop to account for the type of variables by modifying the above syntax slightly.

我们还可以使用if-else循环通过稍微修改上述语法来说明变量的类型。

def checking(n):
if type(n) == str:
print("String!")
elif type(n) == int:
print("Integer!")
else:
print("we're not sure what n is....")
x = [1,2,3,'a','bac',2.12]for i in x:    checking(i)

Pointers to note:

注意事项:

  1. We’ve used the elif statement in this context to add an additional possible case of n that we want to account for.

    在这种情况下,我们使用了elif语句来添加我们要考虑的n的其他可能情况。
  2. We’ve also used type as a condition to evaluate the variable instead of the original use of the value of the variable.

    我们还使用类型作为条件来评估变量,而不是最初使用变量的值。

异常处理 (Exception-Handling)

Sometimes in python, you will find that you’ll need to account for exceptions. These could be invalid operations (Eg. trying to divide 0 or stack overflow) or a class of values that you simply aren’t interested in.

有时在python中,您会发现需要考虑例外情况。 这些可能是无效的操作(例如,试图除以0或堆栈溢出)或您根本不感兴趣的一类值。

In these cases, we can use

在这种情况下,我们可以使用

  1. Continue

    继续
  2. Pass

    通过
  3. Try-except

    试穿除外
  4. Break

    打破

I’ll try to give a brief overview of the usage of these exception handling operations.

我将简要概述这些异常处理操作的用法。

继续 (Continue)

Look at the code below and try to guess what continue does:

查看下面的代码,并尝试猜测继续执行的操作:

y = [1,2,3,4,5,6,6,7,8]
x = []
for i in y:
if i in x:
continue
else:
x.append(i)     print(i)
print(x)

If you guessed that it basically skips the rest of the chunk of code, you’re right! Continue does just that.

如果您猜到它基本上会跳过其余的代码块,那么您是对的! 继续就是这样。

In the code above, we are trying to remove the duplicate values in y. We do so in the code using this process

在上面的代码中,我们试图删除y中的重复值。 我们使用此过程在代码中执行此操作

  1. We check if the variable, i, that we are evaluating is within the new list x.

    我们检查正在评估的变量i是否在新列表x内。
  2. If it is within the new list x, we “continue” and proceed to evaluate the next variable within list y.

    如果它在新列表x中,则我们“继续”并继续求值列表y中的下一个变量。
  3. if it is not within the new list x, we do not “continue” and instead proceed to append the variable to list x.

    如果它不在新列表x中,则我们不会“继续”,而是继续将变量追加到列表x中。

This eventually helps us to remove all the duplicate variables within x.

这最终将帮助我们删除x中所有重复的变量。

通过 (Pass)

y = [1,2,3,4,5,6,6,7,8]
x = []
for i in y:
if i in x:
pass
else:
x.append(i)    print(i)
print(x)

If you were to run the code, you would also notice that all of the duplicate variables were printed! This is a key difference between pass and continue.

如果要运行代码,您还会注意到所有重复的变量都已打印! 这是通过和继续之间的关键区别。

This difference becomes useful if you are trying to run additional operations on the non-duplicate variables (eg. get a sum).

如果您尝试对非重复变量运行其他操作(例如,求和),则此区别将非常有用。

打破 (Break)

Break does what it says. It breaks your program or sub-program when you meet an exception.

打破了它所说的。 遇到异常时,它将中断您的程序或子程序。

Here’s a useful example of break:

这是一个有用的中断示例:

x = [1,3,5,7,2,3,5,7]
count = 0
for i in range(len(x)):
if x[i]%2==0:
print("There is an even number at index " + str(i))
break
else:
continue

In this example, we are trying to find the index of the first even number in our list x. Break allows us to do so by exiting the loop prematurely!

在此示例中,我们试图找到列表x中第一个偶数的索引。 Break允许我们过早退出循环!

试穿 (Try-Except)

Try-Except syntax is especially useful when it comes to dealing with errors in reading files or evaluating syntax. Some of the common exception errors are

当处理读取文件或评估语法中的错误时,Try-Except语法特别有用。 一些常见的异常错误是

  1. IOError: An inability to open the file

    IOError:无法打开文件
  2. ImportError: Python cannot find and open the module you want to import

    ImportError:Python无法找到并打开您要导入的模块
  3. ValueError: When you pass a value into a function with the wrong type or value

    ValueError:当您将值传递给类型或值错误的函数时
  4. KeyboardInterrupt: When you prematurely terminate your program

    KeyboardInterrupt:过早终止程序时
  5. EOFerror: When you’ve reached the end of the file

    EOFerror:到达文件末尾时

Here’s an example of us trying to check for a ValueError:

这是我们尝试检查ValueError的示例:

try:
x = int(input("Please input some numbers: "))
print(x)
except ValueError as ve:
print("Please input numbers. NUMBERS not letters")

This program works because strings and letters cannot be coerced into integers. (Unless they’re integers which have been stored as strings i.e. “2”, “3” etc.)

该程序有效,因为不能将字符串和字母强制转换为整数。 (除非它们是已存储为字符串的整数,即“ 2”,“ 3”等。)

For those working with importing files, you might be familiar with ImportErrors. These can be accounted for by using the following syntax:

对于那些使用导入文件的人,您可能熟悉ImportErrors。 这些可以通过使用以下语法来解决:

try:
f = open('nofile.txt')
except FileNotFoundError:
print("Erm...there's no such file man")

The Try-except syntax can be thought of as such.

Try-except语法可以这样考虑。

try:    except 
:
except
:

结论 (Conclusion)

This sorta sums up basic decision making in Python and many other programming languages. While the exact syntax will definitely differ, the basic principles are roughly the same.

这种归纳总结了Python和许多其他编程语言中的基本决策。 尽管确切的语法肯定会有所不同,但基本原理大致相同。

Once you’ve got the hang of control flow, you’ll be able to build programs that will make a big difference and can work the way you want! :)

一旦掌握了控制流程,就可以构建将产生重大变化并可以按您想要的方式工作的程序! :)

If you’ll like to read more about Variables in Python, check out an article I wrote on them !

如果您想了解有关Python中变量的更多信息,请查看我在写的关于它们的文章!

翻译自:

决策树编程python

转载地址:http://afewd.baihongyu.com/

你可能感兴趣的文章
再也不学AJAX了!(三)跨域获取资源 ③ - WebSocket & postMessage
查看>>
pycharm设置python文件颜色
查看>>
不换行输出的两种方式
查看>>
贵在坚持不懈
查看>>
hdu 1251 统计难题
查看>>
java中关于String 类型数据 的存储方式
查看>>
javascript中的with语句
查看>>
常用设计模式:装饰者模式
查看>>
python接口自动化--get请求
查看>>
ajax 上传文件
查看>>
lintcode-easy-Flatten Binary Tree to Linked List
查看>>
从远程队列中读取消息
查看>>
typescript 接口的新认识
查看>>
java常见面试题及三大框架面试
查看>>
懒惰的肥兔博文导读
查看>>
[db] mongodb 存取修改简单小实例
查看>>
面试百题003——求子数组的最大和
查看>>
jq.validate 自定义验证两个日期
查看>>
公布一个以前写的随机数生成的方法
查看>>
AtCoder Regular Contest 077 被虐记&题解
查看>>