0
Please I need a better explanation for the WHILE and IF loop
3 ответов
+ 1
IBE CHIBUIKE DONALD
WHILE LOOP
FOR LOOP
but IF is not a loop.
A student gets a task, to print numbers from 1 to 10.
print(1)
print(2)
print(3)
print(4)
print.... and so on.
But you can easily do it using for or while loop.
FOR LOOP:
for num in range(1, 11):
print(num)
You can use any name in place of 'num' like 'i' or 'j', but change it everywhere not just one place.
WHILE LOOP:
a = 1
while a < 11:
print(a)
a = a + 1
This means it will first print 1 then a = a + 1 means now a = 2, it would print 2, then a = 3, now print 3, and so on.
IF ELSE STATEMENTS:
You use this if you wanna do something ONLY if certain conditions are met. Above, we were printing all the 10 numbers but now teacher wants us to print numbers that are only EVEN.
so inside while loop, use
if num % 2 == 0:
print(i)
% gives you remainder so even numbers when divided by 2 give 0 remainder so it would only print evens.
+ 2
maf . Thanks