好的,所以我不确定我在这里做错了什么,但是我的代码会自动选择&#34中的第一个;如果" exxple的声明,如果它是
if 1 == 2
print("Works")
elif 1 == 1
print("There we go")
即使输入了错误的值,它也会自动选择第一个。请参阅下面的代码:
def troubleshoot ():
print("Now we will try and help you with your iPhone.")
print("")
time.sleep(1)
hardsoft = input(str("Is the issue a problem with hardware of software? Write n if you are not sure: ") ) #ISSUE WITH IT SELECTING THE FIRST ONE NO MATER WHAT#
if hardsoft == "Software" or "software" or "S" or "s" or "soft" or "Soft":
software ()
elif hardsoft == "Hardware" or "hardware" or "Hard" or "hard" or "h" or "H":
hardware ()
elif hardsoft == "Not sure" or "not" or "Not" or "NOT" or "not sure" or "n" or "N":
notsure ()
else:
print("Sorry, that command was not recognised")
print("Please try again")
troubleshoot ()
答案 0 :(得分:1)
在第一个代码块中,您缺少缩进和冒号。它应该是:
if 1 == 2:
print("Works")
elif 1 == 1:
print("There we go")
这样你也可以得到预期的结果。
对于第二部分:if hardsoft == "Software" or "software" or "S" or "s" or "soft" or "Soft":
不是一个有效的条件 - 或者至少它没有做你认为应该做的事情。那里的每个字符串都被转换为一个布尔值,并且任何非空字符串都将被解释为true。因此,像if "Software"
这样的条件总是如此。正确的条件是:
if hardsoft == "Software" or hardsoft == "software" or hardsoft == "S" or hardsoft == "s" or hardsoft == "soft" or hardsoft == "Soft":
... and so on
答案 1 :(得分:0)
您的if语句包含许多逻辑部分。每个部分都转换为boolean - 所以任何非空字符串都转换为True。 我可以建议你想要这样的东西:
def troubleshoot ():
print("Now we will try and help you with your iPhone.")
print("")
time.sleep(1)
hardsoft = input(str("Is the issue a problem with hardware of software? Write n if you are not sure: ") ) #ISSUE WITH IT SELECTING THE FIRST ONE NO MATER WHAT#
if hardsoft == "Software" or hardsoft == "software" or hardsoft == "S" or hardsoft == "s" or hardsoft == "soft" or hardsoft == "Soft":
software ()
elif hardsoft == "Hardware" or hardsoft == "hardware" or hardsoft == "Hard" or hardsoft == "hard" or hardsoft == "h" or hardsoft == "H":
hardware ()
elif hardsoft == "Not sure" or hardsoft == "not" or hardsoft == "Not" or hardsoft == "NOT" or hardsoft == "not sure" or hardsoft == "n" or hardsoft == "N":
notsure ()
else:
print("Sorry, that command was not recognised")
print("Please try again")
troubleshoot ()
此外,您必须了解这些长ifs,并优化此代码。