For Loop In Python zero to Hero
numbers = [1, 2, 3, 4, 5]
hear Code
for number in numbers:
print(number)
#numbers is the sequence, which in this case is a defined list of numbers
#number is the loop variable that takes each value from the list, one at a time.
#print(number) is a statement in the code block that gets executed for each item in the list
number=int(input("Enter a number: "))
up_to=int(input("Enter a number: "))
for i in range(1, up_to):
print(f"{number} x {i} = {number * i}")
Statements: break and continue with for loops
The break statement allows you to exit the loop before it is completed. When the break statement is executed, the loop terminates immediately, and the program continues with the next statement following the loop.
The continue statement allows skipping the current iteration of a loop and proceeding to the next iteration. When the continue statement is encountered, the next iteration begins
items = ['apple', 'banana', 'cherry', 'date', 'elderberry']
search_item = 'cherr'
for item in items:
if item == search_item:
print(f'Found {search_item}!')
break
# Optional else clause
else:
print(f'{search_item} not found.')
=======================================================
items1 = ['apple', 'banana', 'cherry', 'lemon', 'elderberry']
for items in items1:
if 'a' in items:
continue
print(items)
================================================
In Python, enumerate() is a built-in function that adds a counter to an iterated item and returns it as an enumerated object. This can be especially useful for looping over a list, or any other item where both the index and the value of each item are needed.
As a developer, you can use these functions to make your code more readable and concise by eliminating the need to manually manage counter-variables. They also help reduce the risk of errors that can occur when manually incrementing a counter.
Here’s a simple example to illustrate how enumerate() can be used in a for loop:
# List of fruits
fruits = ['apple', 'banana', 'cherry']
# Using enumerate to get index and value
for index, fruit in enumerate(fruits, start=0 ):
print(f"{index}: {fruit}")
===============================================
Real time Usage:=
In the following loop example, you can use a loop to automate processing files. The following loop scans a directory, separates files from folders, and provides a list of all the files inside with their local path.
import os
directory = '/path/to/directory'
# Iterate over all files in the directory
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
if os.path.isfile(file_path):
print(f'File: {filename, file_path}')
/path/to/directory is a placeholder to be replaced with the local path for the directory to be processed.
os.listdir(directory) lists all the entries in the specified directory.
os.path.join(directory, filename) constructs the full path to the file.
os.path.isfile(file_path) checks if the path is a file (and not a directory).
Knowing the exact location of files helps create precise backups and restore them when needed.
Pattern Prints in For loop
:#Pyramid Pattern (Important 🔥)
n = 5
for i in range(1, n+1):
print(" " * (n-i) + "*" * (2*i-1))
Output:-
*
***
*****
*******
*********
No comments:
Post a Comment