Please help me to understand this I am a beginner in python and please tell me why this question answer is 12. | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 1

Please help me to understand this I am a beginner in python and please tell me why this question answer is 12.

What is the output of this code? a=[] for i in range(1, 10): if (i%4==0) and (i%2==0): a.append(i) print(a[0]+a[1])

7th Jun 2021, 5:17 AM
Coderado
Coderado - avatar
7 Respostas
+ 6
List <a> will be filled with [ 4, 8 ]. These are numbers within range 1 ~ 9 which are fully divisible by 4 and 2. The result (12) is sum of the 2 numbers in the list.
7th Jun 2021, 5:24 AM
Ipang
+ 3
your condition is redundant: divisible by 4 necessarily implies divisible by 2
7th Jun 2021, 6:36 AM
bell
bell - avatar
+ 2
Thankyou everyone.your answers helped me a lot
7th Jun 2021, 8:49 AM
Coderado
Coderado - avatar
+ 1
So here let me explain this code one by one ! 1st a = [ ] Here, we have a variable 'a' assigned to an empty list 2nd for i in range (1,10): This code is to create a loop (loops is used when we want to execute a particular task consecutively) Here, i takes values from 1 to 9 3rd if (i%4 == 0) and (i%2 == 0): Here, we used an logical operator if to check for an condition . The condition is; i%4 == 0 for what value of i in range (1,10) when divided by 4 leaves remainder 0 Similarly, i%2 == 0 also means the same. We also used an another operator 'And' And is used with logical operator if because it only executes the particular task only when both the conditions are satisfied ! 4th a.append(i) This code is executed when the if condition is satisfied . append is an attribute in list data type which is used to add elements or values into a list Here 'a' is the name or variable which indicates the list .
7th Jun 2021, 7:56 AM
ch Murali
+ 1
5th Print(a[0] + a[1]) Here, the number in the square brackets is the index number which is used to access the particular value in a list . a[0] gets the first value of the list a a[1] gets the second value of the list a These values will be added and then printed as output !
7th Jun 2021, 7:58 AM
ch Murali
+ 1
What happens in processing is : i values ranges from 1 - 9 So, According to condition I should be divisible by 4 and 2 (as remainder will be zero) So, values which will divided by 4 and 2 in range (1,9) are 4,8 These values will be added into a list named 'a' This how it looks a = [4,8] Now, In the last statement ! print(a[0]+a[1]) print(4+8) Here, 4 and 8 are the 1st and 2nd values of the list 'a' HENCE ultimately print(12) Output : 12
7th Jun 2021, 8:02 AM
ch Murali
7th Jun 2021, 8:03 AM
ch Murali