检查输入是否包含名称python

2024-04-26 09:44:35 发布

您现在位置:Python中文网/ 问答频道 /正文

当thisname()函数运行时,它会给出错误“int object is not iterable”。我真的不明白怎么了。有什么想法吗?谢谢!你知道吗

import sys

def ifName():
    ifNameList = userInput.split()
    for i in len(ifNameList):
        #Seeing if one word following another word both have their first letters in capital
        if ifNameList[i] and ifNameList[i+1].istitle():
            print("is that a dude/dudette?")

userInput = input("type something")

if " " in userInput:
    ifName()

我变了

for i in len(ifNameList)):

for i in (range(len(ifNameList)))

现在它给我这个错误'IndexError:list index out of range

更新: 我改变了一切

for i in len(ifNameList):
            #Seeing if one word following another word both have their first letters in capital
            if ifNameList[i] and ifNameList[i+1].istitle():
                print("is that a dude/dudette?")

  for i in (range(len(ifNameList))):

        #Seeing if one word following another word both have their first letters in capital
        if i != 0:
            if ifNameList[i] and ifNameList[i-1].istitle():
                print("Is that a dude/dudette")
            else:
                print("That is not a dude/dudette")
        else:
           continue

Tags: inforlenifisanotheroneword
2条回答

首先,len方法返回一个整数。所以

for i in len(ifNameList)):

正在整数上循环,因此出现错误“int object is not iterable”

其次

for i in (range(len(ifNameList)))

引发错误“IndexError:list index out of range”,该错误仍然有效,因为您有一条语句[i+1]。你知道吗

第一个循环获取索引0(即“i”)和1(即“i+1”)。但是第二个循环获取索引1(即“i”)和2(即“i+1”)。你知道吗

因此,当在列表的最后一个索引上循环时,会引发错误,然后尝试查找不存在的最后一个索引+1索引。你知道吗

查看问题定义,您似乎想找到输入词是否满足istitle()条件。你知道吗

我会这样写:

import sys

def ifName():
    ifNameList = userInput.split()
    non_title_names = []
    for each_name in ifNameList:
        #Seeing if one word following another word both have their first letters in capital
        if not each_name.istitle():
            non_title_names.append(each_name)
    if non_title_names:
        print("Not a dude/dudette?")
    else:
        print("is that a dude/dudette?")

userInput = input("type something:\t")

if " " in userInput:
    ifName()

你在做一个简单的检查,过于复杂。这是使代码至少正常工作的一种方法:

import sys

def ifName(userInput):
    ifNameList = userInput.split()
    if len(ifNameList) != 2:
        print("Please enter two names", file=sys.stderr)

    elif ifNameList[0].istitle() and ifNameList[1].istitle():
        #Seeing if one word following another word both have their first letters in capital
        print("is that a dude/dudette?")
    else:
        print("Please capilalize your names", file=sys.stderr)

    # Return something?

userInput = input("type something")

if " " in userInput:
    ifName(userInput)
但是有一些事情要考虑。你的函数应该返回一些东西,现在它做的很少。你知道吗

注意,我将用户的输入作为参数传递到函数中。我看不出有什么好的理由在这里使用全局。你知道吗

您需要用户将名称大写,为什么不在程序中使用str.capitalize()这样做呢?你知道吗

假设所有名称都有两个组件。你确定总是这样吗?你知道吗

当输入了奇数个名称,或者至少没有两个名称时,不清楚您希望发生什么。你知道吗

相关问题 更多 >