Showing posts with label python control statement. Show all posts
Showing posts with label python control statement. Show all posts

Saturday, December 3, 2022

Ternary Operator in Python

In Python there is no ternary operator in the form of (:?) as in programming languages like c, c++, Java. Python ternary operator is an if-else conditional expression written in a single line.

Form of Python ternary operator

Syntax for Python Ternary Operator is as given below-

[when_expr_true] if [conditional_expression] else [when_expr_false]

Initially conditional_expression is evaluated, if it is true then the ‘when_expr_true’ value is used, if false then ‘when_expr_false’ value is used.

Python ternary operator example

Let’s see an example to clarify the ternary operator usage. Here is a condition written using traditional if-else statement.

    if age > 18:
        msg = 'can vote'
    else:
        msg = "can't vote"
    print(msg)

Using ternary operator same condition can be written in one line as-

msg = 'can vote' if age > 18 else "can't vote"

As you can see using Python ternary operator you can test condition in a single line making the code concise and more readable. That’s the advantage of using ternary operator.

Nested Python ternary operator

Ternary operator can be nested too but beware that with nested ternary operators you lose the very advantage for which you tend to use ternary operator; readability.

For example following if-elif suite

  if a > b:
      print('a is greater than b')
  elif a < b:
      print('a is less than b')
  else:
      print('a and b are equal')

can be written using nested ternary operator-

msg = 'a is greater than b' if(a > b) else 'a is less than b' if(a < b) else 'a and b are equal'

Using ternary operator with tuple, dictionary

There is also a short form to be used with tuple and dictionary based on the fact that conditional_expression is evaluated first.

1. Consider the following example for tuple.

def display_msg(age):
    print('Age is', age)
    t = ("can't vote", "can vote")
    msg = t[age > 18]
    print(msg)


display_msg(20)
display_msg(8)

Output

Age is 20
can vote
Age is 8
can't vote

As you can see false value is stored first in the tuple and then the true value. It is because of the fact that false = 0 and true = 1. Expression t[age > 18] evaluates to t[0] if expression is false and it evaluates to t[1] if expression is true.

2. For dictionary you can store key value pair for true and false.

def display_msg(age):
    print('Age is', age)
    d = {True: "can vote", False: "can't vote"}
    msg = d[age > 18]
    print(msg)


display_msg(20)
display_msg(8)

Output

Age is 20
can vote
Age is 8
can't vote

That's all for this topic Ternary Operator in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python for Loop With Examples
  2. pass Statement in Python
  3. Python First Program - Hello World
  4. Class And Object in Python
  5. self in Python

You may also like-

  1. Python Exception Handling Tutorial
  2. Abstract Class in Python
  3. Strings in Python With Method Examples
  4. Python Program to Count Occurrences of Each Character in a String
  5. Transaction Management in Java-JDBC
  6. Java Stream flatMap() Method
  7. Marker Interface in Java
  8. How to Create PDF in Java Using OpenPDF

Tuesday, July 5, 2022

Python break Statement With Examples

In this tutorial you’ll learn about break statement in Python which is used inside a for loop or while loop to terminate the loop when break statement is executed. When break statement is encountered inside a loop control comes out of the loop and the next statement after the loop is executed.

Common use of break statement is to use it along with some condition in the loop using if statement. When the condition is true the break statement is executed resulting in termination of the loop.

Break statement when used in nested loops results in the termination of the innermost loop in whose scope it is used.

break statement Python examples

1- Using break statement with for loop in Python. In the example a tuple is iterated using a for loop to search for a specific number as soon as that number is found you need to break out of for loop.

numbers = (89, 102, 0, 234, 67, 10, 333, 32)
flag = False
for num in numbers:
    if num == 10:
        flag = True
        break
if flag:
    print('Number found in tuple')
else:
    print('Number not found in tuple')

Output

Number found in tuple

As you can see here break statement is used inside for loop to break out of loop when the condition is satisfied. Note that searching for an element in a tuple can be done in a more compact way like given below, above example is more of an illustration of break statement.

if searched_num in numbers:
    print('Number found in tuple')
