我如何让python程序什么都不做?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19632728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:14:55  来源:igfitidea点击:

How do I get a python program to do nothing?

python

提问by Polli Ester

How do I get a Pythonprogram to do nothing with if statement?

如何让Python程序对 if 语句不做任何事情?

 if (num2 == num5):
     #No changes are made

回答by rlms

You could use a passstatement:

您可以使用以下pass语句:

if condition:
    pass

Python 2.x documentation

Python 2.x 文档

Python 3.x documentation

Python 3.x 文档

However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the ifstatement.

但是,我怀疑您是否想这样做,除非您只需要将某些内容作为占位符放入,直到您回来编写if语句的实际代码。

If you have something like this:

如果你有这样的事情:

if condition:        # condition in your case being `num2 == num5`
    pass
else:
    do_something()

You can in general change it to this:

您通常可以将其更改为:

if not condition:
    do_something()

But in this specific case you could (and should) do this:

但是在这种特定情况下,您可以(并且应该)这样做:

if num2 != num5:        # != is the not-equal-to operator
    do_something()

回答by Lix

The passcommand is what you are looking for. Use passfor any construct that you want to "ignore". Your example uses a conditional expression but you can do the same for almost anything.

pass命令就是您要查找的内容。使用pass任何构造,你想“忽略”。您的示例使用条件表达式,但您几乎可以对任何事情执行相同的操作。

For your specific use case, perhaps you'd want to test the opposite condition and only perform an action if the condition is false:

对于您的特定用例,也许您想测试相反的条件,并且仅在条件为假时才执行操作:

if num2 != num5:
    make_some_changes()

This will be the same as this:

这将与此相同:

if num2 == num5:
    pass
else:
    make_some_changes()

That way you won't even have to use passand you'll also be closer to adhering to the "Flatter is better than nested" convention in PEP20.

这样你甚至不必使用pass,你也将更接近遵守PEP20 中的“扁平优于嵌套”约定



You can read more about the passstatement in the documentation:

您可以在文档中阅读有关该pass声明的更多信息:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

pass 语句什么都不做。它可以在语法上需要语句但程序不需要操作时使用。

if condition:
    pass
try:
    make_some_changes()
except Exception:
    pass # do nothing
class Foo():
    pass # an empty class definition
def bar():
    pass # an empty function definition

回答by siddharth jambukiya

you can use pass inside if statement.

您可以在 if 语句中使用 pass 。

回答by Imaya

You can use continue

您可以使用继续

if condition:
    continue
else:
    #do something