+ 2
Nested Loops
Can you please explain this code for me? Thanks. for i in range(1,10): is_prime = True for k in range(2,i): if (i%k) == 0: print(i, " is divisable by", k) is_prime = False if is_prime: print(i, " is prime ")
7 Respuestas
0
Felix bro it's better to see on YouTube for better understanding while it's hard to understand in comments.... don't worry u will get it ..👍😎
+ 4
In the second loop is statement that check which number from the first loop( "possibles prime numbers") is divisible by any number from range from 2 to number. If the number is divisible by any number in this range the statement marks the number as non-prime number(is_prime= False). Else it prints the number.
+ 3
Felix Do u know what is the prime number?
If u know try to think about this code. If u will have trouble with it I can explain.
+ 3
outer for loop: test for numbers 1-10 if they are prime or not
By default say it is a prime.
inner loop: test if the number is divisible by any number between 2 and itself (excluded)
That is done with the modulus operator % which tells you the rest/remainder of a division.
So e.g. for 5 it goes like this:
5%2 = 1 --> not divisble by 2
5%3 = 2 --> not divisible by 3
5%4 = 1 --> not divisible by 4
So the if-condition is always wrong and is_prime will stay true.
For the number 4 however, you get:
4%2 = 0 --> divisable by 2
You enter the if-branch and is_prime is set to false.
4%3 = 1 --> not divisable by 3
You see, even if you already know that it is not a prime, the loop continous. So for just detecting primes it is quite in-effecient for larger numbers.
Also to show every number for which it is divisable it is not as efficient, since for e.g. 8 you know that if it is divisable by 2, it is also divisable by 4. More sophisticated methods exist, but this a nice start to get familiar with it :)
+ 1
Yes, I know what prime number is but I'm having trouble to understand the codes. Can you please help me understand? Thanks.
0
I got this already. I do understand the codes now from range() to indentation. Thanks for your reply.
0
you know C language??
example :
In C language,
for(initialisation,condition,inc/dec operation)
{
statements;
}
In python language,
for i in range(initialisation starts with given number here , limits upto n number and use every time less than conditions here, how many numbers increment/decrement ):
example :
'''for(i=1;i<n;i++) -> in c language '''
//i++ -> i=i+1...i.e increment by 1
for i in range(1,n,1):