Python if循环的多个条件
您好,我在为一所学校编写代码时遇到了一些问题,但代码不起作用。它不会在整个循环中运行,但所有代码在我看来都是正确的。有人有什么想法吗Python if循环的多个条件,python,Python,您好,我在为一所学校编写代码时遇到了一些问题,但代码不起作用。它不会在整个循环中运行,但所有代码在我看来都是正确的。有人有什么想法吗 User_Input = input ( "Please enter a message that is no longer than 7 characters." ) User_Input_Length = len ( User_Input ) if { User_Input_Length >= 7
User_Input = input ( "Please enter a message that is no longer than 7 characters." )
User_Input_Length = len ( User_Input )
if { User_Input_Length >= 7
and User_Input_Length == 1
}:
print ( "Your message is odd." )
elif { User_Input_Length >= 7
and User_Input_Length == 3
}:
print ( "Your message is odd." )
elif { User_Input_Legnth >= 7
and User_Input_Length == 5
}:
print ( "Your message is odd." )
elif { User_Input_Length >= 7
and User_Input_Length == 7
}:
print ( "Your message is odd" )
elif { User_Input_Length >= 7
and User_Input_Length == 2
}:
print ( "Your message is even" )
elif { User_Input_Length >= 7
and User_Input_Length == 4
}:
print ( "Your message is even" )
elif { User_Input_Length >= 7
and User_Input_Length == 6
}:
print ( "Your string is even" )
else:
print ( "The string is too long." )
print ( "Goodbye" )
你不是在测试你认为你是什么。你的表情看起来像:
{ User_Input_Length >= 7 and User_Input_Length == 1 }
在Python中,{}
包含一个集合
或dict
(或对其中一个的理解)。因此,这是一个包含一个bool
值的集合。根据,任何包含成员的集合都被视为True,因此您的第一个测试将是唯一执行的分支
其次,内部(未选中)条件测试
用户输入长度
是否同时为7或更大和某个其他值;只有7的才是真的 这些大括号用于定义集合,非空集合的计算结果始终为true,因此您的代码将始终计算第一个if
Python不需要在if语句周围加括号。必须在
if
条件的参数中使用括号,并且要注意代码块的位置:与使用的C不同
作为分隔符,python知道您的块已结束,只是因为它跳到下一行
if(1 < 2) and (2 < 3):
print("true")
elif(1 > 2):
print("false")
如果(1<2)和(2<3):
打印(“真实”)
elif(1>2):
打印(“假”)
您可以使用模方法
(又称%
运算符)除以2
,并检查rest==1
。如果是这样,则为奇数,否则,如果rest==0
,则为偶数。User\u-Input\u-Length>=7,User\u-Input\u-Length==1
。。。嗯,想一想。那“看起来怎么样”?