Page 339 - Artificial Intellegence_v2.0_Class_9
P. 339
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. It means when the number of iterations are
known/definite before we start with the execution of a 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. It is therefore known as 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. 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.
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]) will give an output ['E']
print(book[-7]) will give an output ['O']
9. How can we modify elements in a list?
Ans. List is mutable so data can be easily modified by overwriting a new value to an existing value in a given list by using an
assignment operator (=).
Syntax
list[index] = newvalue
For example,
l1 = [10, 20, 40, 50]
l1[3] = 100
print(l1)
Introduction to Python 337

