【问题标题】:Why is edit() causing traceback?为什么 edit() 会导致回溯?
【发布时间】:2015-05-16 23:50:37
【问题描述】:

非常感谢你们的帮助,我正在学习 10 年级的计算机编程,是的,这是我的最终评估。我遵循了您的建议并修复了我的代码.. 但是我想添加最后一件事,但它似乎无法在其他任何地方找到。在选择1的while循环之后,如果输入是“N”,那么我希望程序结束。但是,当它这样做时,输出是

Okay, have a good day!

Traceback (most recent call last):
  File "/Users/Zac_R/Documents/School/Grade 10/Computer Science/H1Z1 Text  
    Adventure.py", line 224, in 0
builtins.SystemExit:

有没有办法删除它,让它只是说“好的,祝你有美好的一天!”?

最后,当我说“请输入有效的命令!”时,类型光标移动到下一行 (**) 而不是停留在我想要的位置 (*)。例如:

请输入有效的命令! [是/否]:* **

以下代码供参考:

import time
import random
from sys import exit


def play ():

    # Health variables
    userHealth = 20
    zombieHealth = 15

    # This is the actual game
    print ( "{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}" )
    print ( "{------------=[Entering The Apocalypse!]=------------}" )
    print ( "{----------------------=[H1Z1]=----------------------}" )
    print ( "{---------------=[Made by: Zac Roter]=---------------}" )
    print ( "{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}" ) 
    time.sleep (1)

    print ( "You wake up in a small hospital room. You do not remember how you got here..." )
    time.sleep (1)

    print ( "It is dark and you can only make out a stick on the ground." )
    time.sleep (1)

    choice2 = input( "Do you take it? [Y/N]: " ) 

    # Stick taken
    if (choice2 == "Y"):
        print ( "Stick obtained!" )
        stick = 1


    # Stick not taken
    else:
        print ( "You did not take the stick" )
        stick = 0


    print ( "As you walk towards the only exit, you hear a faint voice ahead. " )
    time.sleep (1)

    choice3 = input( "Do you approach the voice? [Y/N]: " ) 

    # Approach zombie
    if (choice3 == "Y"):
        print ( "You approach the sound..." )
        time.sleep (1)
        print ( "As you get closer, you begin to make out the source of the sound was from a zombie!")
        choice4 = input( "Do you try to fight it? [Y/N]: ") 

        # Fight zombie
        if (choice4 == "Y"):

            # With stick
            if (stick == 1):
                print ( "You only have a stick to fight with!" )
                time.sleep (1)
                print ( "You swiftly strike the zombie in the leg to slow it down." )
                time.sleep (1)
                print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                print ("                    Loading...                  ")
                print ("         STICK DOES 2-8 DAMAGE PER TURN         ")
                print ("        ZOMBIE DOES 1-6 DAMAGE PER TURN         ")
                print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                time.sleep(1)    
                while (zombieHealth <= 0 and userHealth <= 0):
                    zombieHealth = zombieHealth - int(random.randint(2,9) )
                    userHealth = userHealth - int(random.randint(1,7) )
                    print ("Zombie has...", zombieHealth, "health left!" )
                    print ("You have...", userHealth, "health left!" )
                    time.sleep (1)

                if (zombieHealth <= 0 and userHealth > 0):
                    print ( "You have killed the zombie!" )

                if (userHealth <= 0 and zombieHealth > 0):
                    print ( "The zombie has killed you!" )
                    playagain()

                if (userHealth <= 0 and zombieHealth <= 0):
                    print ( "You kill the zombie, but you die of the zombie bite." )
                    playagain()

            # Without stick
            else:
                print ( "You don't have anything to fight with!" )
                time.sleep(1)
                print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                print ("                    Loading...                  ")
                print ("          HANDS DO 1-6 DAMAGE PER TURN          ")
                print ("        ZOMBIE DOES 1-6 DAMAGE PER TURN         ")
                print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                time.sleep(1)    
                while (zombieHealth > 0 and userHealth > 0):
                    zombieHealth = zombieHealth - int(random.randint(1,7) )
                    userHealth = userHealth - int(random.randint(1,7) )
                    print ("Zombie has...", zombieHealth, "health left!" )
                    print ("You have...", userHealth, "health left!" )
                    time.sleep (1)

                    if (zombieHealth <= 0 and userHealth > 0):
                        print ( "You have killed the zombie!" )

                    elif (userHealth <= 0 and zombieHealth > 0):
                        print ( "The zombie has killed you!" )
                        playagain()

                    else:
                        print ( "You kill the zombie, but you die of the zombie bite." )
                        playagain()






        #Don't fight zombie         
        else:            
            print ( "You choose not to fight the zombie." )
            time.sleep(1)
            print ( "As you turn away, it sprints and kills you!!!" )
            playagain()



    # Don't approach zombie
    else:
        print ( "As you turn away, a zombie sprints and kills you!!!" )
        playagain()


    print ( "Finally, you reach the exit to open doors to an unidentifiable world." )
    time.sleep (1)

    print ( "After a small victory, you hear the sounds of more zombies coming towards you from all angles." )
    time.sleep (1)

    print ( "Suddenly an SUV drives over the zombies in front of you!" )
    time.sleep (1)

    print ( "[Driver]: Get in, dammit!" )
    time.sleep (1)

    choice5 = input( "Do you get in the SUV? [Y/N]: " )
    time.sleep (1)

    # Enter SUV

    if (choice5 == "Y"):
        print ( "As you enter the SUV, the driver injects you with a syringe." )
        playagain()


    else: 
        print ( "You decline his offer, and as the SUV drives away, the zombies devour your remains." )
        playagain()


