+ 1
Can some one explain below code
name=input("Enter a Name: ") i=0 temp_var = "" while i<len(name): if name[i] not in temp_var: temp_var+=name[i] print(f"{name[i]} : {name.count(name[i])}") i=i+1 #OUT PUT # Enter a Name: hello world # h : 1 # e : 1 # l : 3 # o : 2 # : 1 # w : 1 # r : 1 # d : 1 not understood "not in" for "o" character condition I have learn if condition is true the will go to if block if not the will go outside how is counting 0 3 times if condition is not meeting
8 odpowiedzi
+ 3
count will not increase. The function count() returns the frequency..
Ex: "aaabc".count('a') returns 3.
'a' is 3 times in string.
Check your temp_var is "helo wrd".
you are already find frequemcy of 'l'
by name.count('l') and adding 'l' to temp_var;
so need to print again. that's what 'l' not in temp_var do.
skips second 'l'.
+ 2
'h' not in temp_var true, so adding to temp_var; printing char with its count.
'e' not in temp_var true, so adding to temp_var; printing char with its count.
'l' not in temp_var true, so adding to temp_var; printing char with its count.
'l' not in temp_var false, out of if block.
#it is in temp_var by previous iteration.
'o' not in temp_var true, so adding to temp_var; printing char with its count.
This is enough I think.. Repeated same next...
Hope it helps..
+ 2
No it will not print when name[i] is 'l' in second time..
See the code with printing i index value . It skips repeated value indexes.
name=input("Enter a Name:\n ")
i=0
temp_var = ""
while i<len(name):
if name[i] not in temp_var:
temp_var+=name[i]
print(f"{i}: {name[i]} : {name.count(name[i])}")
i=i+1
edit: skips 3, 7, 9.
+ 1
@Jayakrishna Thanks for quick help
can you explain me this
The 'l' not in temp_var false, out of if block.
means its go to i=i+1 then how the count will increase? which is mentioned in print function if will go outside the block the the print statement will not execute
+ 1
Yes sir Understood but if the condition is not true / not meet for second 'i' cause its already in string then how it will count means how it will go to the print statement
+ 1
Okay sir thanks for quick help 🙂 🙂 🙂
+ 1
Hope it clear now...
You're welcome.
- 1
Hi