如何解决Python条件结构有问题
我的 python 代码中有一个 if 条件结构,但它的执行方式有问题...
我希望第一个嵌套的 if 在返回 The input choice you entered is out of range")
时打印 false
但它执行 else
中的代码,即第二个嵌套的 if 中的 you entered 4
,我希望它执行第一个嵌套 if 的 false
对应项,如果它是 print("nThe input choice you entered is out of range")
,我缩进了错误的方式还是?请帮助我
message=input("Enter the message you want encrypted")
if(message.isalpha()& message.__len__()!=0):
options=("1. Substitution Cypher","2.Playfair Cypher","3. Transposition Cypher","4. Product Cypher","RSA Cypher")
print("Choose an encryption Cypher you would like to use?")
print(options[0])
print(options[1])
print(options[2])
print(options[3])
choice=int(input("Please reply with a number for choice of Cypher"))
##USER NEEDS CHOICE OF encryption algorithm to use
if(choice>=1&choice<=4):
if(choice==1):
print("You chose 1")
elif(choice==2):
print("You chose 2")
elif(choice==3):
print("You chose 3")
else:
print("You chose 4")
else:
print("nThe input choice you entered is out of rage")
else:
print("User input is required in form of alphabet format")
解决方法
if(choice>=1&choice<=4):
这和你想的不一样。由于 operator precedence &
比比较更具粘性,因此上面等价于
if(choice>=(1&choice)<=4):
如果你想保留&
你需要添加括号如下
if((choice>=1)&(choice<=4)):
但是请注意,由于 Python 的一项功能,您可能会编写
if(1<=choice<=4):
得到相同的结果
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。