2012-12-28 41 views
0

我新来python和编程一般,我碰到这个问题,同时摆弄一个简单的while循环。该循环需要输入以评估两个可能的密码:Python:小while循环错误

print('Enter password') 
    passEntry = input() 

    while passEntry !='juice' or 'juice2': 
     print('Access Denied') 
     passEntry = input() 
     print(passEntry) 

    print('Access Granted') 

它似乎并没有将juice或juice2视为有效。

也只有接受一个密码,如:

while passEntry != 'juice' : 

将无法​​正常工作,而:

while passEntry !='juice' : 

工作正常。我似乎无法找到这些问题的原因(后两者之间的区别仅在于=后面的空格)。任何帮助表示赞赏。

+0

这可能不是原因的错误我猜! –

回答

7

首先,你应该使用Python的getpass模块来移植一个密码。例如:

import getpass 
passEntry = getpass.getpass("Enter password") 

然后,你写的代码看守while循环:

while passEntry != 'juice' or 'juice2': 

得到由Python解释器解释为保护表达

(passEntry != 'juice') or 'juice2' 
while循环

这总是如此,因为不管passEntry是否等于“juice”,当解释为布尔值时,“juice2”将被视为真。

在Python中,测试成员资格的最佳方法是使用in operator,该工具适用于各种数据类型,如列表,集合或元组。例如,一个列表:

while passEntry not in ['juice', 'juice2']: 
0

这是行不通的?

while passEntry !='juice' and passEntry !='juice2': 
1

如何:

while passEntry !='juice' and passEntry!= 'juice2': 

,并使用raw_input()代替input()

input()将输入评估为Python代码。

+0

是的,这是它的第一部分,使用或取代和使逻辑错误。由于 – baker641

+0

的raw_input()没有似乎工作但 – baker641

3

可以使用

while passEntry not in ['juice' ,'juice2']: 
1

passEntry !='juice' or 'juice2'意味着(pass != 'juice') or ('juice2')"juice2"是一个非空字符串,所以它总是如此。因此你的情况总是如此。

你想要做passEntry != 'juice' and passEntry != 'juice2',或者更好的passEntry not in ('juice', 'juice2')

0

你的错误是在你写while语句的方式。

while passEntry !='juice' or 'juice2': 

当python解释器读取该行时,该行将始终为真。并且还 代替:

passEntry = input() 

用途:

passEntry = raw_input() 

(除非你使用Python 3)

input在Python 2个evals输入。

这将是正确的代码:

print('Enter password') 
passEntry = raw_input() 

while passEntry != 'juice' and passEntry != 'juice2': 
    print('Access Denied') 
    passEntry = raw_input() 
    print(passEntry) 

print('Access Granted') 
+0

好吧,即时通讯运行python3,所以我想这就是为什么的raw_input()给了我的问题。谢谢 – baker641