1|Page
Question 1:
Differentiate between For loop and While loop in Python with an
example.
Answer-
In Python, both for loops and while loops are used for
iteration, but they have different structures and use cases.
1. For Loop:
Syntax:
pythonCopy code
for item in iterable: # code block to be executed
Example:
pythonCopy code
fruits = ["apple", "banana", "cherry"] for fruit in fruits:
print(fruit)
Explanation: The for loop iterates over each item in
the fruits list and prints it. It automatically knows when to stop
based on the length of the fruits list.
2. While Loop:
Syntax:
pythonCopy code
while condition: # code block to be executed
Example:
pythonCopy code
i = 1 while i <= 5: print(i) i += 1
Explanation: The while loop repeatedly executes the
code block as long as the condition (in this case, i <= 5)
remains true. It's useful when you don't know in advance how
many times you need to iterate.
In summary, for loops are used when you have a collection of
items to iterate over, and you know the number of iterations in
advance. while loops are used when you need to repeat an
action until a specific condition is met, and the number of
iterations is not known beforehand.
Question 2:
2|Page
Name 10 Python keywords and its uses.
Answer-
Here are 10 Python keywords and their uses:
1. if: Used for conditional execution. It allows you to execute
a block of code only if a specified condition is true.
2. else: Used in conjunction with if to execute a block of
code if the if condition is false.
3. elif: Short for "else if," elif is used to check for multiple
conditions after an initial if statement. It allows you to check for
additional conditions if the previous ones are false.
4. for: Used for looping over a sequence (such as a list,
tuple, dictionary, or string) and executing a block of code for
each item in the sequence.
5. while: Used to create a loop that executes a block of code
as long as a specified condition is true.
6. break: Used to exit a loop prematurely. When break is
encountered inside a loop, the loop is terminated, and the
program continues with the next statement after the loop.
7. continue: Used to skip the rest of the code inside a loop
for the current iteration and continue with the next iteration.
8. def: Used to define a function. Functions allow you to
encapsulate reusable pieces of code and execute them by
calling the function with specific arguments.
9. return: Used inside a function to return a value. When a
return statement is executed, the function exits and returns
the specified value to the caller.
10. class: Used to define a class. Classes are used to create
objects with properties (attributes) and methods (functions)
that operate on those properties.
These keywords are fundamental to the structure and flow
control of Python programs.