Tutorial Playlist
200 Lessons1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
Now Reading
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Reverse a List in Python
92. Python List remove() Method
93. How to Add Elements in a List in Python
94. How to Reverse a List in Python?
95. Difference Between List and Tuple in Python
96. List Slicing in Python
97. Sort in Python
98. Merge Sort in Python
99. Selection Sort in Python
100. Sort Array in Python
101. Sort Dictionary by Value in Python
102. Datetime Python
103. Random Number in Python
104. 2D Array in Python
105. Abs in Python
106. Advantages of Python
107. Anagram Program in Python
108. Append in Python
109. Applications of Python
110. Armstrong Number in Python
111. Assert in Python
112. Binary Search in Python
113. Binary to Decimal in Python
114. Bool in Python
115. Calculator Program in Python
116. chr in Python
117. Control Flow Statements in Python
118. Convert String to Datetime Python
119. Count in python
120. Counter in Python
121. Data Visualization in Python
122. Datetime in Python
123. Extend in Python
124. F-string in Python
125. Fibonacci Series in Python
126. Format in Python
127. GCD of Two Numbers in Python
128. How to Become a Python Developer
129. How to Run Python Program
130. In Which Year Was the Python Language Developed?
131. Indentation in Python
132. Index in Python
133. Interface in Python
134. Is Python Case Sensitive?
135. Isalpha in Python
136. Isinstance() in Python
137. Iterator in Python
138. Join in Python
139. Leap Year Program in Python
140. Lexicographical Order in Python
141. Literals in Python
142. Matplotlib
143. Matrix Multiplication in Python
144. Memory Management in Python
145. Modulus in Python
146. Mutable and Immutable in Python
147. Namespace and Scope in Python
148. OpenCV Python
149. Operator Overloading in Python
150. ord in Python
151. Palindrome in Python
152. Pass in Python
153. Pattern Program in Python
154. Perfect Number in Python
155. Permutation and Combination in Python
156. Prime Number Program in Python
157. Python Arrays
158. Python Automation Projects Ideas
159. Python Frameworks
160. Python Graphical User Interface GUI
161. Python IDE
162. Python input and output
163. Python Installation on Windows
164. Python Object-Oriented Programming
165. Python PIP
166. Python Seaborn
167. Python Slicing
168. type() function in Python
169. Queue in Python
170. Replace in Python
171. Reverse a Number in Python
172. Reverse a string in Python
173. Reverse String in Python
174. Stack in Python
175. scikit-learn
176. Selenium with Python
177. Self in Python
178. Sleep in Python
179. Speech Recognition in Python
180. Split in Python
181. Square Root in Python
182. String Comparison in Python
183. String Formatting in Python
184. String Slicing in Python
185. Strip in Python
186. Subprocess in Python
187. Substring in Python
188. Sum of Digits of a Number in Python
189. Sum of n Natural Numbers in Python
190. Sum of Prime Numbers in Python
191. Switch Case in Python
192. Python Program to Transpose a Matrix
193. Type Casting in Python
194. What are Lists in Python?
195. Ways to Define a Block of Code
196. What is Pygame
197. Why Python is Interpreted Language?
198. XOR in Python
199. Yield in Python
200. Zip in Python
The for loop in Python is a fundamental control structure. First, it iterates through a sequence of items. Then, executes a code block for each item in the sequence. Python for loop can be used to iterate through elements such as integers in a range or items in a list. Essentially, to automate operations that need each item to be processed individually.
Common applications include looping through lists, and strings, dictionaries, among others. It is mostly helpful for data analysis, manipulation, and transformation. for loops are a quick and effective technique to manage repeating tasks. Keep reading this tutorial to learn more about for loop in Python.
In this tutorial, we will mainly deal with while loop in Python, python for loop, nested loop in Python, the different types of loop control statements, and much more.
In Python, a while loop is a control structure that is used for repeatedly executing blocks of code as long as the given conditions are true. The syntax of a while loop looks like this:
while condition:
# Code to be executed while the condition is true
# This code block will keep running as long as the condition remains true
Here's a simple example of a while loop that counts from 1 to 5:
Code:
count = 1
while count <= 5:
print(count)
count += 1
In this example, the count variable starts at 1, and the loop will continue as long as count is less than or equal to 5. Inside the loop, the current value of count is printed, and then count is incremented by 1 in each iteration.
It's important to be cautious while using while loops to ensure that the loop eventually terminates. If the condition provided in the loop header never becomes false, you might end up with an infinite loop, causing your program to run indefinitely.
To prevent infinite loops, you can use mechanisms like user input or counter variables to control the loop's behavior. Here's an example of using a while loop for repeatedly asking users for input till the program is finally provided a valid number:
Code:
while True:
try:
num = int(input("Enter a number: "))
print("You entered:", num)
break # Exit the loop if valid input is provided
except ValueError:
print("Invalid input. Please enter a valid number.")
In this example, the loop keeps running until the user provides a valid integer input. If the user enters something that can't be converted to an integer, a ValueError exception is caught, and an error message is displayed. Once the user enters a valid number, the break statement is used to exit the loop.
In Python, a for loop is a control structure that iterates over a sequence (like a list, tuple, string, etc.) or other objects that are iterable. It repeatedly executes a block of code for each element in the sequence. The syntax of a for loop looks like this:
for element in sequence:
# Code to be executed for each element in the sequence
Here's a simple example of a for loop that iterates over a list of numbers and prints each number:
Code:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
In this example, the loop iterates over each element in the numbers list and prints it.
You can also use the range() function to generate a sequence of numbers and iterate over them in a for loop:
Code:
for i in range(1, 6): # Generates numbers from 1 to 5 (inclusive)
print(i)
In the above example, the range() function is used for generating the number sequence that starts from the first argument and ends before the second argument. In this case, it generates numbers from 1 to 5.
You can also iterate over strings:
Code:
text = "Hello"
for char in text:
print(char)
This loop will iterate over each character in the string "Hello" and print each character.
Additionally, you can combine for loops with other control structures, such as using nested for loops to iterate over multiple sequences or using break and continue statements to control the loop's behavior.
Sometimes, you might need to iterate over a sequence using its index positions, rather than the values themselves. In Python, you can achieve this using the range() function and the length of the sequence. Here's how you can iterate by the index of sequences:
Code:
sequence = ["apple", "banana", "cherry", "date"]
for index in range(len(sequence)):
item = sequence[index]
print(f"Index {index}: {item}")
In this example, range(len(sequence)) generates a sequence of numbers from 0 to len(sequence) - 1, which are the valid index positions for the given sequence. The loop then iterates over these index positions, and within each iteration, you can access both the index and the corresponding value using sequence[index].
However, a more Pythonic way to achieve the same result is by using the enumerate() function, which provides both the index and the value in each iteration:
Code:
sequence = ["apple", "banana", "cherry", "date"]
for index, item in enumerate(sequence):
print(f"Index {index}: {item}")
Using enumerate() is generally preferred because it's more concise and easier to read.
Remember that Python uses 0-based indexing, so the first element of a sequence is at index 0, the second element is at index 1, and so on.
Certainly! Nested loops in Python refer to the concept of having one loop inside another. This allows you to perform more complex iterations that involve multiple levels of iteration. You can nest any type of loop within another loop, such as for loops inside for loops, while loops inside for loops, and so on.
Here are a few examples of nested loops in Python:
Code:
for i in range(3): # Outer loop
for j in range(2): # Inner loop
print(f"Outer loop index: {i}, Inner loop index: {j}")
In this example, the outer loop is run three times, and the inner loop runs twice for each iteration of the outer loop. This results in a total of 3 * 2 = 6 iterations, and the program prints out the combination of indices from both loops.
Code:
i = 1
while i <= 3: # Outer loop
j = 1
while j <= 2: # Inner loop
print(f"Outer loop index: {i}, Inner loop index: {j}")
j += 1
i += 1
This is equivalent to the previous example but using while loops instead.
Code:
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=" ")
print() # Print a new line after each row
In this example, the outer loop is used for iterating over each of the rows in the 2D list matrix, and the inner loop iterates over the elements within each row, printing them out in a grid format.
Loop control statements in Python help you alter the flow of loops based on certain conditions. The three loop control statements you mentioned are continue, break, and pass. Let's look at each one in detail:
The continue statement is used within loops to skip the rest of the current iteration and proceed to the next iteration. This is particularly useful when you want to skip some part of the loop's body under specific conditions.
Code:
for i in range(1, 6):
if i == 3:
continue
print(i)
In this example, the loop iterates over the numbers 1 to 5. When i is equal to 3, the continue statement is executed, and the remaining part of the loop body for that iteration is skipped. As a result, the number 3 is not printed.
The break statement is used for exiting loop prematurely, regardless of whether the loop's condition is still met. It's often used when a specific condition is satisfied and you want to immediately stop the loop.
Code:
for i in range(1, 6):
if i == 4:
break
print(i)
In this example, the loop iterates from 1 to 5. When i becomes 4, the break statement is executed, and the loop is terminated. As a result, only the numbers 1, 2, and 3 are printed.
The pass statement is a placeholder statement that does nothing. It's used when statements are syntactically required but you don't want any action to be taken. It's often used as placeholders in code that you plan to fill in later.
Code:
for i in range(1, 4):
if i == 2:
pass
else:
print(i)
In this example, when i is 2, the pass statement is executed, essentially doing nothing. The loop continues to the next iteration. For other values of i, the corresponding value is printed.
The range() function is used for generating sequences of numbers that can be used for iterations, typically in for loops. It's often used to create a range of indices or values that you want to iterate over.
Here is an example of how to use the range() function:
Code:
# Loop from 0 to 4 (0, 1, 2, 3)
for i in range(4):
print(i)
# Loop from 2 to 6 (2, 3, 4, 5)
for j in range(2, 6):
print(j)
# Loop from 1 to 10 with step 2 (1, 3, 5, 7, 9)
for k in range(1, 10, 2):
print(k)
In Python, the else statement can be used with a for loop to specify a block of code that should run when the loop completes all its iterations without being interrupted by a break statement.
numbers = [1, 2, 3, 4, 5]
search_value = 3
for num in numbers:
if num == search_value:
print(f"Found {search_value} in the list.")
break
else:
print(f"{search_value} not found in the list.")
In this example, the for loop iterates through the numbers list to search for search_value. If the value is found, the break statement is executed, and the else block is skipped. However, if the loop completes without encountering a break, the else block is executed, indicating that the value was not found.
The combination of the else statement and a for loop can be helpful for scenarios where you want to execute specific code when a loop completes all its iterations without being prematurely interrupted by a break.
The for loop in Python is an essential and foundational feature in Python. Many industries worldwide strongly prefer experts with exceptional knowledge of programming languages such as Python.
If you want to bag the best jobs in the most lucrative industries globally, look no further and take up a Computer Science course by upGrad. The courses by upGrad are designed by industry experts and tailored to meet the needs of the global job market. Visit upGrad today to know more.
1. How can I break out of a for loop prematurely?
You can exit the loop prematurely if a certain condition is met. To do this, use the “break” statement inside a for loop.
2. Is it possible to skip the rest of the current iteration and continue with the next one?
It is possible to proceed to the next iteration by skipping the current iteration. To do this, you can use the “continue” statement.
3. Can I nest for loops within each other?
Yes, you can nest one or more for loops within each other to create nested iterations, which can be helpful in working with multidimensional data structures.
4. Are there alternatives to for loops in Python?
Yes, Python offers other looping constructs like while loops and functional programming constructs like list comprehensions and the “map()” function that can sometimes provide more concise and efficient ways of achieving certain looping tasks.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...