首页 > 解决方案 > 如何修复代码中的打印错误

问题描述

我的代码存在一些我不知道如何解决的问题。

  1. 当我打印出他们选择的游戏和级别的消息时,最后,它并没有打印出级别(初级、中级或高级)。它只打印出游戏。我已将“num”打印出来,但我也尝试了“Level”和“number”。代码是

    print ("Play",gamelist[gametype], "at" ,num)

  2. 当询问用户他们想玩什么游戏时,如果他们输入了 0-3 范围之外的数字或字母,则在最后打印消息时会在代码中进一步分解。这只是在询问什么游戏时,而不是他们想要游戏的级别。

任何帮助将不胜感激。

#Ask user what game they would like to play
def game () :
    global gametype,gamelist
    gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
    gamecount = 0
    print ("Hello",name,"the four games avaliable are:")
    while gamecount < 4:
        print (gamecount," ",gamelist[gamecount])
        gamecount = gamecount + 1
    gametype = int(input("What number game do you want? (Please choose between 0 and 3) "))
    print ( "You have chosen",gamelist[gametype],)
    print ("")

#Ask game level
def number():
    while True:
        try:
            Level = int(input("What is the level you would like to play at? "))

            if Level <= 25:
                print ("Begginer ")
                break

            elif Level >=26 and Level <=75:
                print ("Intermediate")
                break

            elif Level >=76 and Level <=100:
                print ("Advanced")
                break
            else:
                print("Out Of range(1-100): Please enter a valid number:")

        except ValueError:
            print("Please enter a valid number")

#Create a subroutine to print out the action message
def printmessage ():

    print ("")
    print ("#                                                      #")
    print ("########################################################")
    print ("#################### ACTION MESSAGE ####################")
    print ("########################################################")
    print ("#                                                      #")
    print ("Play",gamelist[gametype], "at" ,num)
    print ("#                                                      #")
    print ("########################################################")
    print ("#################### ACTION MESSAGE ####################")
    print ("########################################################")
    print ("#                                                      #")

#This is to let the program work
name = input("What is your name? ")
print ("")

game ()
num = number()
printmessage()

标签: python

解决方案


在函数 def number 的末尾添加以下代码行:

return Level

推荐阅读