else:
    print('Number not found in tuple')

2- Using break statement in Python with while loop. In the example there is an infinite while loop that is used to prompt user for an input. Condition here is that entered number should be greater than 10 to break out of while loop otherwise prompt user again to enter valid input.

while True:
   num = int(input("Enter a number greater than 10: "))
   # condition for breaking out of loop
   if num > 10:
       break
   print("Please enter a number greater than 10...")

print("Entered number is", num)

Output

Enter a number greater than 10: 7
Please enter a number greater than 10...
Enter a number greater than 10: 11
Entered number is 11

3- In this example we’ll see how to use break statement with nested loops. There are 2 for loops in the example and break statement is used in the scope of inner for loop so it breaks out of that loop when the condition is true.

for i in range(1, 6):
    print(i, "- ", end='')
    for j in range(1, 10):
        print('*', end='')
        # print only 5 times then break
        if j >= 5:
            break
    # move to next line now
    print()

Output

1 - *****
2 - *****
3 - *****
4 - *****
5 - *****

As you can see though the range of inner loop is (1..10) but it breaks out when j’s value is 5 because of the break statement. The end='' used in print statement ensures that the cursor doesn’t move to next line after printing in each iteration.

That's all for this topic Python break Statement With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python continue Statement With Examples
  2. pass Statement in Python
  3. Python assert Statement
  4. Python First Program - Hello World
  5. Python String split() Method

You may also like-

  1. Name Mangling in Python
  2. Inheritance in Python
  3. Class And Object in Python
  4. Python Generator, Generator Expression, Yield Statement
  5. Java Variable Types With Examples
  6. Ternary Operator in Java With Examples
  7. How to Convert Date And Time Between Different Time-Zones in Java
  8. Spring Constructor Based Dependency Injection

Wednesday, June 29, 2022

Python Conditional Statement - if, elif, else Statements

Conditional statement is used to execute a set of statements based on whether the condition is true or not. For conditional execution of statements if statement is used in Python. You can also have conditional branching using if-else and if-elif-else statements in Python.

Python if-elif-else statement syntax

General syntax for if-elif-else statement in Python is as follows-

if boolean_expression1:
 suite1
elif boolean_expression2:
 suite2
...
elif boolean_expressionN:
 suiteN
else:
 else-suite

Note that there can be zero or more elif statements, even else clause is optional. So we’ll start with if statement examples and move towards full conditional branching using if-elif-else statement in Python.


if statement in Python

if statement is used to execute the body of code when the condition evaluates to true. If it is false then the indented statements (if suite) is not executed.

Python if statement syntax

if condition:
 if-suite

Here condition is a boolean expression that evaluates to either true or false. If it evaluates to true if-suite is executed, if expression evaluates to false then the suite if not executed.

Python if statement example

def myfunction():
    x = 10
    y = 12
    if x < y:
        print('x is less than y')
    print('After executing if statement')

myfunction()

Output

x is less than y
After executing if statement

Indentation for grouping statements in Python

To understand conditional statements and loops in Python better you should also have an understanding of how Python used indentation for grouping statements.

Indentation refers to the white spaces at the beginning of the statement. In Python statements that are indented to the same level are part of the same group known as suite.

By default Python uses 4 spaces for indentation which is configurable.

Indentation in the context of if statement can be explained as given below-

Python if else statement

if-else statement in Python

Moving on from a simple if statement towards conditional branching there is if-else statement in Python. In if-else statement if-suite is executed if the condition evaluates to true otherwise else-suite is executed.

Python if-else statement syntax

if condition:
 if-suite
else
 else-suite

Python if-else statement example

def myfunction():
    x = 15
    y = 12
    if x < y:
        diff = y - x
        print('In if difference is-', diff)
    else:
        diff = x - y
        print('In else difference is-', diff)

    print('After executing if-else statement')

myfunction()

Output

In else difference is- 3
After executing if-else statement

Condition (x < y) evaluates to false therefore else statement is executed.

if-elif-else statement in Python

If you have conditional branching based on multiple conditions then you can use if-elif-else statement in Python.

