【问题标题】:Python if statement gone wrong. Whats wrong? [duplicate]Python if 语句出错。怎么了? [复制]
【发布时间】:2021-07-07 08:42:04
【问题描述】:

我不明白我的代码有什么问题。有人可以帮我吗?我整个上午都在努力解决它。

question = input("Choose from 0 to 1 : ") 
mylist = ["Mark", "Jenny"] 
if question == 0: 
    print(mylist[0], "is your new friend") 
elif question == 1: 
    print(mylist[1], "is your new friend")
else:
    print("I said choose from 0 to 1")

【问题讨论】:

  • 你能解释一下错误是什么以及在哪里吗?
  • input() 函数返回一个字符串,但您正在检查整数 0 和 1。

标签: python python-3.x if-statement printing user-input


【解决方案1】:

问题出在数据类型上:

input() 返回一个字符串,但在 if 语句中,您将字符串“0”与整数 0 进行比较。因此,总是执行 else。

将 input() 转换为 int() 如下所示:

question = int(input("Choose from 0 to 1 : "))
mylist = ["Mark", "Jenny"] 
if question == 0: 
    print(mylist[0], "is your new friend") 
elif question == 1: 
    print(mylist[1], "is your new friend")
else:
    print("I said choose from 0 to 1")

【讨论】:

  • 我猜我很蠢。我应该看到的。谢谢
  • 发生在每个人身上,这就是你在无数次犯了这个错误之后记住这些事情的方式!
猜你喜欢
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 2014-06-12
  • 2014-01-16
  • 2022-11-18
  • 1970-01-01
  • 2012-09-17
  • 2022-01-07
相关资源
最近更新 更多