【问题标题】:Multiple IF and ELIF conditionals [Python]多个 IF 和 ELIF 条件 [Python]
【发布时间】:2015-02-21 02:49:58
【问题描述】:
name="admin"
passw="aaa"

itemone="01"
itemtwo="02"

a=input("Enter your username:")
b=input("Enter your password:")

if(a==name)and(b==passw):
    print("Welcome.")
    c=int(input("Enter Item Code:"))

   if(c==itemone):
    print("Name: ID")
   elif(c==itemtwo):
    print("Name: Mirror")
   else:
    print("Item not found. Try again.")

else:
    print("Username/Password is incorrect.")
    exit()

当输入“01”或“02”时,程序会忽略所有其他代码并指向“未找到项目。再试一次。”

我终于让它工作了!谢谢!!!

【问题讨论】:

  • 您将 c(整数)与 itemone(字符串)进行比较
  • 请尝试正确缩进您的代码,以便更容易解释!
  • 您应该使用raw_input 而不是input,因为后者会导致您的输入字符串为evaled 请参阅docs.python.org/2/library/functions.html#input

标签: python if-statement


【解决方案1】:

您正在接受输入并将其转换为整数,然后检查它是否等于字符串。这将返回错误。示例:

01=="01"
=> False

"01"=="01"
=> True

您不需要将输入转换为整数。

【讨论】:

    【解决方案2】:

    正如 robert_x44 所说,您正在将整数与字符串进行比较。

    试试:

    itemone=01
    itemtwo=02
    

    另外,在您的帖子中,if 块没有缩进。这可能只是格式错误,但是python if语句必须缩进。

    【讨论】:

      【解决方案3】:

      要么将itemoneitemtwo 更改为ints,要么不要将您的输入转换为int。现在你正在比较 ints 和 strs,这是行不通的。

      从以下两项更改中选择一项 - 不要同时进行两项更改,否则您只会扭转您现在所处的情况(比较 strs 与 ints 而不是 ints 与 str s.)

      如何使用ints

      变化:

      itemone="01"
      itemtwo="02"
      

      到:

      itemone=1
      itemtwo=2
      

      如何使用strs

      变化:

      c=int(input("Enter Item Code:"))
      

      到:

      c = input("Enter Item Code:")
      

      【讨论】: