Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My program that counts the number of times a character appears in a string does not work for 1 input I am trying. It works on all other ones

when I enter "n Monday" it gives me the right output but then when I try something like "n Nothing" it gives me an error saying ‘num_occur’ is not defined. How can I fix this code without using the for statement.

string = str(input("Enter a string that contains a character and a phrase:\n"))
character = string[0]
phrase = string[2:]
if character in phrase:
    num_occur = phrase.count(character)
print(f'The number of times character {character} appears in the phrase: {num_occur}')
if character not in phrase:
    print(f'The number of times character {character} appears in the phrase: 0')

I tried adding str() in the if statement but that did not do anything.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

if character in phrase:
    num_occur = phrase.count(character)
    print(f'The number of times character {character} appears in the phrase: {num_occur}')

you need to tab in that print …

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading