if-else in for loop

In this section, we will use how to use if-else statement with a loop. If-else is used when conditional iteration is needed. For example, print studetn names who got more than 80 percent.

The if-else statement checks the condition and if the condition is True it executes the block of code present inside the if block and if the condition is False, it will execute the block of code present inside the else block.

When the if-else condition is used inside the loop, the interpreter checks the if condition in each iteration, and the correct block gets executed depending on the result.

if condition:
    block of statements
else:
    block of statements

Example: Print all even and odd numbers

In this progaram, for loop statement first iterates all the elements from 0 to 20.

Next, the if statement checks whether the currect number is even or not. If yes, it prints it. Else, the else block gets executed.

for i in range(1, 11):
    if i % 2 == 0:
        print("Even number:", i)
    else:
        print("Odd number:", i)

Output:

Odd number: 1

Even number: 2

Odd number: 3

Even number: 4

Odd number: 5

Even number: 6

Odd number: 7

Even number: 8

Odd number: 9

Even number: 10

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值