Home >Backend Development >Python Tutorial >Python While Loop Examples

Python While Loop Examples

DDD
DDDOriginal
2025-01-05 16:18:44853browse

Python While Loop Examples

#Tasks
# 2 4   6   8   10
#3  6   9   12  15
#1  3   5   7   9   2   4   6   8   10
#10 8   6   4   2
#9  7   5   3   1
#1  2   3   4   5   6   7   8   9   10
#1  RED BLUE RED 5 REDBLUE 7 RED BLUE RED


#Task 1
i=1
while i <= 10:
    if i%2 ==0:
        print(i, end =' ')
    i=i+1
print('')


#Task 2

i=1
while i <= 15:
    if i%3 ==0:
        print(i, end =' ')
    i=i+1
print('')

#Task 3 using 2 loops

i=1
while i<= 10:
    if i%2 != 0:
        print(i, end= ' ')
    i=i+1
i=1
while i<=10:
    if i%2 == 0:
        print(i, end =' ')
    i=i+1
print('')

#Task 3 using 1 loop

i=1
output = ''
while i<= 10:
    if i%2 != 0:
        print(i, end= ' ')
    elif i%2 == 0:
        output = output + str(i) + ' '
    i=i+1
else:
    print(output)

#Task 4

i=10
while i>=1:
    if i%2 == 0:
        print(i, end =' ')
    i=i-1
print('')

#Task 5

i=10
while i>=1:
    if i%2 != 0:
        print(i, end =' ')
    i=i-1
print('')

#Task 6 

i = 1
while i<=10:
    print(i, end =' ')
    i=i+1
print('')

#Task 7

i = 1
while i<=10:
    if i%2 == 0 and i%3 == 0:
        print('REDBLUE',end =' ')
    elif i%3 == 0:
        print('BLUE',end= ' ')
    elif i%2 == 0:
        print('RED',end =' ')
    else:
        print(i,end =' ')
    i=i+1
print('')

The above is the detailed content of Python While Loop Examples. 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