【问题标题】:while and if statements problem with my script?while 和 if 语句与我的脚本有问题?
【发布时间】:2020-10-29 06:23:18
【问题描述】:

所以我想打印“错误!”每次我得到错误的输入。它有效,但是当我输入 尽管“guess.capitalize() != secret_word”为假,但正确的输入仍然执行“if”语句。你能告诉我我做错了什么吗? 多种方法表示赞赏!

secret_word = "Dog"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

while guess.capitalize() != secret_word and not out_of_guesses:
    if guess_count < guess_limit:
        guess = input("Enter your guess: ")
        guess_count += 1
        print("Wrong!")
    else:
        out_of_guesses = True

if out_of_guesses:
    print("You ran out of guesses")
else:
    print("You won!")

【问题讨论】:

  • 在第二个 sn-p 中你有 guess = ... 直接跟在 guess = ... 后面。猜猜(双关语有点意思)guess 将具有哪些值。

标签: python if-statement input while-loop count


【解决方案1】:

我评论了导致错误的代码部分:

while guess.capitalize() != secret_word and not out_of_guesses:
    if guess_count < guess_limit:
        guess = input("Enter your guess: ")# Here, the user can input correct word or wrong word
        guess_count += 1
        print("Wrong!") # The code goes down here, regardless of what the user input
    else:
        out_of_guesses = True

修正版:

secret_word = "Dog"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

while not out_of_guesses:
    if guess_count < guess_limit:
        guess = input("Enter your guess: ")# Here, the user can input correct word or wrong word
        if guess.lower() != secret_word.lower():
            guess_count += 1
            print("Wrong!") # The code goes down here, regardless of what the user input
        else:
            break
    else:
        out_of_guesses = True

if out_of_guesses:
    print("You ran out of guesses")
else:
    print("You won!")

【讨论】:

    【解决方案2】:

    您好,我想我理解您要做什么,我已阅读您的代码并对其进行了重构以尝试为您提供所需的输出。

    secret_word = "Dog"
    guess_count = 0
    
    while True:
        if guess_count != 3:
            guess_count +=1
            guess = input("Enter your guess: ") 
            if guess.upper() == secret_word.upper():
                print("You Won!")
                break
            else:
                print("Wrong")
                continue
        else:
            print("You ran out of guesses")
            break
    

    如果这不是您想要获得的输出,请告诉我。

    【讨论】:

      猜你喜欢
      • 2017-01-15
      • 2019-08-15
      • 2017-05-21
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 2019-08-21
      相关资源
      最近更新 更多