简体   繁体   English

为什么我的猜谜游戏会跳过“较低”和“较高”部分

[英]why does my guessing game skip over the 'lower' and 'higher' parts

import random
import time
numOfGuesses = 0
guess = ''
playername = ''
numbertoguess = 0
MAX_GUESS = 10
#======================
playername = input ('What is your name:')
numbertoguess = random.randint (1, 100)
input("hello, " + playername + ", Guess the number I am thinking of   
(hint     its     between 1 and 100")
#======================
while numOfGuesses < MAX_GUESS:
 guess = int(input("What is your guess:"))
numOfGuesses += 1
 time.wait(1)
if guess < numbertoguess:
print ('Higher')
if guess > numbertoguess:
 print ('Lower')
elif numOfGuesses > MAX_GUESS:
 sys.exit()
else:
   sys.exit()
 #======================
 if guess == numbertoguess:
 print ("You are right," + playername + ",you guessed it in "+str  
(numOfGuesses) + "tries")
 elif guess != numbertoguess and numOfGuesses == 10:
print ("awe so close," + playername + ".")
print ("the number was" + str(numbertoguess) +".")`

when you finish one guess instead of telling you to go "higher" or "lower" the code runs over them and doesn't print either.当您完成一个猜测而不是告诉您“更高”或“更低”时,代码会运行它们并且也不会打印。 I'm so new to python if someone could help me that would be great.如果有人可以帮助我,我对 python 很陌生,那就太好了。

Ok, a few problems here.好的,这里有几个问题。

1) Python treats newlines as semicolons in C-like languages, so 1) Python 将换行符视为类 C 语言中的分号,因此

input("hello, " + playername + ", Guess the number I am thinking of   
(hint     its     between 1 and 100")

will throw a syntax error.会抛出语法错误。 To encode a newline, use the escape sequence "\\n"要编码换行符,请使用转义序列"\\n"

input("hello, " + playername + ", Guess the number I am thinking of \n(hint it's between 1 and 100")

This looks like a copy + paste issue though.不过,这看起来像是复制+粘贴问题。

2) Python uses indentations to figure out where your blocks are. 2) Python 使用缩进来确定块的位置。 So all of the statements in your loop body MUST begin with the same number of spaces / tabs as the rest.因此,循环体中的所有语句都必须以与其余语句相同数量的空格/制表符开头。 So your while loop should look like (indentation wise)所以你的 while 循环应该看起来像(缩进明智的)

while numOfGuesses < MAX_GUESS:
    guess = int(input("What is your guess:"))
    numOfGuesses += 1
    time.sleep(1)

    if guess < numbertoguess:
        print ('Higher')
    if guess > numbertoguess:
        print ('Lower')
    elif numOfGuesses > MAX_GUESS:
        sys.exit()
    else:
        sys.exit()

I believe this is causing the issues you specified in your question title.我相信这会导致您在问题标题中指定的问题。 Since the while loop is only executing the line guess = int(input("What is your guess:")) because it is the only one indented properly.由于 while 循环仅执行guess = int(input("What is your guess:"))因为它是唯一正确缩进的行。

Note: you cannot mix tabs and spaces, python will have a fit and no soup for you注意:你不能混合制表符和空格,python 会适合没有汤

Also indentation styles are typically 4 spaces or 1 tab.此外,缩进样式通常为 4 个空格或 1 个制表符。 Single space indents WILL give you headaches after a while.一段时间后,单个空格缩进会让您头疼。

3) If you need a delay, the proper function is time.sleep() 3)如果你需要延迟,正确的函数是time.sleep()

4) You have two if statements in your while body, so should the guess pass the if guess < numbertoguess: it will continue to the next if guess > numbertoguess: and fail it. 4)你的 while 主体中有两个 if 语句,所以如果猜测通过if guess < numbertoguess:它将继续下一个if guess > numbertoguess:并且失败。 Then it will jump to the else body, which is a system exit / break statement.然后它会跳转到else主体,这是一个系统退出/中断语句。 Either will cause the game to end prematurely.要么会导致游戏提前结束。

Change if chain to:将 if 链更改为:

if guess < numbertoguess:
    print ('Higher')
elif guess > numbertoguess:
    print ('Lower')
elif numOfGuesses > MAX_GUESS:
    break;
else:
    break;

5) You have sys.exit() but you forgot to import sys . 5)你有sys.exit()但你忘了import sys Also exit() does not need to be imported, you can use it without the sys module.此外, exit()不需要导入,您可以在没有sys模块的情况下使用它。

6) exit() quits your program. 6) exit()退出你的程序。 Nothing after the while loop will run if one of those elif / else statements executes.如果执行这些elif / else语句之一,则 while 循环之后的任何内容都不会运行。 The statement you are looking for is likely the break statement, which continues program execution on the next line after the loop.您要查找的语句可能是break语句,它在循环后的下一行继续执行程序。

7) Same as number 1), you've got a statement split across two lines here 7)与数字 1 )相同,这里有一条语句分成两行

print ("You are right," + playername + ",you guessed it in "+str  
(numOfGuesses) + "tries")

Fix to固定到

print ("You are right," + playername + ",you guessed it in " + str(numOfGuesses) + "tries")

NOTES笔记

Style wise, use 4 space or 1 tab indentations.风格明智,使用 4 个空格或 1 个制表符缩进。 It makes things easier to read.它使事情更容易阅读。 Also use newlines to separate logical blocks in code.还可以使用换行符来分隔代码中的逻辑块。 You can use #=========== to denote important blocks or huge logical blocks.您可以使用#===========来表示重要的块或巨大的逻辑块。

That's not to say you cannot have no newlines and cannot use #=========== for logical blocks, but people reading your code will hate you.这并不是说你不能没有换行符,也不能对逻辑块使用#=========== ,但阅读你的代码的人会讨厌你。


Your strings are missing some formatting here and there您的字符串在这里和那里缺少一些格式


You've hardcoded the max guesses here at the bottom: elif guess != numbertoguess and numOfGuesses == 10: In fact, you don't really need that check, since you've checked for a correct answer above.您已经在底部对最大猜测进行了硬编码: elif guess != numbertoguess and numOfGuesses == 10:事实上,您并不真正需要那个检查,因为您已经检查了上面的正确答案。

if guess == numbertoguess:
    print ("You are right," + playername + ",you guessed it in " + str(numOfGuesses) + "tries")

else:    
    print ("awe so close," + playername + ".")
    print ("the number was" + str(numbertoguess) +".")

This works because there are two logical states that the user can be in at the moment: guessed correctly or guessed incorrectly MAX_GUESS times.这是有效的,因为此时用户可以处于两种逻辑状态:正确猜测或错误猜测MAX_GUESS次。 Should you have 3+ logical states (guessed correctly, guessed incorrectly, guessed 42 for an easter egg), you will have to have another check.如果您有 3 个以上的逻辑状态(猜对了,猜错了,复活节彩蛋猜到了 42),您将不得不再进行一次检查。


Consider using a for loop instead of a while loop.考虑使用 for 循环而不是 while 循环。 while loops are good for when you do not need to know how many loops you've done, or when your loop criteria is a specific boolean expression. while循环适用于您不需要知道已经完成了多少循环,或者当您的循环条件是特定的布尔表达式时。 (ex while something.hasNext(): ) (例如while something.hasNext():

for loops are good for a specific number of iterations, or when you need to access something sequentially. for循环适用于特定次数的迭代,或者当您需要按顺序访问某些内容时。 (there are also for each loops). (每个循环也有)。

for i in range(MAX_GUESS): # i = 0 to i = MAX_GUESS -1

Then you won't need a check for your number of guesses since you're guaranteed to loop a max of MAX_GUESS times然后你不需要检查你的猜测次数,因为你保证最多循环 MAX_GUESS 次


A suggestion if I may.如果可以的话,给个建议。 Get an IDE (integrated Development Environment) with syntax highlighting and checking.获取具有语法突出显示和检查功能的 IDE(集成开发环境)。 I use Eclipse with a python plugin, but eclipse is a bit much for beginners.我使用带有python插件的Eclipse ,但 Eclipse 对初学者来说有点多。 Our CS professors suggested Wing , but I never used it我们的 CS 教授推荐了Wing ,但我从来没有用过

--- ---

Finished product (aside from string formatting. I'll let you do that):成品(除了字符串格式。我会让你这样做):

import random
import time

numOfGuesses   = 0
numbertoguess  = 0
MAX_GUESS      = 10
guess          = ''
playername     = ''

playername = input ('What is your name:')
numbertoguess = random.randint (1, 100)
input("hello, " + playername + ", Guess the number I am thinking of \n(hint it's between 1 and 100")

for numOfGuesses in range(MAX_GUESS): # nOG = 0 to nOG = MAX_GUESS -1
    guess = int(input("What is your guess:"))
    time.sleep(1)

    if guess < numbertoguess:
        print ('Higher')
    elif guess > numbertoguess:
        print ('Lower')
    else:
        break;

if guess == numbertoguess:
    print ("You are right," + playername + ",you guessed it in " + str(numOfGuesses) + "tries")

else:    
    print ("awe so close," + playername + ".")
    print ("the number was" + str(numbertoguess) +".")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM