Blog

  • for else Loops

    Python – For Else Loop

    Python supports an optional else block to be associated with a for loop. If a else block is used with a for loop, it is executed only when the for loop terminates normally.

    The for loop terminates normally when it completes all its iterations without encountering a break statement, which allows us to exit the loop when a certain condition is met.

    Flowchart of For Else Loop

    The following flowchart illustrates use of for-else loop −

    for-else

    Syntax of For Else Loop

    Following is the syntax of for loop with optional else block −

    for variable_name in iterable:#stmts in the loop...else:#stmts in else clause..

    Example of For Else Loop

    The following example illustrates the combination of an else statement with a for statement in Python. Till the count is less than 5, the iteration count is printed. As it becomes 5, the print statement in else block is executed, before the control is passed to the next statement in the main program.

    for count inrange(6):print("Iteration no. {}".format(count))else:print("for loop over. Now in else block")print("End of for loop")

    On executing, this code will produce the following output −

    Iteration no. 1
    Iteration no. 2
    Iteration no. 3
    Iteration no. 4
    Iteration no. 5
    for loop over. Now in else block
    End of for loop
    For-Else Construct without break statement
    As mentioned earlier in this tutorial, the else block executes only when the loop terminates normally i.e. without using break statement.

    Example
    In the following program, we use the for-else loop without break statement.

    for i in ['T','P']:
    print(i)
    else:
    # Loop else statement
    # there is no break statement in for loop, hence else part gets executed directly
    print("ForLoop-else statement successfully executed")
    On executing, the above program will generate the following output

    T
    P
    ForLoop-else statement successfully executed
    For-Else Construct with break statement
    In case of forceful termination (by using break statement) of the loop, else statement is overlooked by the interpreter and hence its execution is skipped.

    Example
    The following program shows how else conditions work in case of a break statement.


    for i in ['T','P']:
    print(i)
    break
    else:
    # Loop else statement
    # terminated after 1st iteration due to break statement in for loop
    print("Loop-else statement successfully executed")
    On executing, the above program will generate the following output

    T
    For-Else with break statement and if conditions
    If we use for-else construct with break statement and if condition, the for loop will iterate over the iterators and within this loop, you can use an if block to check for a specific condition. If the loop completes without encountering a break statement, the code in the else block is executed.

    Example
    The following program shows how else conditions works in case of break statement and conditional statements.

    Open Compiler
    # creating a function to check whether the list item is a positive
    # or a negative number
    def positive_or_negative():
    # traversing in a list
    for i in [5,6,7]:
    # checking whether the list element is greater than 0
    if i>=0:
    # printing positive number if it is greater than or equal to 0
    print ("Positive number")
    else:
    # Else printing Negative number and breaking the loop
    print ("Negative number")
    break
    # Else statement of the for loop
    else:
    # Statement inside the else block
    print ("Loop-else Executed")
    # Calling the above-created function
    positive_or_negative()
    On executing, the above program will generate the following output

    Positive number
    Positive number
    Positive number
    Loop-else Executed
  • For Loops

    The for loop in Python provides the ability to loop over the items of any sequence, such as a list, tuple or a string. It performs the same action on each item of the sequence. This loop starts with the for keyword, followed by a variable that represents the current item in the sequence. The in keyword links the variable to the sequence you want to iterate over. A colon (:) is used at the end of the loop header, and the indented block of code beneath it is executed once for each item in the sequence.

    Syntax of Python for Loop

    for iterating_var in sequence:
       statement(s)

    Here, the iterating_var is a variable to which the value of each sequence item will be assigned during each iteration. Statements represents the block of code that you want to execute repeatedly.

    Before the loop starts, the sequence is evaluated. If it’s a list, the expression list (if any) is evaluated first. Then, the first item (at index 0) in the sequence is assigned to iterating_var variable.

    During each iteration, the block of statements is executed with the current value of iterating_var. After that, the next item in the sequence is assigned to iterating_var, and the loop continues until the entire sequence is exhausted.

    Flowchart of Python for Loop

    The following flow diagram illustrates the working of for loop −

    forloop

    Python for Loop with Strings

    string is a sequence of Unicode letters, each having a positional index. Since, it is a sequence, you can iterate over its characters using the for loop.

    Example

    The following example compares each character and displays if it is not a vowel (‘a’, ‘e’, ‘i’, ‘o’, ‘u’).

    zen ='''
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    '''for char in zen:if char notin'aeiou':print(char, end='')

    On executing, this code will produce the following output −

    Btfl s bttr thn gly.
    Explct s bttr thn mplct.
    Smpl s bttr thn cmplx.
    Cmplx s bttr thn cmplctd.
    

    Python for Loop with Tuples

    Python’s tuple object is also an indexed sequence, and hence you can traverse its items with a for loop.

    Example

    In the following example, the for loop traverses a tuple containing integers and returns the total of all numbers.

    numbers =(34,54,67,21,78,97,45,44,80,19)
    total =0for num in numbers:
       total += num
    print("Total =", total)

    On running this code, it will produce the following output −

    Total = 539
    

    Python for Loop with Lists

    Python’s list object is also an indexed sequence, and hence you can iterate over its items using a for loop.

    Example

    In the following example, the for loop traverses a list containing integers and prints only those which are divisible by 2.

    numbers =[34,54,67,21,78,97,45,44,80,19]
    total =0for num in numbers:if num%2==0:print(num)

    When you execute this code, it will show the following result −

    34
    54
    78
    44
    80
    

    Python for Loop with Range Objects

    Python’s built-in range() function returns an iterator object that streams a sequence of numbers. This object contains integers from start to stop, separated by step parameter. You can run a for loop with range as well.

    Syntax

    The range() function has the following syntax −

    range(start, stop, step)

    Where,

    • Start − Starting value of the range. Optional. Default is 0
    • Stop − The range goes upto stop-1
    • Step − Integers in the range increment by the step value. Option, default is 1.

    Example

    In this example, we will see the use of range with for loop.

    for num inrange(5):print(num, end=' ')print()for num inrange(10,20):print(num, end=' ')print()for num inrange(1,10,2):print(num, end=' ')

    When you run the above code, it will produce the following output −

    0 1 2 3 4
    10 11 12 13 14 15 16 17 18 19
    1 3 5 7 9
    

    Python for Loop with Dictionaries

    Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is still possible with the for loop.

    Example

    Running a simple for loop over the dictionary object traverses the keys used in it.

    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}for x in numbers:print(x)

    On executing, this code will produce the following output −

    10
    20
    30
    40
    

    Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with the get() method.

    Example

    The following example illustrates the above mentioned approach.

    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}for x in numbers:print(x,":",numbers[x])

    It will produce the following output −

    10 : Ten
    20 : Twenty
    30 : Thirty
    40 : Forty
    

    The items(), keys() and values() methods of dict class return the view objects dict_items, dict_keys and dict_values respectively. These objects are iterators, and hence we can run a for loop over them.

    Example

    The dict_items object is a list of key-value tuples over which a for loop can be run as follows −

    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}for x in numbers.items():print(x)

    It will produce the following output −

    (10, 'Ten')
    (20, 'Twenty')
    (30, 'Thirty')
    (40, 'Forty')
    

    Using else Statement with For Loop

    Python supports to have an else statement associated with a loop statement. However, the else statement is executed when the loop has exhausted iterating the list.

    Example

    The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 to 20.

    #For loop to iterate between 10 to 20for num inrange(10,20):#For loop to iterate on the factors for i inrange(2,num):#If statement to determine the first factorif num%i ==0:#To calculate the second factor
    
         j=num/i          
         print("%d equals %d * %d"%(num,i,j))#To move to the next numberbreakelse:print(num,"is a prime number")break</pre>

    When the above code is executed, it produces the following result −

    10 equals 2 * 5
    11 is a prime number
    12 equals 2 * 6
    13 is a prime number
    14 equals 2 * 7
    15 equals 3 * 5
    16 equals 2 * 8
    17 is a prime number
    18 equals 2 * 9
    19 is a prime number
  • Loops

    Python Loops

    Python loops allow us to execute a statement or group of statements multiple times.

    In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.

    Programming languages provide various control structures that allow for more complicated execution paths.

    Flowchart of a Loop

    The following diagram illustrates a loop statement −

    Loop Architecture

    Types of Loops in Python

    Python programming language provides following types of loops to handle looping requirements −

    Sr.No.Loop Type & Description
    1while loopRepeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
    2for loopExecutes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
    3nested loopsYou can use one or more loop inside any another while, for or do..while loop.

    Python Loop Control Statements

    Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

    Python supports the following control statements. Click the following links to check their detail.

    Let us go through the loop control statements briefly

    Sr.No.Control Statement & Description
    1break statementTerminates the loop statement and transfers execution to the statement immediately following the loop.
    2continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
    3pass statementThe pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.
  •  MatchCase Statement

    Python match-case Statement

    A Python match-case statement takes an expression and compares its value to successive patterns given as one or more case blocks. Only the first pattern that matches gets executed. It is also possible to extract components (sequence elements or object attributes) from the value into variables.

    With the release of Python 3.10, a pattern matching technique called match-case has been introduced, which is similar to the switch-case construct available in C/C++/Java etc. Its basic use is to compare a variable against one or more values. It is more similar to pattern matching in languages like Rust or Haskell than a switch statement in C or C++.

    Syntax

    The following is the syntax of match-case statement in Python –

    match variable_name:
       case 'pattern 1': statement 1
       case 'pattern 2': statement 2...
       case 'pattern n': statement n
    

    Example

    The following code has a function named weekday(). It receives an integer argument, matches it with all possible weekday number values, and returns the corresponding name of day.

    defweekday(n):
       match n:
    
      case 0:return"Monday"
      case 1:return"Tuesday"
      case 2:return"Wednesday"
      case 3:return"Thursday"
      case 4:return"Friday"
      case 5:return"Saturday"
      case 6:return"Sunday"
      case _:return"Invalid day number"print(weekday(3))print(weekday(6))print(weekday(7))</pre>

    On executing, this code will produce the following output −

    Thursday
    Sunday
    Invalid day number
    

    The last case statement in the function has "_" as the value to compare. It serves as the wildcard case, and will be executed if all other cases are not true.

    Combined Cases in Match Statement

    Sometimes, there may be a situation where for more than one cases, a similar action has to be taken. For this, you can combine cases with the OR operator represented by "|" symbol.

    Example

    The code below shows how to combine cases in match statement. It defines a function named access() and has one string argument, representing the name of the user. For admin or manager user, the system grants full access; for Guest, the access is limited; and for the rest, there's no access.

    defaccess(user):
       match user:
    
      case "admin"|"manager":return"Full access"
      case "Guest":return"Limited access"
      case _:return"No access"print(access("manager"))print(access("Guest"))print(access("Ravi"))</pre>

    On running the above code, it will show the following result −

    Full access
    Limited access
    No access
    

    List as the Argument in Match Case Statement

    Since Python can match the expression against any literal, you can use a list as a case value. Moreover, for variable number of items in the list, they can be parsed to a sequence with "*" operator.

    Example

    In this code, we use list as argument in match case statement.

    defgreeting(details):
       match details:
    
      case [time, name]:returnf'Good {time} {name}!'
      case [time,*names]:
         msg=''for name in names:
            msg+=f'Good {time} {name}!\n'return msg
    print(greeting(["Morning","Ravi"]))print(greeting(["Afternoon","Guest"]))print(greeting(["Evening","Kajal","Praveen","Lata"]))

    On executing, this code will produce the following output −

    Good Morning Ravi!
    Good Afternoon Guest!
    Good Evening Kajal!
    Good Evening Praveen!
    Good Evening Lata!
    

    Using "if" in "Case" Clause

    Normally Python matches an expression against literal cases. However, it allows you to include if statement in the case clause for conditional computation of match variable.

    Example

    In the following example, the function argument is a list of amount and duration, and the intereset is to be calculated for amount less than or more than 10000. The condition is included in the case clause.

    defintr(details):
       match details:
    
      case [amt, duration]if amt&lt;10000:return amt*10*duration/100
      case [amt, duration]if amt&gt;=10000:return amt*15*duration/100print("Interest = ", intr([5000,5]))print("Interest = ", intr([15000,3]))</pre>

    On executing, this code will produce the following output −

    Interest = 2500.0
    Interest = 6750.0
  • Nested if Statement


    Python supports nested if statements which means we can use a conditional if and if…else statement inside an existing if statement.

    There may be a situation when you want to check for additional conditions after the initial one resolves to true. In such a situation, you can use the nested if construct.

    Additionally, within a nested if construct, you can include an if…elif…else construct inside another if…elif…else construct.

    Syntax of Nested if Statement

    The syntax of the nested if construct with else condition will be like this −

    if boolean_expression1:
    statement(s)if boolean_expression2:
    statement(s)
    Flowchart of Nested if Statement
    Following is the flowchart of Python nested if statement −

    nested if statement flowchart
    Example of Nested if Statement
    The below example shows the working of nested if statements −

    num = 36
    print ("num = ", num)
    if num % 2 == 0:
    if num % 3 == 0:
    print ("Divisible by 3 and 2")
    print("....execution ends....")
    When you run the above code, it will display the following result −

    num = 36
    Divisible by 3 and 2
    ....execution ends....
    Nested if Statement with else Condition
    As mentioned earlier, we can nest if-else statement within an if statement. If the if condition is true, the first if-else statement will be executed otherwise, statements inside the else block will be executed.

    Syntax
    The syntax of the nested if construct with else condition will be like this −

    if expression1:
    statement(s)
    if expression2:
    statement(s)
    else
    statement(s)
    else:
    if expression3:
    statement(s)
    else:
    statement(s)
    Example
    Now let's take a Python code to understand how it works −

    num=8
    print ("num = ",num)
    if num%2==0:
    if num%3==0:
    print ("Divisible by 3 and 2")
    else:
    print ("divisible by 2 not divisible by 3")
    else:
    if num%3==0:
    print ("divisible by 3 not divisible by 2")
    else:
    print ("not Divisible by 2 not divisible by 3")
    When the above code is executed, it produces the following output −

    num = 8
    divisible by 2 not divisible by 3
    num = 15
    divisible by 3 not divisible by 2
    num = 12
    Divisible by 3 and 2
    num = 5
    not Divisible by 2 not divisible by 3
  • ifelse Statement


    Python if else Statement

    The if-else statement in Python is used to execute a block of code when the condition in the if statement is true, and another block of code when the condition is false.

    Syntax of if-else Statement

    The syntax of an if-else statement in Python is as follows −

    if boolean_expression:# code block to be executed# when boolean_expression is trueelse:# code block to be executed# when boolean_expression is false

    If the boolean expression evaluates to TRUE, then the statement(s) inside the if block will be executed otherwise statements of the else block will be executed.

    Flowchart of if-else Statement

    This flowchart shows how if-else statement is used −

    ifelse syntax

    If the expr is True, block of stmt1, 2, 3 is executed then the default flow continues with stmt7. However, if the expr is False, block stmt4, 5, 6 runs then the default flow continues.

    Python implementation of the above flowchart is as follows −

    if expr==True:
       stmt1
       stmt2
       stmt3
    else:
       stmt4
       stmt5
       stmt6
    Stmt7
    

    Python if-else Statement Example

    Let us understand the use of if-else statements with the following example. Here, variable age can take different values. If the expression age > 18 is true, then eligible to vote message will be displayed otherwise not eligible to vote message will be displayed. Following flowchart illustrates this logic −

    if-else

    Now, let’s see the Python implementation the above flowchart.

    age=25print("age: ", age)if age >=18:print("eligible to vote")else:print("not eligible to vote")

    On executing this code, you will get the following output −

    age: 25
    eligible to vote
    

    To test the else block, change the age to 12, and run the code again.

    age: 12
    not eligible to vote
    Python if elif else Statement
    The if elif else statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.

    Similar to the else block, the elif block is also optional. However, a program can contains only one else block whereas there can be an arbitrary number of elif blocks following an if block.

    Syntax of Python if elif else Statement
    if expression1:
    statement(s)
    elif expression2:
    statement(s)
    elif expression3:
    statement(s)
    else:
    statement(s)
    How if elif else Works?
    The keyword elif is a short form of else if. It allows the logic to be arranged in a cascade of elif statements after the first if statement. If the first if statement evaluates to false, subsequent elif statements are evaluated one by one and comes out of the cascade if any one is satisfied.

    Last in the cascade is the else block which will come in picture when all preceding if/elif conditions fails.

    Example
    Suppose there are different slabs of discount on a purchase −

    20% on amount exceeding 10000,

    10% for amount between 5-10000,

    5% if it is between 1 to 5000.

    no discount if amount<1000

    The following flowchart illustrates these conditions −

    if-elif
    We can write a Python code for the above logic with if-else statements −

    amount = 2500
    print('Amount = ',amount)
    if amount > 10000:
    discount = amount * 20 / 100
    else:
    if amount > 5000:
    discount = amount * 10 / 100
    else:
    if amount > 1000:
    discount = amount * 5 / 100
    else:
    discount = 0

    print('Payable amount = ',amount - discount)
    Set amount to test all possible conditions: 800, 2500, 7500 and 15000. The outputs will vary accordingly −

    Amount: 800
    Payable amount = 800
    Amount: 2500
    Payable amount = 2375.0
    Amount: 7500
    Payable amount = 6750.0
    Amount: 15000
    Payable amount = 12000.0
    While the code will work perfectly fine, if you look at the increasing level of indentation at each if and else statement, it will become difficult to manage if there are still more conditions.

    Python if elif else Statement Example
    The elif statement makes the code easy to read and comprehend. Following is the Python code for the same logic with if elif else statements −

    amount = 2500
    print('Amount = ',amount)
    if amount > 10000:
    discount = amount * 20 / 100
    elif amount > 5000:
    discount = amount * 10 / 100
    elif amount > 1000:
    discount = amount * 5 / 100
    else:
    discount=0

    print('Payable amount = ',amount - discount)
    The output of the above code is as follows −

    Amount: 2500
    Payable amount = 2375.0
  •  if Statement

    Python If Statement

    The if statement in Python evaluates whether a condition is true or false. It contains a logical expression that compares data, and a decision is made based on the result of the comparison.

    Syntax of the if Statement

    if expression:
       # statement(s) to be executed
    

    If the boolean expression evaluates to TRUE, then the statement(s) inside the if block is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if block is executed.

    Flow Diagram (Flowchart) of the if Statement

    The below diagram shows flowchart of the if statement −

    Python if statement

    Example of Python if Statement

    Let us consider an example of a customer entitled to 10% discount if his purchase amount is > 1000; if not, then no discount is applicable. The following flowchart shows the whole decision making process −

    If Statement Flowchart

    First, set a discount variable to 0 and an amount variable to 1200. Then, use an if statement to check whether the amount is greater than 1000. If this condition is true, calculate the discount amount. If a discount is applicable, deduct it from the original amount.

    Python code for the above flowchart can be written as follows −

    discount =0
    amount =1200# Check he amount valueif amount >1000:
       discount = amount *10/100print("amount = ", amount - discount)

    Here the amout is 1200, hence discount 120 is deducted. On executing the code, you will get the following output −

    amount = 1080.0
    

    Change the variable amount to 800, and run the code again. This time, no discount is applicable. And, you will get the following output −

    amount = 800
  • Decision Making

    Python’s decision making functionality is in its keywords − if..elif…else. The if keyword requires a boolean expression, followed by colon (:) symbol. The colon (:) symbol starts an indented block. The statements with the same level of indentation are executed if the boolean expression in if statement is True. If the expression is not True (False), the interpreter bypasses the indented block and proceeds to execute statements at earlier indentation level.

    Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.

    Following is the general form of a typical decision making structure found in most of the programming languages −

    Decision making statements in Python

    Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value.

    Types of Decision Making Statements in Python

    Python programming language provides following types of decision making statements. Click the following links to check their detail.

    Sr.No.Statement & Description
    1if statementsAn if statement consists of a boolean expression followed by one or more statements.
    2if…else statementsAn if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.
    3nested if statementsYou can use one if or else if statement inside another if or else if statement(s).

    Let us go through each decision making briefly −

    Single Statement Suites

    If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.

    Example

    Here is an example of a one-line if clause −

    var =100if( var ==100):print("Value of expression is 100")print("Good bye!")

    When the above code is executed, it produces the following result −

    Value of expression is 100
    Good bye!
    

    if…else statement

    In this decision making statement, if the if condition is true, then the statements within this block are executed, otherwise, the else block is executed.

    The program will choose which block of code to execute based on whether the condition in the if statement is true or false.

    Example

    The following example shows the use of if…else statement.

    var =100if( var ==100):print("Value of var is equal to 100")else:print("Value of var is not equal to 100")

    On running the above code, it will show the following output −

    Value of var is equal to 100
    

    Nested if statements

    A nested if is another decision making statement in which one if statement resides inside another. It allows us to check multiple conditions sequentially.

    Example

    In this example, we will see the use of nested-if statement.

    var =100if( var ==100):print("The number is equal to 100")if var %2==0:print("The number is even")else:print("The given number is odd")elif var ==0:print("The given number is zero")else:print("The given number is negative")

    On executing the above code, it will display the below output −

    The number is equal to 100
    The number is even
  • Control Flow

    Python program control flow is regulated by various types of conditional statementsloops, and function calls. By default, the instructions in a computer program are executed in a sequential manner, from top to bottom, or from start to end. However, such sequentially executing programs can perform only simplistic tasks. We would like the program to have a decision-making ability, so that it performs different steps depending on different conditions.

    Most programming languages including Python provide functionality to control the flow of execution of instructions. Normally, there are two type of control flow statements in any programming language and Python also supports them.

    Decision Making Statements

    Decision making statements are used in the Python programs to make them able to decide which of the alternative group of instructions to be executed, depending on value of a certain Boolean expression.

    The following diagram illustrates how decision-making statements work −

    decision making statements

    The if Statements

    Python provides if..elif..else control statements as a part of decision marking. It consists of three different blocks, which are if block, elif (short of else if) block and else block.

    Example

    Following is a simple example which makes use of if..elif..else. You can try to run this program using different marks and verify the result.

    marks =80 
    result =""if marks <30:
       result ="Failed"elif marks >75:
       result ="Passed with distinction"else:
       result ="Passed"print(result)

    This will produce following result:

    Passed with distinction
    

    The match Statement

    Python supports Match-Case statement, which can also be used as a part of decision making. If a pattern matches the expression, the code under that case will execute.

    Example

    Following is a simple example which makes use of match statement.

    defcheckVowel(n):
       match n:
    
      case 'a':return"Vowel alphabet"
      case 'e':return"Vowel alphabet"
      case 'i':return"Vowel alphabet"
      case 'o':return"Vowel alphabet"
      case 'u':return"Vowel alphabet"
      case _:return"Simple alphabet"print(checkVowel('a'))print(checkVowel('m'))print(checkVowel('o'))</pre>

    This will produce following result:

    Vowel alphabet
    Simple alphabet
    Vowel alphabet
    Loops or Iteration Statements
    Most of the processes require a group of instructions to be repeatedly executed. In programming terminology, it is called a loop. Instead of the next step, if the flow is redirected towards any earlier step, it constitutes a loop.

    The following diagram illustrates how the looping works −

    looping_works
    If the control goes back unconditionally, it forms an infinite loop which is not desired as the rest of the code would never get executed.

    In a conditional loop, the repeated iteration of block of statements goes on till a certain condition is met. Python supports a number of loops like for loop, while loop which we will study in next chapters.

    The for Loop
    The for loop iterates over the items of any sequence, such as a list, tuple or a string .

    Example
    Following is an example which makes use of For Loop to iterate through an array in Python:

    words = ["one", "two", "three"]
    for x in words:
    print(x)
    This will produce following result:

    one
    two
    three
    The while Loop
    The while loop repeatedly executes a target statement as long as a given boolean expression is true.

    Example
    Following is an example which makes use of While Loop to print first 5 numbers in Python:

    i = 1
    while i < 6:
    print(i)
    i += 1
    This will produce following result:

    1
    2
    3
    4
    5
    Jump Statements
    The jump statements are used to jump on a specific statement by breaking the current flow of the program. In Python, there are two jump statements break and continue.

    The break Statement
    It terminates the current loop and resumes execution at the next statement.

    Example
    The following example demonstrates the use of break statement −

    x = 0

    while x < 10:
    print("x:", x)
    if x == 5:
    print("Breaking...")
    break
    x += 1

    print("End")
    This will produce following result:

    x: 0
    x: 1
    x: 2
    x: 3
    x: 4
    x: 5
    Breaking...
    End
    It skips the execution of the program block and returns the control to the beginning of the current loop to start the next iteration.
    Example
    The following example demonstrates the use of continue statement −

    Open Compiler
    for letter in "Python":
    # continue when letter is 'h'
    if letter == "h":
    continue
    print("Current Letter :", letter)

    This will produce following result:

    Current Letter : P
    Current Letter : y
    Current Letter : t
    Current Letter : o
    Current Letter : n
  • Booleans

    Python Booleans (bool)

    In Python, bool is a sub-type of int type. A bool object has two possible values, and it is initialized with Python keywords, True and False.

    Example

    >>> a=True>>> b=False>>>type(a),type(b)(<class'bool'>,<class'bool'>)

    A bool object is accepted as argument to type conversion functions. With True as argument, the int() function returns 1, float() returns 1.0; whereas for False, they return 0 and 0.0 respectively. We have a one argument version of complex() function.

    If the argument is a complex object, it is taken as real part, setting the imaginary coefficient to 0.

    Example

    a=int(True)print("bool to int:", a)
    a=float(False)print("bool to float:", a)
    a=complex(True)print("bool to complex:", a)

    On running this code, you will get the following output −

    bool to int: 1
    bool to float: 0.0
    bool to complex: (1+0j)

    Python Boolean Expression
    Python boolean expression is an expression that evaluates to a Boolean value. It almost always involves a comparison operator. In the below example we will see how the comparison operators can give us the Boolean values. The bool() method is used to return the truth value of an expresison.

    Syntax: bool([x])
    Returns True if X evaluates to true else false.
    Without parameters it returns false.
    Below we have examples which use numbers streams and Boolean values as parameters to the bool function. The results come out as true or false depending on the parameter.

    Example
    # Check true
    a = True
    print(bool(a))
    # Check false
    a = False
    print(bool(a))
    # Check 0
    a = 0.0
    print(bool(a))
    # Check 1
    a = 1.0
    print(bool(a))
    # Check Equality
    a = 5
    b = 10
    print(bool( a==b))
    # Check None
    a = None
    print(bool(a))
    # Check an empty sequence
    a = ()
    print(bool(a))
    # Check an emtpty mapping
    a = {}
    print(bool(a))
    # Check a non empty string
    a = 'Tutorialspoint'
    print(bool(a))