Home > Backend Development > Python Tutorial > Python Day- Looping

Python Day- Looping

DDD
Release: 2024-11-27 03:19:13
Original
689 people have browsed it

Python Day- Looping

While Loop:
Example:1

no = 1
while no<=5:
    print(no, end=' ')
    no+=1

Copy after login

Output:

1 2 3 4 5 
Copy after login

Example:2

1) 1 2 3 4 5 6 7 8 9 10
2) 1 2 3 4 5 6 7 8 9 10
3) 10 9 8 7 6 5 4 3 2 1
4) 1 3 5 7 9
5) 2 4 6 8 10
6) 3 6 9

#1 2 3 4 5 6 7 8 9 10
no = 1
while no<=10:
    print(no, end=' ')
    no+=1

print(end='\n')

# 10 9 8 7 6 5 4 3 2 1
no = 10
while no>=1:
    print(no, end=' ')
    no-=1

print(end='\n')

# 1 3 5 7 9 
no = 1
while no<=10:
    print(no, end=' ')
    no+=2

print(end='\n')

#2 4 6 8 10
no=2
while no<=10:
    print(no, end=' ')
    no+=2

print(end='\n')

# 3 6 9
no = 3
while no<=10:
    print(no, end=' ')
    no+=3
Copy after login

Output:

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

Example:3 (using *)

no = 1
while no<=5:
    print(no*3, end=' ') 
    no+=1
Copy after login

Output:

3 6 9 12 15
Copy after login

Example:4(5 tables-->1*5=5 upto 10*5=50)

Input can be given in 2 ways,

Input: 1

no = 1
while no<=10:
    print(no,"*5=",no*5, end='\n')
    no+=1

Copy after login

Input: 2 (Using f string-formatted string literal)
-->A formatted string literal or f-string is a string literal that is prefixed with f or F.
-->Expressed using curly braces {}.
-->It is used to look at the values , expressions or instance inside {} and substitute them with the variables values or results.

no = 1
while no<=10:
    result=no*5
    print(f'{no} * 5 = {result}')
    no+=1
Copy after login

Output of both inputs:

1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50

Copy after login

Example:5

#1  2   3   4   5   5   4   3   2   1

no = 1

while no <= 5:  
    print(no, end=" ")
    no += 1

no = 5
while no > 0:  
    print(no, end=" ")
    no -= 1
Copy after login

Output:

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

Example:6

#1  3   5   7   9   2   4   6   8   10

no = 1
while no<=10:
    print(no, end = ' ')
    if no==9:
        no = 0
    no+=2
Copy after login

Output:

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

The above is the detailed content of Python Day- Looping. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template