# The play again option that occurs after every user death
def playagain ():

    print ( "Thank you for playing H1Z1, by Zac Roter." )
    choice6 = input( "Would you like to play again? [Y/N]: " ) 

    if (choice6 == "Y"):
        play()

    if (choice6 == "N"):
        print ( "Okay, have a good day!" )
        exit()

    while (choice6 != "Y" or "N"):
        print ( "Please enter a valid command! [Y/N]: " )
        choice6 = input()

        if (choice1 == "Y"):
            print ( "Starting game..." )
            play()

        elif (choice1 == "N"):
            print ( "Okay, have a good day!" )
            exit()

# The main menu of the program
print ( "{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}" )
print ( "{-------------------=[Welcome To]=-------------------}" )
print ( "{----------------------=[H1Z1]=----------------------}" )
print ( "{---------------=[Made by: Zac Roter]=---------------}" )
print ( "{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}" )
time.sleep (1)


name = input( "Greetings survivor, what is your name?: " )
time.sleep (1)

print ( "Welcome "+name+", to H1Z1!" )
time.sleep (1)

print ( "The objective of this game is to survive in a zombie apocalypse." )
time.sleep (1)

choice1 = input( "Would you like to play? [Y/N]: " )

if (choice1 == "Y"):
    print ( "Starting game..." )
    play()

if (choice1 == "N"):
    print ( "Okay, have a good day!" )
    exit()


while (choice1 != "Y" or "N" ):
    print ( "Please enter a valid command! [Y/N]: " )
    choice1 = input()

    if (choice1 == "Y"):
        print ( "Starting game..." )
        play()

    elif (choice1 == "N"):
        print ( "Okay, have a good day!" )
        exit()

你们摇滚!

【问题讨论】:

  • 你的战斗序列似乎是递归的(虽然我没有阅读整个内容)但你应该在那里使用if 然后elif 然后else 语句。编程课的最终项目?这是几级?
  • 这 3 个 if 语句是否应该在您的 while 循环中?否则,您会遇到缩进错误/
  • 您的问题是“为什么exit() 会导致回溯?”如果是这样,那应该是问题的标题......
  • 你是在空闲状态下运行这个吗?
  • 我在 Wing101 运行它

标签: python


【解决方案1】:

分析一下:

>>> def a():
...    print("Type something: ")
...    a = input()
...
>>> a()
Type something: 
La la la la la la # That's my input

printing 在 Python 3 中是一个函数,具有多个隐藏参数,你很少(如果有的话)输入。如果您在解释器中输入help(print),它会很好地解释它:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.

这里的兴趣点在于这部分:end = '\n'。在函数内部,这才是真正发生的事情:

打印我的字符串,并添加“结束”值。刷新到屏幕(写入屏幕)

你有两个选择:

调用print时更改end关键字参数:

print("Enter a valid command!", end = "")
choice6 = input()

或者完全删除print 调用。将字符串放入您的input

choice6 = input("Enter a valid command! ")

这将导致:

Enter a valid command! Never! # "Never!" is my input

【讨论】:

    【解决方案2】:

    choice1 的值不会在 while 循环内更新,因此choice1 将保持为“Y”、“y”、“N”或“n”以外的值。您需要再次从用户那里获取输入,以便更新此变量。比如:

    while(choice1 != "Y" or "y" or "N" or "n"):
        print("Please enter a valid command!")
        choice1 = input()
    

    【讨论】:

      猜你喜欢
      • 2018-07-12
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 2013-02-25
      • 2012-12-31
      • 2014-01-01
      • 2017-03-10
      • 2019-12-01
      相关资源
      最近更新 更多