【问题标题】:A part of my code is not working in a while loop [closed]我的一部分代码在while循环中不起作用[关闭]
【发布时间】:2020-10-21 18:06:31
【问题描述】:

我不知道为什么,但它是在猜测密码,但是当它猜对时它并没有结束程序。非常感谢任何帮助!

#imports
import time, random

#Welcome
print("Welcome to Password Guess!")
pass1 = input("Please insert your phone password:")

#Start system

guessclock = 0

start1 = 1

i = 1
while i < 2:
    while i < 2:
        guess1 = random.randint(1, 2)
        guessclock += 1
        print(guess1)
    if pass1 == guess1:
        i = 3
        print("Password guessed")
        print("It took", guessclock)
        print("Attempts")

【问题讨论】:

  • 添加break声明
  • 同样条件下嵌套的while有什么意义?另外,你永远不会改变i,所以你会有一个无限循环
  • 添加的 break 语句仍然不起作用。
  • 您需要更新您的变量,以便在满足条件时退出循环。例如,i = i + 1
  • 请提供预期的minimal, reproducible example。显示中间结果与您的预期不同的地方。我们应该能够复制和粘贴您的代码的连续块,执行该文件,并重现您的问题以及跟踪问题点的输出。这让我们可以根据您的测试数据和所需的输出来测试我们的建议。你的程序应该在哪里弄清楚如何退出?哪些变量没有改变,或者哪些条件没有按照您的预期工作?

标签: python python-3.x loops


【解决方案1】:

尝试替换

pass1 = input("Please insert your phone password:")

pass1 = int(input("Please insert your phone password:")) # turns pass1 into an integer

【讨论】:

  • 成功了!非常感谢
  • 有什么办法可以让它不重新猜组合吗?
  • 制作一个包含所有可能组合的列表,例如:combos = [1, 2] 然后使用random.choice 从两个组合中选择一个,然后删除选择的组合并随机选择另一个组合。 combos.remove(random.choice(combos))。现在你可以少猜一个项目,移除重新猜测的组合
  • 有没有一种方法可以在不列出 100 万个组合的情况下做到这一点。
  • 我不这么认为,但是,您可以使用combos = list(range(start, stop, step=1)),其中范围在stop 之前结束,这会生成一个组合列表。或者使用可以使用列表理解[i for i in range(start, stop, step)]
【解决方案2】:

这是一个更好的版本(没有双while循环和int转换):

#imports
import time, random

#Welcome
print("Welcome to Password Guess!")
pass1 = int(input("Please insert your phone password:"))

#Start system

guessclock = 0

start1 = 1

i = True
while i:
    guess1 = random.randint(1, 2)
    guessclock += 1
    print(guess1)
    if pass1 == guess1:
        i = False
print("Password guessed")
print("It took", guessclock)
print("Attempts")

【讨论】:

    猜你喜欢
    • 2022-12-30
    • 1970-01-01
    • 2014-06-06
    • 2019-11-14
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    相关资源
    最近更新 更多