Python:小while循环

2024-06-25 23:14:49 发布

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

我不熟悉python和编程,我在摆弄一个简单的while循环时遇到了这个问题。循环接受输入以评估两个可能的密码:

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

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

    print('Access Granted')

它似乎不认为果汁或果汁2是有效的。在

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

^{pr2}$

不起作用,而:

    while passEntry !='juice' :

工作正常。我似乎找不到这些问题的原因(后两者之间的唯一区别是=)后面的空格。感谢任何帮助。在


Tags: or密码inputaccess编程passwordjuiceprint
3条回答

首先,应该使用Python的getpass模块来获取可移植的密码。例如:

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

然后,您编写的保护while循环的代码:

^{pr2}$

由Python解释器解释为带有保护表达式的while循环

(passEntry != 'juice') or 'juice2'

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

在Python中,测试成员资格的最佳方法是使用^{} operator,它适用于各种数据类型,如列表、集合或元组。例如,列表:

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

怎么样:

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

raw_input()代替input()?在

input()对输入进行计算,就像它是Python代码一样。在

你可以用

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

相关问题 更多 >