Page 423 - Ai_417_V3.0_C9_Flipbook
P. 423
Statements for True
else:
Statements for False
Example:
age=int(input("Enter your age: "))
if (age>=18):
print("Eligible for driving")
else:
print("Not eligible")
6. Explain "for" loop with an example.
Ans. It is used to repeat a set of instructions for a fixed number of times. This means when the number of iterations are
known/definite before we start the execution of the loop. It is therefore also known as definite loop. Indentation of
statements is must to specify the block of statements to be repeated using for loop.
There are two ways to use for loop:
• Using sequence
• Using range() function
Example:
for i in range(10, 0, -1):
print(i)
7. Explain while loop with example.
Ans. It is used to repeat a set of instructions as long as the condition is true. It means when the number of iterations are not
fixed/indefinite before we start with the execution of a loop. Therefore, it is known as an indefinite loop. Indentation of
statements is must to specify the block of statements to be repeated using while loop.
This loop is also called an entry-controlled loop as it checks for the condition in the beginning only. If the condition is
'True' then the body of the loop will be executed. If the condition is 'False' then it will not be allowed to enter within the
loop and it stops. The syntax of the while loop is:
while <condition>:
statements
Where,
while is a keyword.
condition is a criterion to repeat the instructions. The instructions repeat till the condition is 'True'. As soon as the
condition is 'False', the control exits from the loop.
Statements are always indented can be single or a block and are repeated till the condition is 'True'.
For example,
i = 1
while i < 6:
print(i)
i += 1
8. What is negative indexing? Explain with an example.
Ans. In negative indexing, the index number begins with -1 till -length and we refer the elements from right to left.
For example, book=['C', 'O', 'M', 'P', 'U', 'T', 'E', 'R']
So, each letter gets an element number starting from -1
print(book[2:4]) will give an output ['M', 'P']
print(book[-7:-3]) will give an output ['O', 'M', 'P', 'U']
Introduction to Python 421

