Geting TypeError:类型'int'的参数在Python中不可迭代

问题描述 投票:0回答:2

我正在尝试用到目前为止所学的知识来编写文本游戏,但是遇到了一个问题。

[输入1很好,但是输入2则出现以下错误:

Traceback (most recent call last):
  File "ex36.py", line 39, in <module>
    start()
  File "ex36.py", line 27, in start
    if choice == 1 or "closer" in choice:
TypeError: argument of type 'int' is not iterable

我意识到函数idf():完全没有必要,因为我可以将输入2视为字符串,而无需将其转换为整数。这将修复程序。但是,我想知道为什么在尝试将输入更改为字符串时会发生此错误,以及为什么它仅适用于1而不适用于2。

对于这个愚蠢的问题,我感到抱歉;我是编程和尝试自学python的新手。谢谢大家的支持。

更新1:我认为我现在已经看到问题了,如以下两个答复者所指出的。当程序尝试检查“ closer”(选择的字符串是整数)时,会发生问题。

我希望if语句同时接受整数和字符串。我该怎么做?有任何修改程序的建议吗?

from sys import exit

print("""Welcome to my text game! You may input numbers (e.g. 1, 2, 3) to
navigate or type in your choice.""", "\n")

def bad_news(reason):
    print(reason)
    exit(0)

#IDs if str or int
def idf(check):
    if check.isdigit() == True:
        converted = int(check)
        return converted
    else:
        return check

def start():
    print("You're walking home down a dark road, in a dark and gloomy night.")
    print("There's someone going the same way as you.")
    print("'It's quite dark and dangerous,' you think. 'Better do something.'")
    print("Will you: 1. Follow him/her closer? or 2. Keep distance?")
    choice1 = input("> ")

    choice = idf(choice1)

    if choice == 1 or "closer" in choice:
        bad_news("""The person gets spooked and you got cops called on you.
Now you have a restraining order. Great!""")
    elif choice == 2 or "distance" in choice:
        alley()
    else:
        print("The input is invalid; please try again.")
        start()

def alley():
    print("Now in alley.")

start()
python
2个回答
0
投票

您的idf将任何数字字符串转换为数字,然后尝试检查字符串是否在整数中。

您最好的选择是总是从idf返回字符串(或完全删除此函数),然后检查choice == "1"是否>>


-1
投票

您的问题是这条线:

© www.soinside.com 2019 - 2024. All rights reserved.