-1

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.

zkhan21
  • 9
  • 3
  • Remove the first `if` line. – Selcuk Feb 02 '23 at 00:17
  • 1
    If the character doesn't appear in the phrase, you never set `num_occur`. You don't need the `if` statement, `count()` will return `0` if the character doesn't appear. – Barmar Feb 02 '23 at 00:17
  • Welcome to Stack Overflow. In your own words: if it is **not** the case that `character in phrase`, then what should `num_occur` be equal to? In these cases, what do you expect the code to do? Specifically, what value do you think `num_occur` will have, and how will the code set that? – Karl Knechtel Feb 02 '23 at 02:03
  • Alternately: where the code says `print(f'The number of times character {character} appears in the phrase: {num_occur}')` - should that happen always, or only `if character in string`? Therefore, should it be inside that `if` block, or outside? Is it? – Karl Knechtel Feb 02 '23 at 02:05

2 Answers2

-1
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 ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
-1
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')
Bastet
  • 36
  • 3