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

Question:

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.

Asked By: zkhan21

||

Answers:

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 …

Answered By: Joran Beasley
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}')
else:
    print(f'The number of times character {character} appears in the phrase: 0')
Answered By: Bastet
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.