首页 > 解决方案 > if语句的初学者Python问题

问题描述

提前道歉,因为这可能相当愚蠢。

基本上我只是想弄清楚如何处理输入(我对编码很陌生),我在 if 语句中遇到了一个问题。

x=input("What is your name? ")
name=x
print("Hello,", name, "nice to meet you")
y=input("Would you like me to close now? (yes/no) ")
listx=["no","No","NO","nO"]
for response in listx:
    if response == y:
        input("Why? ")
        input("I think you're being rather terse", name, ". ")
        input("No, you. ")
        input("So that's how it's going to be? ")
        input("Well I'm closing anyway. ")
        input("Bye then. ")

我只是认为这会带我完成这个有趣的小交流,随着时间的推移,我可以自定义回复,但此时有一个问题:

input("I think you're being rather terse", name, ". ")

此时代码似乎无法识别名称;我定义了名称,因为当我使用 x 时它也不起作用。我假设代码无法识别它,因为 if 语句本质上是在真空中或其他什么东西,但我将如何解决这个问题?我希望能够调用之前在对话中发生的细节,以使其更有趣。

标签: python-3.7

解决方案


你不能用input()语句来做到这一点——它只适用于print(). 所以print()可以将任意数量的字符串作为参数,但input()只会使用一个(在最新版本的 python 中,如果您尝试提供多个字符串,则会引发错误 - 当我尝试自己运行您的代码时,我得到了一个TypeError) .

如果要包含name在 的文本中,则input()需要将其连接起来:

input("I think you're being rather terse " + name + ". ")

或使用格式字符串插入它:

input(f"I think you're being rather terse {name}. ")

推荐阅读