Why does my python function not return the correct times the letters are in the string?
Question:
word = "hello My name is Bob"
for i in word:
if i == "m":
print("There is an M")
Why is it not printing two times, there r two "m"s
Answers:
You have to do i.lower() to lowercase the "M"
Python is a case-sensitive language so "M" and "m" are different. so to compare them by ignoring the case it requires conversion of both the side either lower or upper case. Below code will give you result either it’s "M" or "m"
such as :
word = "hello My name is Bob"
for i in word:
if i.lower() == "m".lower():
print("There is an M")
Try pasting this:
word = "hello My name is Bob"
for i in word.upper():
if i == "M":
print("There is an M")
The issue with your output is Python’s case sensitivity. Python reads your ‘word’ variable and finds only one ‘m'(simple m). So it prints only one time. By adding ‘.lower()’, we convert the whole string into simple letters leading to the expected output.
word = "hello My name is Bob"
for i in word:
if i == "m":
print("There is an M")
Why is it not printing two times, there r two "m"s
You have to do i.lower() to lowercase the "M"
Python is a case-sensitive language so "M" and "m" are different. so to compare them by ignoring the case it requires conversion of both the side either lower or upper case. Below code will give you result either it’s "M" or "m"
such as :
word = "hello My name is Bob"
for i in word:
if i.lower() == "m".lower():
print("There is an M")
Try pasting this:
word = "hello My name is Bob"
for i in word.upper():
if i == "M":
print("There is an M")
The issue with your output is Python’s case sensitivity. Python reads your ‘word’ variable and finds only one ‘m'(simple m). So it prints only one time. By adding ‘.lower()’, we convert the whole string into simple letters leading to the expected output.