python viva
python viva
Introduction to Python:
2. Conditional Statements:
3. Loops:
python
Copy code
for variable in iterable:
# code
What is the difference between for and while loops?
for is for fixed iterations, while runs until a condition is false.
Can you use an else block with loops?
Yes, it runs if the loop doesn’t hit break.
How do you exit a loop prematurely in Python?
Use break.
What is the role of the continue statement?
Skips to the next iteration.
How does a nested loop work?
A loop inside another loop, running multiple layers.
How do you loop through a list in Python?
Use for item in list:.
What is an infinite loop? How do you create one?
A loop that never ends, e.g., while True:.
What is the range function, and how is it used in loops?
range() generates a sequence of numbers, often used in for loops.
How can you loop through a dictionary in Python?
Use for key, value in dict.items():.
What is the purpose of enumerate() in loops?
Provides both index and value when looping through an iterable.
What is a do-while loop, and does Python have it?
Python lacks do-while, but similar behavior can be achieved with while.
How do you reverse a loop in Python?
Use reversed(), e.g., for i in reversed(range(n)).
Can you nest a for loop inside a while loop, and vice versa?
Yes, Python allows nested loops.
What is the difference between break and return in a loop?
break exits the loop; return exits the function.
How can you skip an iteration in a loop?
Use continue to skip to the next iteration.
4. Patterns:
python
Copy code
for i in range(1, 6):
print("*" * i)
python
Copy code
for i in range(5, 0, -1):
print("*" * i)
yaml
Copy code
1
12
123
1234
python
Copy code
for i in range(1, 5):
for j in range(1, i + 1):
print(j, end="")
print()
python
Copy code
for i in range(n):
print("*" * n)
Copy code
1
2 3
4 5 6
7 8 9 10
python
Copy code
num = 1
for i in range(1, 5):
for j in range(i):
print(num, end=" ")
num += 1
print()
python
Copy code
for i in range(1, n+1):
print(" " * (n-i) + "*" * (2*i-1))
Write a program to print an inverted pyramid pattern.
python
Copy code
for i in range(n, 0, -1):
print(" " * (n-i) + "*" * (2*i-1))