Home >Backend Development >Python Tutorial >Day - Slicing,for loop and nested loop

Day - Slicing,for loop and nested loop

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-05 12:05:15756browse

Day - Slicing,for loop and nested loop

Slicing:

Slicing is a programming technique used in Python to extract a portion of a sequence. By specifying a range of indices, you can retrieve specific parts of the sequence without altering the original data.

Example:

name=[2,8]

Step operator:

A step operator refers to the ability to specify an increment for iteration in loops. In Python, this is often used with the range() function, which allows specifying a step to control how the loop variable changes after each iteration.

Example:

name[2:8:3]
3 is a step operator.

Program using two variable:

start,end= 1,6
while end>1:
    for num in range(start,end):
        print(num, end=" ")
    print()
    end-=1   

Same program using one variable:

end= 6
while end>1:
    for num in range(1,end):
        print(num, end=" ")
    print()
    end-=1  

*Same program without using variable or using nested loop:
*

for end in range(6,1,-1):
    for num in range(1,end):
        print(num, end=" ")
    print()  

Output:

1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 

Nested loop:

A nested for loop is a loop inside another loop.

Syntax:

for outer in outer_iterable:
    for inner in inner_iterable:

1.The outer loop runs first.
2.For every iteration of the outer loop, the inner loop runs completely.
3.When the inner loop finishes, the outer loop proceeds to its next iteration.

for row in range(2,7):
    for col in range(1,row):
        print(col, end=' ')
    print()
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
for row in range(5):
    for col in range(5-row):
        print(col+1, end=' ')
    print()
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 
for row in range(5):
    for col in range(5-row):
        print((col+1)*2, end=' ')
    print()
2 4 6 8 10 
2 4 6 8 
2 4 6 
2 4 
2 
for row in range(5):
    for col in range(5-row):
        print((col+1)*(row+1), end=' ')
    print()
1 2 3 4 5 
2 4 6 8 
3 6 9 
4 8 
5 

Task:

(https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3v84djylxrixjnllx8hq.jpg)

for row in range(5):
    for col in range(5-row):
        print((col+1)*3, end=" ")
    print()

3 6 9 12 15 
3 6 9 12 
3 6 9 
3 6 
3 
for row in range(5):
    for col in range(row+1):
        print(5-col, end=' ')
    print()
5 
5 4 
5 4 3 
5 4 3 2 
5 4 3 2 1 

The above is the detailed content of Day - Slicing,for loop and nested loop. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn