我的“如果”陈述不起作用

2024-09-30 16:36:38 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,所以我不确定我在这里做错了什么,但是我的代码在exmaple的if语句中自动选择了第一个if

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 ()

Tags: or代码youifwithnotsoftwarehardware
2条回答

if语句包含许多逻辑部分。每个部分都转换为布尔值-因此任何非空字符串都转换为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,并优化此代码。你知道吗

在第一个代码块中,缺少缩进和冒号。应该是:

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

相关问题 更多 >