相关代码是:
while True:
command = raw_input("Please enter a command: ")
cls()
if command == "quit":
cls()
quit()
break
if command == "add":
cls()
problem=add()
cls()
if problem==1:
print "Invalid subject type! Check your spelling, or use the new subject command."
if problem==2:
print "Invalid problem type! Please use the *insert new type command here*."
if problem==3:
print "Invalid date! Check your spelling or try to express it in another way (i.e. 1/2/14, tomorrow, or in 3 days)."
if problem==4:
print "The time you entered was in the past! Hopefully you've already turned in that assignment!"
if problem==5:
print "Both the subject and the type are incorrect"
if command == "print" or "optimize" or "list":
cls()
optimize_print()
if command == "optimize":
cls()
optimize_print()
if command == "remove":
cls()
if len(assignments) != 0:
remove()
else:
print "There is nothing to remove"
cls()
if command == "open website":
cls()
site = raw_input("What website would you like to open? ")
open_web(site)
if command == "clear":
certainty = raw_input("This action cannot be undone. Are you sure you want to clear all assignments? ")
if "y" in certainty:
clear_all()
else:
pass
if command == "start" or "run":
run_prog()
if command == "new subject":
cls()
sub = raw_input("What subject would you like to add? ")
for i in subjects:
if sub.lower() == i.lower():
print "That subject already exists."
break
break
else:
pass
new_subject(sub)
elif command == "change website" or "new website":
cls()
subject_to_add_website = raw_input("What subject would you like to add/change a website for? ")
change_website(subject_to_add_website)
if command == "new assignment" or command == "new type" or command == "new assignment type":
cls()
ty = raw_input("What assignment type would you like to add? ")
for i in types:
if ty.lower() == i.lower():
print "That assignment type already exists."
break
break
else:
pass
new_type(ty)
我们在python 2.7中有一个调度程序,一旦给定的函数运行完毕,它会使用while循环来提示输入新的输入。突然间没有我们意识到在while循环中发生了任何重大更改,程序现在执行所有if语句,即使您输入的字符串与其中任何一个都不匹配。我错过了一些明显的东西吗? (我应该补充说这是在控制台中运行并且以前工作但现在在各种mac和pc上都失败了)
答案 0 :(得分:2)
包含or
的所有if语句都会运行,无论command
的值如何。这是因为字符串文字被评估为True
条件if command == "start" or "run"
首先评估command
的值,然后评估"真实性"字符串run
。始终满足此条件,并始终运行其后的代码。
这应该改为:
if command == "start" or command =="run":
do.something()
答案 1 :(得分:2)
比较
command == "print" or "optimize" or "list"
将始终评估为True
。 Python将其评估为
(command == "print") or bool("optimize") or bool("list") # non-empty strings evaluate to True
以下是更正代码的方法:
command == "print" or command == "optimize" or command == "list"
pythonic的写作方式是:
command in ("print", "optimize", "list")
答案 2 :(得分:1)
而不是输入:
command == "start" or "run"
您应该输入:
command == "start" or command == "run"
因为在第一种情况下,或者"运行"将无条件地宣告为True,因此每次都会执行