+ 3

Can you please explain the output of this code?

def fun1(a): x = [] for i in range(a): if(i%2 == 0): x.append("+"*i) return x print(len(func1(6))) Answer is 3

11th Mar 2020, 1:08 PM
APC (Inactive for a while)
APC (Inactive for a while) - avatar
3 Answers
+ 2
For the numbers 0, 2 and 4, a string is appended to the list. ['', '++', '++++'] There are three strings in that list, so len is 3.
11th Mar 2020, 1:17 PM
HonFu
HonFu - avatar
+ 2
for i in range 6 i%2==0//0%2==0 ,true x.append("+"*0)//add "+" in zero time means x[]=[""] 1%2==0// false 2%2==0//true x.append("+"*2)//add "+" in two time means x[]=["","++"] 3%2==0//false 4%2==0//true x.append("+"*4)//add "+" in four time means x[]=["","++","++++"] 5%2==0//false and exit the loop length(x)=3
11th Mar 2020, 1:21 PM
Prathvi
Prathvi - avatar
+ 1
in the function there is for i in range(a): if (i%2==0) : x.append("+"*i) To put it simply, it says that for every even number i ... Add "+" * i in the list x Here a == 6 In range(6) there are 3 even numbers 0, 2 and 4 (6 is not included) So the list will be x = [ "", "++", "++++" ] There are 3 elements in list return x will return this list so len(func1(6)) Will give 3 as a result
11th Mar 2020, 1:26 PM
Utkarsh Sharma
Utkarsh Sharma - avatar