python 验证用户输入的字符,并迭代字符在句子中出现的次数

gblwokeq  于 2022-11-21  发布在  Python
关注(0)|答案(3)|浏览(118)

while循环和for循环可以单独工作,但是将它们组合起来并不能产生所需的输出。我希望用户输入一个句子,然后输入一个字符。字符必须作为一个单一的1字符输入,如果不是,那么程序应该再次询问。

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")
sc4hvdpw

sc4hvdpw1#

您在此代码块中遇到的问题:

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

只有当你第一次输入一个以上的字符时,它才会给予你想要的输出,否则它不会进入for循环来计算while循环条件len(singleCharacter) != 1内的字符数,然后返回初始字符数0。因此,要按预期工作,你应该把for循环用于计算while循环外的字符数:

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

输出量:

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

ogsagwnx2#

类似于:

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]))

应该做你想做的事。

ix0qys7i

ix0qys7i3#

只要将for循环从while循环中取出,它就会正常工作

相关问题