如何在python中定义函数来重复提示?(初学者)

2024-10-06 17:28:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,所以我决定用python3创建一个基本的游戏来帮助自己学习!每当我尝试使用“def”时,我的问题就出现了。当我尝试运行这个程序时,它会完全跳过所有用户输入,因为def。在这种情况下使用函数的目的是将播放器返回到它显示两扇门的位置。也许这是一个与压痕有关的问题?如果有人能试一试,看看你是否能发现错误,你的帮助将不胜感激!:D个

def sec1 ():
print ("You have two doors in front of you. Do you choose the door on the left or right?")
room1 = input('Type L or R and hit Enter.')

if room1 == "L":
    print ("********")
    print ("Good choice",name)
elif room1 == "R":
    print ("********")
    print ("Uh oh. Two guards are in this room. This seems dangerous.")
    print ("Do you want to retreat or coninue?")
    roomr = input('Type R or C and hit enter.')

if roomr == "R":
    print ("Good choice!")
    sec1()

Tags: orandtheinyouinputifdef
3条回答

在Python中,缩进非常重要。下面是一个适当缩进的代码示例(我有几个自由):

def sec1 ():
    print ("You have two doors in front of you. Do you choose the door on the left or right?")
    name = input('Enter your name.')
    room1 = input('Type L or R and hit Enter.')

    if room1 == "L":
        print ("********")
        print ("Good choice",name)
    elif room1 == "R":
        print ("********")
        print ("Uh oh. Two guards are in this room. This seems dangerous.")
        print ("Do you want to retreat or coninue?")
        roomr = input('Type R or C and hit enter.')
        if roomr == "R":
            print ("Good choice!")
        elif roomr == "C":
            print ("Run!")

第1段()

你有缩进问题。缩进在Python中很重要。根据PEP8 styling guideline,建议使用4 spaces代替tabs进行缩进。您还缺少name变量。你知道吗

下面是一个快速解决方案:

def sec1 ():
    print("You have two doors in front of you. Do you choose the door on the left or right?")
    room1 = input('Type L or R and hit Enter.')

    name = "Player Name"

    if room1 == "L":
        print("********")
        print("Good choice", name)

    elif room1 == "R":
        print("********")
        print("Uh oh. Two guards are in this room. This seems dangerous.")
        print("Do you want to retreat or coninue?")
        roomr = input('Type R or C and hit enter.')

        if roomr == "R":
            print("Good choice!")
            sec1()

sec1()

为什么我们在结尾有sec1()?

功能就像机器。它自己什么都不做。必须有人来操作它。^末尾的{}(注意括号)正在发送一个信号来开始执行顶部定义的函数sec1。你知道吗

我认为最好的学习方法是设置断点并使用调试器来学习程序的流程。你知道吗

在调试模式下运行程序,然后单击图标进行单步执行、单步执行等操作。这听起来很复杂,但非常简单,一旦知道如何执行此功能,就可以节省大量时间。你知道吗

数学函数

也许在这里提到Mathematical Functions有点离题,但我认为,这是完全值得的。编程语言中的函数深受Mathematical Functions的启发,然而,在当今大多数编程语言中(除了HaskellF#等函数编程语言),最初的Mathematical Functions的概念一年四季都有很大的偏离。你知道吗

在数学中,函数的输出完全依赖于它的输入,不修改函数外的值,然而,在大多数编程语言中,情况并非总是这样,有时它可能是运行时错误的来源。你知道吗

提示

作为一个初学者,我强烈建议你使用一个合适的IDE(集成开发环境),如果你还没有。PyCharm有一个免费的社区版本。ide附带了PEP8风格的检查器、调试器、探查器等,可以帮助您更轻松地学习Python。你知道吗

def sec1 ():
    print ("You have two doors in front of you. Do you choose the door on the left or right?")
    room1 = input('Type L or R and hit Enter.')

函数体应该缩进

相关问题 更多 >