Home > Backend Development > Python Tutorial > Python Day-Loop-Slicing & step operator,Pattern Formation,Task

Python Day-Loop-Slicing & step operator,Pattern Formation,Task

Susan Sarandon
Release: 2024-12-17 01:36:25
Original
913 people have browsed it

Slicing operator & Step operator:

Example:

name = 'abcdefghijklmn'

name[2:8] --> Slicing Operator-->Used for extracting portions of a sequence.

name[2:8:3] --> Step Operator-->The step operator defines the interval between indices. A positive step moves forward, while a negative step moves backward.

1) Syntax to get following output:

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Method:1(Using 2 variables)

start, end = 1, 6
while end>1:
    for num in range(start,end):
        print(num, end=' ')
    print()
    end-=1
Copy after login

Method:2(Using single variable)

end = 6
while end>1:
    for num in range(1,end):
        print(num, end=' ')
    print()
    end-=1
Copy after login

Method:3(Without using variables)

for end in range(6,1,-1):
    for num in range(1,end):   
        print(num, end=' ')
    print()
Copy after login

Method:4

for row in range(5):
    for col in range(5-row):
        print(col+1, end=' ')
    print()
Copy after login

Output:

1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 
Copy after login

2) Syntax to get following output:

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

for row in range(2,7):
    for col in range(1,row):
        print(col,end=' ')
    print()
Copy after login

Output:

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
Copy after login

3) Syntax to get following output:
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)*2, end=' ')
    print()
Copy after login

Output:

2 4 6 8 10 
2 4 6 8 
2 4 6 
2 4 
2 
Copy after login

4) Syntax to get following output:

1 2 3 4 5
2 4 6 8
3 6 9
4 8
5

for row in range(5):
    for col in range(5-row):
        print((col+1)*(row+1), end=' ') 
    print()
Copy after login

Output:

1 2 3 4 5 
2 4 6 8 
3 6 9 
4 8 
5 
Copy after login

Task:
Draw this "kolam" without taking your hand out from paper:

Python Day-Loop-Slicing & step operator,Pattern Formation,Task

The above is the detailed content of Python Day-Loop-Slicing & step operator,Pattern Formation,Task. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template