Python if-elif-else statement syntax

if condition1:
 if-suite-1
elif condition2:
 elif-suite-2
elif condition3:
 elif-suite-3
.....
.....
elif conditionN:
 elif-suite-N
else:
 else-suite

Initially condition1 is evaluated if it is true then if-suite is executed, if condition1 is false then condition2 is evaluated if that is true then elif-suite-2 is executed. If condition 2 is false then condition 3 is evaluated and so on. If none of the condition is true then else-suite is executed.

Python if-elif-else statement example

def myfunction():
    invoice_amount = 2000
    tarrif = 0
    if invoice_amount > 2500 and zone == "Americas":
        tarrif = 100
    elif invoice_amount > 2500 and zone == "EU":
        tarrif = 150
    elif invoice_amount > 2500 and zone == "APAC":
        tarrif = 200
    else:
        tarrif = 250
    print('Tarrif is', tarrif)

myfunction()

Output

Tarrif is 250

Nested if statement in Python

You can have nested if-elif-else statement with in if statement upto any depth, only thing is that each nested if statement has to be indented properly.

Nested if statement Python example

def myfunction():
    x = 65
    if x >= 50:
        # nested if statement
        if x > 75 and x <= 99:
            print('x is greater than 75 but less than 100')
        elif x >= 50 and x <= 75:
             print('x is greater than or equal to 50 but less than or equal to 75')
        else:
            print('x is greater than 100')
    else:
        print('x is less than 50')

myfunction()

Output

x is greater than or equal to 50 but less than or equal to 75

That's all for this topic Python Conditional Statement - if, elif, else Statements. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python while Loop With Examples
  2. Ternary Operator in Python
  3. Abstraction in Python
  4. Magic Methods in Python With Examples
  5. Python Functions : Returning Multiple Values

You may also like-

  1. Abstract Class in Python
  2. Python String join() Method
  3. Python Program to Check Armstrong Number
  4. Automatic Numeric Type Promotion in Java
  5. Java join() Method - Joining Strings
  6. equals() And hashCode() Methods in Java
  7. Spring depends-on Attribute and @DependsOn With Examples
  8. Angular First App - Hello world Example

Sunday, June 26, 2022

Python while Loop With Examples

In Python programming language there are two loops for..in loop and while loop. In this tutorial you’ll learn about while loop in Python which is used to repeatedly execute the loop body while the given condition evaluates to true.


Syntax of Python while loop

Full syntax of while loop in Python is as given below.

while condition:
 while_suite
else:
 else_suite

Here condition is a boolean expression that evaluates to either true or false. Initially condition is checked and if it evaluates to true the statements making up the while_suite are executed. Control then goes back to the start of the loop and condition is checked again if it evaluates to true the statements making up the while_suite are executed again. Same process is followed repeatedly while the condition evaluates to true. When the condition evaluates to false control comes out of the while loop.

The else statement in the while loop is optional. The else_suite is executed if the while loop terminates normally and if the optional else statement is present.

while loop flow

Python while Loop

Python while loop examples

1- To display numbers 1..10 using while loop in Python.

i = 1
while i <= 10:
    print(i)
    i+=1

print('Out of while loop')

Output

1
2
3
4
5
6
7
8
9
10
Out of while loop

In the example i <= 10 is the condition for the while loop. While this condition is true loop body which are the following two indented statements are executed.

    print(i)
    i+=1

When value of i becomes greater than 10 control comes out of while loop.

2- Displaying table of 5 using while loop in Python.

i = 1
while i <= 10:
    print(5, 'X', i, '=', (i*5))
    i+=1

Output

5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

Python while loop with else statement

In Python, while loop has an optional else statement too. If the while loop runs till completion and terminates the else-suite is executed.

If while loop doesn’t run completely because of any of the following reason, else statement is not executed.

  • while loop is terminated abruptly due to a break statement
  • while loop is terminated abruptly due to a return statement
  • if an exception is raised

In the following example else_suite is executed as the while loop completes normally.

i = 1
while i <= 10:
    print(i)
    i+=1
else:
    print('in else block')

Output

1
2
3
4
5
6
7
8
9
10
in else block

Now, if we break the while loop abruptly, else-suite won’t be executed.

i = 1
while i <= 10:
    print(i)
    i+=1
    if i > 5:
        break
else:
    print('in else block')

Output

1
2
3
4
5

Nested while loop in Python

while loop can be nested which means you can have one while loop inside another (or even for loop inside while loop). In the nested loops for each iteration of the outer while loop, inner while loop is iterated while the condition of inner while loop evaluates to true.

Python Nested while loop example

Suppose you want to print inverted right triangle using asterisk (*) symbol, following example shows one way to do it using nested while loops in Python.

rows = 6
while rows > 0:
    j = 1
    # inner while
    while j <= rows:
        # end='' to ensure print remains on the same line
        print('* ', end='')
        j += 1
    # for outer while
    rows = rows - 1
    print()

Output

* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
* 

That's all for this topic Python while Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Conditional Statement - if, elif, else Statements
  2. Python continue Statement With Examples
  3. Python First Program - Hello World
  4. Ternary Operator in Python
  5. Polymorphism in Python

You may also like-

  1. Local, Nonlocal And Global Variables in Python
  2. List Comprehension in Python With Examples
  3. Python Program to Check Whether String is Palindrome or Not
  4. Constructor Overloading in Java
  5. Private Methods in Java Interface
  6. Matrix Multiplication Java Program
  7. How to Sort an ArrayList in Descending Order in Java
  8. Sending Email Using Spring Framework Example

Thursday, June 23, 2022

Python return Statement With Examples

In this tutorial you’ll learn about return statement in Python which is used to exit a function and return a value.

Note that returning a return result from a function is not mandatory, return is not required if a function does not return a value. If no explicit return statement is used in a function, return None is implicitly returned by the function.

A return statement may or may not return a value. If a return statement is followed by a value (or expression) that value or the value after evaluating the expression is returned. If return statement without any value is used then the execution of the function terminates even if there are more statements after the return statement.

Python return statement examples

Let’s try to understand usage of return statement with some examples.

1- Return value from a function using return statement.

def sum(num1, num2):
    print('in sum function')
    return num1+num2

result = sum(16, 5)
print('sum is', result)

Output

in sum function
sum is 21

In the function return statement is followed by an arithmetic expression num1+num2, that expression is evaluated and the value is returned from the function.

2- A function with no return statement. You may have a function that doesn’t return any value in that case you need not write the return statement. If there is no return statement Python implicitly returns None.

def sum(num1, num2):
    print('in sum function')
    print('sum is', num1+num2)

sum(16, 5)

Output

in sum function
sum is 21

3- Using Python return statement with no return value. In the function an array is iterated to find a passed value, as soon as that value is found come out of the function using return.

from array import *
def find_in_array(arr, value):
    for i in arr:
        if i == value:
            print(value, 'found in array')
            #come out of function as value is found
            return
        
a = array('i', [3,4,5,6,7])
find_value = 5
find_in_array(a, find_value)

Output

5 found in array

4- If there are statements after return in a function those are not executed because the execution of the function is terminated when the return statement is encountered.

def sum(num1, num2):
    sum = num1+num2
    return sum
    #not reachable
    print('in sum function after calculation')

result = sum(16, 5)
print('sum is', result)

5- In Python, return statement can return multiple values. Multiple values can be returned as a tuple, list or dictionary. When multiple values are returned as comma separated values from a function, actually a tuple is returned.

def sum(num1, num2):
    sum = num1+num2
    # returning multiple values
    return sum,num1,num2 # can also be written as (sum, num1, num2)


result, num1, num2 = sum(16, 5)
print('sum of %d and %d is %d' % (num1, num2, result))

Output

sum of 16 and 5 is 21

That's all for this topic Python return Statement With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python assert Statement
  2. pass Statement in Python
  3. Polymorphism in Python
  4. Class And Object in Python
  5. Namespace And Variable Scope in Python

