【问题标题】:Infinite Loop x Counter Problems无限循环 x 计数器问题
【发布时间】:2015-04-21 10:01:47
【问题描述】:

您好,我的代码存在三个问题:

  1. 当我为我的第一个问题输入“N”时,它会出错。
  2. 在“再次运行?”之后进入无限循环。输入。
  3. 我的计数器没有正确加起来,所以即使我的答案是对还是错,它也不会计算在内。

请帮帮我。

下面是我的代码:

    #Introduction-ish print statement
print("In this application, we will be playing a coin coss game.  For as "\
      "many times as you like, we will continue playing the game.")


#def function1():
response=str(input("\nWould you like to run this application?  Type 'Y' to run "\
               "or 'N' to not run: "))
if response=="N":
    print("\nOutcome of Game:")
    print("You did not run the application."\
          "  Nothing happened.  You did not play the game.")


#Counters
programCounter=0
hCounter=0
tCounter=0
guessCountR=0
guessCountW=0

#User Input

if response=="Y":

    funcGuess=str(input("\nPick one- Type 'H' for Heads or 'T' for Tails: "))

#Coins

import random

#number=random.randint(1,2)

while response !="N" and funcGuess=="H" or funcGuess=="T":
    number=random.randint(1,2)
    if number==1:
        number=="Heads"
        hCounter+=1
    else:
            number=="Tails"
            tCounter+=1
    if funcGuess==number:
        guessCountR+=1
    else:
        guessCountW+=1

    print(number)
    response=str(input("Run again?"))
    if response=="Y":
        funcGuess=str(input("\nPick one- Type 'H' for Heads or 'T' for Tails: "))
if response=="N":
    print("\nOutcome of Game:")
    print("You guessed ",programCounter, "time(s).")
    print("You guessed heads",hCounter, "time(s).")
    print("You guessed tails",tCounter, "time(s).")
    print("You guessed correctly",guessCountR, "time(s).")
    print("You guessed incorrectly",guessCountW, "time(s).")

#Guess Count
guessCount=guessCountR+guessCountW


#paste


#if response =="Y":
    #function1()

#else:
    #print("\nOutcome of Game:")
    #print("You did not run the application."\
          #"  Nothing happened.  You did not play the game.")

我不介意所有的 cmets。我故意把它们留在那里,但如果有人帮助发现它们有用,请告诉我。

对这篇长文深表歉意。

【问题讨论】:

  • 请为每个问题创建一个最小示例,然后将它们作为单独的问题重新提交。

标签: debugging python-3.x logic counter infinite-loop


【解决方案1】:

问题一:

在第 34 行,您正在评估一个名为 funcGuess 的变量。如果您对最初的问题回答“Y”,它只会在第 26 行定义。

问题 2:

while 循环无限循环,因为永远无法满足中断条件。无法在循环中为response 分配值“N”。此外,请务必将 or 评估的两边放在括号之间,以便正确评估该行

问题 3:

正确的数字和猜测分别分配给变量numberfuncGuessnumber 始终为 1 或 2,funcGuess 始终为“H”或“T”。因此funcGuess == number 永远不能评估为True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2021-09-02
    • 2020-09-09
    • 2021-09-11
    • 2018-09-24
    相关资源
    最近更新 更多