双重问题;通过 Python 3.9

问题描述

这确实是一个双重问题,因为我知道相同的代码块有两个错误

我基本上是在制作一个基于“滚动 d20”而改变的互动故事。例如,向玩家呈现一个场景,并提示玩家掷 d20。计算机生成一个 1 到 20 之间的数字,并且根据滚动,故事将以某种方式展开。我遇到的障碍是我定义了一个函数“RollD20()”,它将变量“n”的值存储为 1 到 20 之间的随机整数,然后打印滚动的值。当我调用函数时,它崩溃并显示“n 未定义”的错误

这个问题的另一部分,在同一个代码块中,是我试图让游戏本质上询问用户,你想玩吗?如果答案是肯定的,那么剩下的就完成了。如果不是,则该过程结束。但到目前为止,无论我按什么键,y 或 yes,n 或 no,甚至输入,它都不会像预期的那样结束该过程,它只是继续前进。有没有简单的方法解决这个问题?

谢谢,代码在下面。


import sys
import random

while True:

    def NewGame():
        print(input("Hello! Would you like to go on an adventure? y/n >> "))
        if input == "y" or "yes":
            print("Great! Roll the dice.")
            print(input("Press R to roll the D20."))
            print("You rolled a " + RollD20(n) + "!")
        else:
            print(input("Okay,bye! Press any key to exit."))
            sys.exit()


    def RollD20():
        n = random.randint(1,20)
        print(n)


    NewGame()

Traceback (most recent call last):
\venv\main.py",line 22,in <module>
    NewGame()
\venv\main.py",line 11,in NewGame
    print("You rolled a " + RollD20(n) + "!")
NameError: name 'n' is not defined

Process finished with exit code 1

解决方法

好的,您的代码有很多错误,所以我会逐一逐一检查。

  1. 您需要将输入分配给一个变量,以便您可以在 if 语句中进行比较。永远不要在现有 Python 函数或对象之后命名变量,因此我将其命名为 inp

  2. 真的没有必要打印每一条输入语句;只需拨打 input

  3. 你需要做的不是x == "y" or "yes",而是x == "y" or x == "yes"

  4. 对于 RollD20 函数,您应该返回它而不是打印 n,因为您在 NewGame 函数中使用返回值。

  5. NewGame函数中,您不需要向RollD20传递任何参数。此外,由于它返回一个整数,您必须将结果转换为字符串才能打印。

话虽如此,以下是完整的更正代码:

import sys
import random

while True:

    def NewGame():
        inp = input("Hello! Would you like to go on an adventure? y/n >> ")
        if inp == "y" or inp == "yes":
            print("Great! Roll the dice.")
            input("Press R to roll the D20.")
            print("You rolled a " + str(RollD20()) + "!")
        else:
            input("Okay,bye! Press any key to exit.")
            sys.exit()


    def RollD20():
        n = random.randint(1,20)
        return n 


    NewGame()