You may also like-

  1. Removing Spaces From String in Python
  2. Global Keyword in Python With Examples
  3. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  4. List Comprehension in Python With Examples
  5. First Java Program - Hello World Java Program
  6. instanceof Operator in Java With Examples
  7. Array Rotation Java Program
  8. Benefits, Disadvantages And Limitations of Autowiring in Spring

Python assert Statement

In this tutorial you’ll learn about assert statement in Python which is used to assert the trueness of a condition.

Assertion is a boolean expressions to check if the condition is true or false. In case it is true, the program does nothing and move to the next line of code. If the condition is false, the program stops and throws an error.

Python assert statement

In Python there is an assert statement to assert if a given condition is true or not. If the condition is false execution stops and AssertionError is raised.

Syntax of assert statement in Python-

assert expression, message

Here message is optional, if no message is passed then the program stops and raises AssertionError if the condition is false.

If message is passed along with the assert statement then the program stops and raises AssertionError + display error message, if the condition is false.

Assert statement example

1- Using assert statement without any message.

def divide(num1, num2):
    assert num2 != 0
    result = num1/num2
    print('Result-', result)

divide(16, 0)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 6, in <module>
    divide(16, 0)
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 2, in divide
    assert num2 != 0
AssertionError

In the example there is an assert statement with a condition that the second argument should not be zero. Since the assert condition returns false AssertionError is raised.

2- When the condition in assert statement is true.
def divide(num1, num2):
    assert num2 != 0
    result = num1/num2
    print('Result-', result)

divide(16, 2)

Output

Result- 8.0

3- Using assert statement with a message. If an optional message is passed then the message is also displayed if the condition is false.

def divide(num1, num2):
    assert num2 != 0, "Second argument can't be passed as zero"
    result = num1/num2
    print('Result-', result)

divide(16, 0)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 6, in <module>
    divide(16, 0)
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 2, in divide
    assert num2 != 0, "Second argument can't be passed as zero"
AssertionError: Second argument can't be passed as zero

Using assert statement in Python

Assert statement is useful for debugging or quick sanity testing. It should not be used for data validation in the code.

By using PYTHONOPTIMIZE environment variable or by using -O or -OO assert statements can be disabled. In that case assert statements won’t be executed and using them for any critical data validation in your code may cause serious issues.

In Python internally any assert statement is equivalent to-

if __debug__:
    if not expression: raise AssertionError

The built-in variable __debug__ is False when optimization is requested (command line option -O) which means no assert statements are executed.

That's all for this topic Python assert Statement. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python continue Statement With Examples
  2. Python break Statement With Examples
  3. Operator Overloading in Python
  4. Global Keyword in Python With Examples
  5. Name Mangling in Python

You may also like-

  1. String Length in Python - len() Function
  2. Magic Methods in Python With Examples
  3. Python Program to Display Fibonacci Series
  4. Nested Try Statements in Java Exception Handling
  5. Race Condition in Java Multi-Threading
  6. Printing Numbers in Sequence Using Threads Java Program
  7. How to Read Properties File in Spring Framework
  8. What is Hadoop Distributed File System (HDFS)

Wednesday, June 22, 2022

Python continue Statement With Examples

In this tutorial you’ll learn about continue statement in Python which is used inside a for loop or while loop to go back to the beginning of the loop. When continue statement is encountered in a loop control transfers to the beginning of the loop, any subsequent statements with in the loop are not executed for that iteration.

Common use of continue statement is to use it along with if condition in the loop. When the condition is true the continue statement is executed resulting in next iteration of the loop.

continue statement Python examples

1- Using continue statement with for loop in Python. In the example a for loop in range 1..10 is executed and it prints only odd numbers.

for i in range(1, 10):
    # Completely divisble by 2 means even number
    # in that case continue with next iteration
    if i%2 == 0:
        continue
    print(i)

print('after loop')

Output

1
3
5
7
9
after loop

2- Using continue statement in Python with while loop. In the example while loop is iterated to print numbers 1..10 except numbers 5 and 6. In that case you can have an if condition to continue to next iteration when i is greater than 4 and less than 7.

i = 0
while i < 10:
    i += 1
    if i > 4 and i < 7:
        continue
    print(i)

