Python For Loop: Simple Examples and Usage
Here's an example of a simple 'for' loop in Python:
# Iterate over a list of numbers and print each one
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
In this example, the 'for' loop iterates over the 'numbers' list and assigns each value to the variable 'num'. The 'print' statement then outputs each number to the console.
You can also use the 'range()' function to generate a sequence of numbers to iterate over:
# Iterate over the numbers 0 through 4 and print each one
for i in range(5):
print(i)
In this example, the 'for' loop iterates over the sequence of numbers generated by 'range(5)', which includes the numbers 0 through 4. The 'print' statement outputs each number to the console.
原文地址: https://www.cveoy.top/t/topic/mF9i 著作权归作者所有。请勿转载和采集!