python - 为什么我的程序应该进入if却直接进入else block

标签 python

我试图制作一个简单的调查机器人,但我在第二个 if 语句上遇到了麻烦。它只是忽略 if 和 elif,直接进入 else 语句。我已经尝试了一切,尽管这可能是一个简单的解决方案,但请帮助...

 import sys

 yes = "yes"
 no = "no"
 experience_good = "yes"
 contact = "1"

 print("How many times have you bean contacted by us in the past quarter (3 months)")
 contact = sys.stdin.readline()

 if contact != 0:
     print("Was your experience was us good? Type a 1 for yes or 0 for no")
     experience_good = sys.stdin.readline()
     print("experiencence_good is", experience_good)
     # The above line was just to double check the variable was inputted 
correctly
     if experience_good is 1:
         print("Good to hear that.")
     elif experience_good is 0:
         print("Sorry about that. What could we be doing better?")
         doing_better = sys.stdin.readline()
     else:
         print("Stuff's been messed up")

我得到的输出只是:

How many times have you bean contacted by us in the past quarter (3 months)

3

Was your experience was us good? Type a 1 for yes or 0 for no

1

exp_good is 1

Stuff's been messed up

最佳答案

因为experience_good永远不会1!它开始于

experience_good = "yes"

然后中途也许改变为

experience_good = sys.stdin.readline()

此时如果用户输入1,则该变量将保存的是字符串值'1',而不是1所以你需要

experience_good = int(sys.stdin.readline().strip())

关于python - 为什么我的程序应该进入if却直接进入else block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44350986/

相关文章:

Python Pygame 错误

python - 使用带有 Python 的 COM 通过 DirectShow 访问网络摄像头

python - 如何线程 Tweepy 流

python - 在 Python 3 中打印文档字符串

python - 这里有什么问题? (属性错误 __len__)

python - "python -v"输出太长

python - 如何增加 opencv 中高半径值的椭圆弧分辨率?

python - django-cms 页面的绝对 url

python - Pandas 选择过去最近的日期

python - 我可以将列表中的 2 个连续空字符串合并为 1 个空字符串,这样当我们有 4 个空字符串时,它应该合并并生成 2 个空字符串