Output

1
2
3
4
7
8
9
10

3- Here is another example of using continue statement with infinite while loop. In the example there is an infinite while loop that is used to prompt user for an input. Condition here is that entered number should be greater than 10, if entered number is not greater than 10 then continue the loop else break out of the loop.

while True:
    num = int(input("Enter a number greater than 10: "))
    # condition to continue loop
    if num < 10:
        print("Please enter a number greater than 10...")
        continue
    else:
        break

print("Entered number is", num)

Output

Enter a number greater than 10: 5
Please enter a number greater than 10...
Enter a number greater than 10: 16
Entered number is 16

That's all for this topic Python continue Statement With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python break Statement With Examples
  2. Python return Statement With Examples
  3. pass Statement in Python
  4. Encapsulation in Python
  5. Namespace And Variable Scope in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Strings in Python With Method Examples
  3. List in Python With Examples
  4. What Are JVM, JRE And JDK in Java
  5. Equality And Relational Operators in Java
  6. Lambda Expressions in Java 8
  7. What is Hadoop Distributed File System (HDFS)
  8. Circular Dependency in Spring Framework

Sunday, June 19, 2022

Python for Loop With Examples

In Python programming language there are two loops for..in loop and while loop. In this tutorial you’ll learn about for loop in Python is used to iterate over a sequence (like string, list, tuple).


Syntax of Python for loop

for var in sequence:
 for loop body
else:
 else_suite

All the elements in the sequence are iterated one by one using the for loop, in each iteration element is assigned to the “var” and the for loop body is executed.

The for loop in Python also includes an optional else clause.

for loop flow

Python for Loop

Python for loop examples

1- If you want to display characters of a String using for loop in Python.

str = 'Test'
for ch in str:
    print(ch)

Output

T
e
s
t

2- Display all the elements in a list using for loop in Python.

cities = ['New York', 'London', 'Mumbai', 'Paris', 'Madrid']
for city in cities:
    print(city)

Output

New York
London
Mumbai
Paris
Madrid

for loop with range sequence type

The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.

Syntax of range is-

range([start,] stop[, step])

If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0.

1- Iterating 0..9 using range and for loop.

for i in range(10):
    print(i)

Output

0
1
2
3
4
5
6
7
8
9

Since start and step arguments are omitted in the range so by default step is 1 and start is 0.

2- Display odd numbers between 1 and 10 using range and for loop in Python.

for i in range(1, 10, 2):
    print(i)

Output

1
3
5
7
9

Here start argument is 1 and step is 2.

3- To display all the elements in a list using index.

Using len function you can get the total number of elements in the list which becomes an argument for range.

cities = ['New York', 'London', 'Mumbai', 'Paris', 'Madrid']
for i in range(len(cities)):
    print(cities[i])

Output

New York
London
Mumbai
Paris
Madrid

Python for loop with else statement

In Python for loop has an optional else statement too. If the for loop runs till completion and terminates the else-suite is executed.

If for loop doesn’t run completely because of any of the following reason, else statement is not executed.

  • for loop is terminated abruptly due to a break statement
  • for loop is terminated abruptly due to a return statement
  • if an exception is raised

Here is an example showing a scenario where for loop with else statement can come handy. If you want to implement a functionality to find an element in array. If element is found in the array then its index is returned otherwise -1 is returned.

In this scenario you can use else statement with python for loop. If an element is found you will return its index so else suite won’t be executed. If for loop runs till completion that would mean searched element is not found in the array in that case else suite is executed and -1 is returned.

from array import *
def find_in_array(array, value):
    for index, e in enumerate(array):
        if e == value:
            return index
    # else associated with for loop
    else:
        return -1

a = array('i', [3,4,5,6,7])
find_value = 4
index = find_in_array(a, find_value)
if index != -1:
    print(find_value, 'found in array at index', index)
else:
    print(find_value, 'not found in array')

Output

4 found in array at index 1

Nested for loop

for loop can be nested which means you can have one for loop inside another. In the nested loops for each iteration of the outer for loop, inner for loop is iterated for the given range of elements.

