我需要帮助修复我的代码 - 非常脆弱



我对Python很陌生,为了完成任务,我必须编写一个简单的'Higher or Lower'风格的游戏。

我目前正在尝试使用户无法通过输入无效输入来使游戏崩溃,但我被困在它要求用户决定他们想要开始多少钱的地步。

我尝试了一些事情,但我大多总是收到此错误:

Traceback (most recent call last):
  File "C:/Users/Liam/Desktop/game test 2-6-6.py", line 36, in <module>
    print("nBank Account: £", LTDbank_account)
NameError: name 'LTDbank_account' is not defined

尝试尽可能多地学习,以便帮助修复此问题或代码中的其他任何内容将不胜感激!

编辑:我还应该提到这是在Python 3.4.3上,如果这很重要的话

import random
highlow = True
while highlow == True:
    LTDplay = input("Would you like to play Higher or Lower? [ y | n ] ")
    if LTDplay == "y" or LTDplay == "n":
        highlow = False
    else:
        print("invalid entry")
    print("-"*40)                               
while LTDplay == "n":                       
    quit()
LTDscore = 0
LTDtries = 0
LTDwagered = 0              
LTDwon = 0
LTDwin_rate = 0
while LTDplay == "y":
    try:
        LTDbank_account = int(input("Please enter the amount of money you wish to start with: £"))
    except ValueError:
        print("invalid entry")
    LTDdie1 = random.randint(1,10)
    print("n| Die 1: ", LTDdie1)
    print("nBank Account: £", LTDbank_account)
    LTDbet = int(input("nPlease place your bet: £"))
    LTDwagered = LTDwagered + LTDbet    
    LTDwinnings = LTDbet/2              
    LTDguess = input("nDo you think the next number will be Higher or Lower? [ h | l ] ") 
    print("nPlease wait while I roll the dice")
    print ("-"*20)
    import time             
    time.sleep(2)
    LTDdie2 = random.randint(1,10)      
    print("n| Die 2: ", LTDdie2)       
    if LTDguess == "h":                 
        if LTDdie2 > LTDdie1:
            print("n*** Congratulations You Win! ***")         
            LTDbank_account = LTDbank_account + LTDwinnings
            LTDwon = LTDwon + LTDwinnings
            LTDscore = LTDscore + 1        
            LTDtries = LTDtries + 1
            print("nScore: ", LTDscore)
            print("-"*40)
        elif LTDdie2 < LTDdie1:
            print("n*** Sorry You Lose ***")               
            LTDbank_account = LTDbank_account - LTDbet
            LTDtries = LTDtries + 1
            print("nScore: ", LTDscore)
            print("-"*40)
        elif LTDdie2 == LTDdie1:
            print("n*** It's a Draw! ***")                 
            LTDtries = LTDtries + 1
            print("nScore: ", LTDscore)
            print("-"*40)
    if LTDguess == "l":                 
        if LTDdie2 > LTDdie1:
            print("n*** Sorry You Lose! ***")
            LTDbank_account = LTDbank_account - LTDbet
            LTDtries = LTDtries + 1
            print("nScore: ", LTDscore)
            print("-"*40)
        elif LTDdie2 < LTDdie1:
            print("n*** Congratulations You Win! ***")
            LTDscore = LTDscore + 1
            LTDtries = LTDtries + 1
            LTDbank_account = LTDbank_account + LTDwinnings
            LTDwon = LTDwon + LTDwinnings
            print("nScore: ", LTDscore)
            print("-"*40)
        elif LTDdie2 == LTDdie1:
            print("n*** It's a Draw! ***") 
            LTDtries = LTDtries + 1
            print("nScore: ", LTDscore)
            print("-"*40)
    LTDwin_rate = (LTDscore / LTDtries)*100         
    if LTDbank_account <= 0:
        print("nLooks like you're all out of money!nn*** GAME OVER ***")
        print("n| Tries: ", LTDtries)
        print("n| Score: ", LTDscore)
        print("n| Win Rate(%): ", LTDwin_rate)
        print("n| Wagered: £", LTDwagered)
        print("n| Winnings: £", LTDwon)
    LTDplay = input("nDo you want to play again? [ y | n ] ")
    while LTDplay == "n":
        print("-"*40)
        print("n FINAL STATS")
        print("n| Tries: ", LTDtries)
        print("n| Score: ", LTDscore)
        print("n| Win Rate(%): ", LTDwin_rate)
        print("n| Wagered: £", LTDwagered)
        print("n| Winnings: £", LTDwon)
        time.sleep(7)      
        quit()

如果第一个条目无效,则打印相应的消息,但随后继续游戏,没有值。 这会导致您看到的问题。

相反,你需要一个循环来获取一个有效的值,更像

okay = False
while not okay:
    try:
        LTDbank_account = int(input("Please enter ..."))
        okay = True
    except ValueError:
        print("invalid entry")

满足此循环,可以继续执行程序的其余部分。

LTDdie1 = random.randint(1,10)
print("n| Die 1: ", LTDdie1)
print("nBank Account: £", LTDbank_account)   # Apparent crash point
...

在您的代码中,如果用户输入了无效的内容,则会打印一条消息,但无论如何代码都会继续,LTDbank_account未定义。相反,请尝试循环input语句,直到获得 LTDbank_account 的有效值:

while True:
    try:
        LTDbank_account = int(input("Please enter the amount of money you wish to start with: £"))
    except ValueError:
        print("invalid entry")
    else:
        break

可能发生的情况是您在以下行遇到异常:

LTDbank_account = int(input("Please enter the amount of money you wish to start with: £"))

如果这是真的,你将看到在错误回溯之前打印到控制台的except块中的文本,具体如下:

输入无效

您可能希望再次提示用户输入金额,直到他给出有效值。 您可以将原始的 try/except 块包装在一个 while 循环中,并在输入有效后中断它,如下所示:

while True:
    try:
        LTDbank_account = int(input("Please enter the amount of money you wish to start with: £"))
        break
    except:
        print("invalid entry")

您需要让用户输入有效的输入,然后才能继续。下面是一个示例:

try:
    LTDbank_account = int(input("Please enter the amount of money you wish to start with: £"))
except ValueError:
    print("invalid entry")

无论用户输入无效输入,这都会继续执行。解决此问题的一种方法是使用开放(无条件)循环。这里的另一点是,如果用户以 £ 开头,它将永远不会转换为整数。我更改了您的提示:

# Input loop. Continue until valid input.
while True:
    try:
        LTDbank_account = int(input("Please enter the amount of money as integer number:"))
        break     # Vaild entry. Break the input loop
    except ValueError:
        print("Seems you didn't enter valid money amount. Please try again.")

我没有检查所有需要修改的地方。仔细检查你的代码,想想会发生什么。然后更改它。

最新更新