Home > Mobile >  Validate user input of character and iterate how many times character exists in sentence
Validate user input of character and iterate how many times character exists in sentence

Time:11-20

The while loop and for loop works individually, but combining them does no generate the desired output. I want the user to enter a sentence, and then a character. The Character must be entered as a single 1 character, if not then the program should ask again.

sentence = input("Type sentence: ")
sentence = sentence.lower()
singleCharacter = input("Type character: ")

char = 0

while len(singleCharacter) != 1:
    singleCharacter = input('Enter a single character: ')
    for i in sentence:
        if i == singleCharacter:
            char  = 1

print(singleCharacter,"appears",char,"times in your sentence")

CodePudding user response:

Something like:

sentence = input("Type sentence: ")
sentence = sentence.lower()
singleCharacter = input("Type character: ")

char = 0

while len(singleCharacter) != 1:
    singleCharacter = input('Enter a single character: ')

print(sum([1 for c in sentence if c == singleCharacter]))

Should do what you want.

CodePudding user response:

Just get for-loop out of while loop and it will be working fine

CodePudding user response:

The problem you encounter in this block of code:

while len(singleCharacter) != 1:
    singleCharacter = input('Enter a single character: ')
    for i in sentence:
        if i == singleCharacter:
            char  = 1

It will only give you the desired output when you enter more than one character at first time, otherwise it will not enter for loop for counting the number of characters which inside of while loop condition len(singleCharacter) != 1 and then will return the initial characters count 0. Therefore to work as expected you should put for loop for counting the characters outside while loop:

while len(singleCharacter) != 1:
    singleCharacter = input('Enter a single character: ')
for i in sentence:
    if i == singleCharacter:
        char  = 1

Output:

Type sentence: Hello World!
Type character: l
l appears 3 times in your sentence
  • Related