Python Nested for loop example

In the example a pyramid pattern using * is displayed using nested for loops.

rows = 6
for i in range (1, rows):
    for j in range (0, rows -i):
        #print spaces, end='' ensures control 
        # remains on the same line
        print(' ', end='')
    for k in range (0, i):
        print('* ', end='')
    print()

Output

     * 
    * * 
   * * * 
  * * * * 
 * * * * * 

Though in Python same pyramid pattern can be displayed very elegantly using a single for loop.

rows = 6
for i in range (1, rows):
    #repeat space for given times 
    print(' '*rows, end='')
    print('* '*(i))
    rows = rows -1

That's all for this topic Python for Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Conditional Statement - if, elif, else Statements
  2. Python return Statement With Examples
  3. Python break Statement With Examples
  4. Method Overriding in Python
  5. Name Mangling in Python

You may also like-

  1. Passing Object of The Class as Parameter in Python
  2. Nonlocal Keyword in Python With Examples
  3. String Slicing in Python
  4. Python Exception Handling Tutorial
  5. Association, Aggregation And Composition in Java
  6. Why Class Name And File Name Should be Same in Java
  7. Just In Time Compiler (JIT) in Java
  8. BeanFactoryPostProcessor in Spring Framework

Thursday, June 16, 2022

pass Statement in Python

In this tutorial you'll learn about pass statement in Python which acts as a placeholder.

Python pass statement

pass statement is a null operation, when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but you don't want to do any operation.

For example you have an array of numbers and you want to display only those numbers which are less than 100.

numbers = [89, 102, 45, 234, 67, 10, 333, 32]
for num in numbers:
  if num > 100:
    #do nothing
    pass
  else:
    print('number is', num)

Output

number is 89
number is 45
number is 67
number is 10
number is 32

As you can see here if-else statement is used to check whether number is greater than or 100 or not. In case it is then you do nothing and that is indicated by using pass statement.

In most of the cases where pass statement is used you can very well write the code without using pass statement too but using pass statement does increase readability.

Python pass statement also ensures that indentation error is not thrown. For example suppose there is a Person class where you have a method to display Person data. You are planning to implement method that will fetch Person details from DB so you want to keep a method as a TODO reminder.

class Person:
    def __init__(self, name, age):
        print('init called')
        self.name = name
        self.age = age

    def display(self):
        print('in display')
        print("Name-", self.name)
        print("Age-", self.age)

    def retrieveData(self):
        #TODO has to be implemented to fetch details from DB

person = Person('John', 40)
person.display()

But running this class gives an error “IndentationError: expected an indented block

In such case adding pass statement with unimplemented method ensures that IndentationError is not thrown.

    def retrieveData(self):
        #TODO has to be implemented to fetch details from DB
        pass

So, you can see that Python pass statement can be used where you need a place holder be it with in a for loop, while loop or if-else statement, after def or even after class and in exception handling too.

pass statement with class

Suppose you are deriving from Exception class to create a user defined exception class with out adding new behavior, then you can just use pass statement.

class MyException(Exception):
    pass

pass statement with exception handling

If you don’t want to do anything for a specific type of Exception after catching it you can use pass statement.

numbers = [89, 102, 0, 234, 67, 10, 333, 32]
for num in numbers:
    try:
        result = 1000/num
        print('Result is',result)
    except ZeroDivisionError:
        print('Division by Zero')
        result = 0
    except AttributeError:
        pass

That's all for this topic pass Statement in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python assert Statement
  2. Python Exception Handling Tutorial
  3. Global Keyword in Python With Examples
  4. Abstraction in Python
  5. Difference Between Function and Method in Python

You may also like-

  1. Comparing Two Strings in Python
  2. Namespace And Variable Scope in Python
  3. Passing Object of The Class as Parameter in Python
  4. Python Program to Find Factorial of a Number
  5. What Are JVM, JRE And JDK in Java
  6. Java Program to Detect And Remove Loop in a Linked List
  7. How to Read Input From Console in Java
  8. Word Count MapReduce Program in Hadoop