Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python - pass Statement



Python pass Statement

Pythonpass statement is used when a statement is required syntactically but you do not want any command or code to execute. It is a null which means nothing happens when it executes. This is also useful in places where piece of code will be added later, but a placeholder is required to ensure the program runs without errors.

For instance, in a function or class definition where the implementation is yet to be written,pass statement can be used to avoid theSyntaxError. Additionally, it can also serve as a placeholder in control flow statements like for and while loops.

Syntax of pass Statement

Following is the syntax of Pythonpass statement

pass

Example of pass Statement

The following code shows how you can use thepass statement in Python −

for letter in 'Python':   if letter == 'h':      pass      print ('This is pass block')   print ('Current Letter :', letter)print ("Good bye!")

When the above code is executed, it produces the followingoutput

Current Letter : PCurrent Letter : yCurrent Letter : tThis is pass blockCurrent Letter : hCurrent Letter : oCurrent Letter : nGood bye!

Dumpy Infinite Loop with pass Statement

This is simple enough to create an infiniteloop usingpass statement in Python.

Example

If you want to code an infinite loop that does nothing each time through, do it as shown below −

while True: pass  # Type Ctrl-C to stop

Because the body of the loop is just an empty statement, Python gets stuck in this loop.

Using Ellipses (...) as pass Statement Alternative

Python 3.X allowsellipses (coded as three consecutive dots ...) to be used in place ofpass statement. Both serve as placeholders for code that are going to be written later.

Example

For example if wecreate a function which does not do anything especially for code to be filled in later, then we can make use of...

def func1():   # Alternative to pass   ...                   # Works on same line toodef func2(): ...           # Does nothing if calledfunc1()                  func2()
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp