“if choice”是在我希望程序停止时调用程序中的其他代码

2024-04-19 04:23:13 发布

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

我的代码是如果choice==“1”打印的代码比我想要的还要远。我不能使用break,因为我希望用户能够输入正确的密码。前面还有一些代码显示enter屏幕,包括choice=input(“choice:”)

这就是我所拥有的

# password
if choice == "1":
    print ("Requires Password")

#open the entire text file 
if choice == "password": 
    fp = open('answers.txt')
    while 1:
        line = fp.readline()
        if not line:
            break
        print (line)

 #quiz programming
 #generate a random keyword
elif choice == "2":
     input("You Ready? Press Enter Then")
print ('''

 Here is your Keyword''')
import random
with open('keywords.txt') as f:
       a = random.choice(list(f)).strip() #.strip cleans the line \n problem
       print ("    ")
       print ("------", a)

有了这段代码,我希望当用户输入1时,“需要密码打印”,然而这是我得到的。你知道吗

choice: 1
Incorrect option
Requires Password


     Here is your Keyword

------ haemoglobin

     Now press enter for your definitions

如何在需要密码时停止并允许用户输入其密码。还有一个错误的选项,在代码中显示的更远,我无法摆脱它。你知道吗


Tags: 代码用户密码inputyouriflinerandom
3条回答

首先,阅读您的说明会发现您的代码示例中缺少更高级别的部分;请您提供更多详细信息好吗?你知道吗

第二,代码中的一条注释:处理返回元素的项时,Python最好的方法是使用for。你知道吗

考虑到这一点,您的代码:

fp = open('answers.txt')
while 1:
    line = fp.readline()
    if not line:
        break
    print (line)

变得更加清晰和精简

for line in open('answers.txt'):  # this is an iterator
    print line,

这是解释in the Python Tutorial。你知道吗

我怀疑在你的代码中,你应该使用raw_input而不是input来获取choice

choice = raw_input("Choose an option").strip()
# password
if choice == "1":
    print ("Requires Password")

#open the entire text file 
if choice == "password": 
    fp = open('answers.txt')
    while 1:
        line = fp.readline()
        if not line:
            break
        print (line)

 #quiz programming
 #generate a random keyword
elif choice == "2":
     input("You Ready? Press Enter Then")

发生的是第一个if执行,打印Requires Password,然后控制权转移到第二个if-elif阶梯。无匹配项,应为choice已等于"1"。你知道吗

然后不管发生什么,不在任何if/elif语句下的其余代码都会执行。if-elif块的存在不会影响此块的执行。你知道吗

所以你需要做的是,要么把代码块放在下面,在某个if-elif(需要满足的条件)下面,要么你可以做的是,在这个块可以被输入之前,放另一个条件来检查你想要的条件是否被满足。你知道吗

相关问题 更多 >