这个if语句有什么问题?

时间:2014-01-06 18:12:35

标签: python if-statement logic conditional-statements

由于某些原因,即使条件不满足,我的程序也不会进入“其他”部分。

if score_str >= 3:
    print("Pass")

    self.prefect = tk.Label(self, width=80, height=4, text = "You have passed, well done! You can now become a prefect.")
    self.prefect.pack(side="top", fill="both", expand=True)

    self.name = tk.Label(self, width=80, height=4, text = student_name)
    self.name.pack(side="top", fill="both", expand=True)

    self.surname = tk.Label(self, width=80, height=4, text = student_surname)
    self.surname.pack(side="top", fill="both", expand=True)

    self.tutor = tk.Label(self, width=80, height=4, text = student_tutor_group)
    self.tutor.pack(side="top", fill="both", expand=True)
else:
    print("Fail")

    self.fail = tk.Label(self, width=80, height=4, text = "Unfortunately you have not scored highly enough to be considered for a prefect position.")
    self.fail.pack(side="top", fill="both", expand=True)

1 个答案:

答案 0 :(得分:9)

从名称我推断score_str是一个字符串;如果是这样,那么你的比较总是失败,因为在Python 2中,数字总是在字符串之前排序:

>>> '1' > 1
True

比较时使得分为整数,这样您至少可以进行数字比较:

if int(score_str) >= 3:

在Python 3中,比较字符串和整数(或任何两种未明确定义比较的类型)将导致异常:

>>> '1' > 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

这会帮助你避免这个问题。