Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 141 - CodePilot V5.0 C7
P. 141

    Program 7 To print “Eligible to vote” if the age is greater than or equal to 18, else “Not eligible to vote”

                         Program7.py
                      File  Edit  Format   Run    Options   Window    Help

                      age = int(input("Enter your age: "))
                      print("Eligible to vote" if age >= 18 else "Not eligible to vote")

                         Output

                      Enter your age: 15
                      Not eligible to vote

                            PYTHON ITERATIVE STATEMENTS

                     Iteration means repeating a set of instructions again and again. It is a flow of control that allows
                     a part of the code to run multiple times without writing it again each time. In many programs, we
                     often need to repeat certain actions. Instead of copying the same code many times, we use loops
                     to do it automatically.

                     Using loops helps save time, reduce mistakes and make the code shorter and cleaner.
                     Python provides two main types of loops: the for loop, which repeats a block of code for each item
                     in a sequence or for a specific number of iterations and the while loop, which repeats a block of
                     code as long as a condition is true.

                     range() function

                     The range() function is a built-in function in Python that generates a sequence of numbers.
                     The  range() function  is most  commonly
                     used  with the  for loop  to  repeat  tasks  a
                     specific number of times.

                     Syntax of the range() function:                   Python has no limit on variable name length, but
                                                                       line lengths should be kept under 79 characters
                     range(start, stop, step)                          for better readability.
                     where,
                         start: This is the optional value where the sequence begins. If you don’t specify it, Python will
                        automatically start from 0.

                        For example, range(5) is treated as range(0, 5) and generates: [0, 1, 2, 3, 4].

                         stop: This is the mandatory value at which the sequence ends, but it is not included in the
                        result.

                        For example, range(2, 6) gives: [2, 3, 4, 5] (6 is excluded).

                                                                                                                      139
                                                                                               Flow of Control in Python

| 136 137 138 139 140 141 142 143 144 145 146 |