Raw Input If Statements Python [duplicate]

纵然是瞬间 提交于 2019-12-17 17:28:19

问题


I am having trouble with if statements in python. I am making a "game" entirely in dolan speak, excuse the spelling, it meant to be humorous manner. Sorry.

Here is the code:

import time

def menu():
    print ("dogz r a supar hahrd tin 2 matsr it tak yrs 2 mastr ut u nw git 2 exprince it. pik a tin 2 du:\n")
    menu = raw_input("1.)Ply Da Dogi gam\n2.)Halp\n")

    if menu == 1:
        game()

    if menu == 2:
        helpGame()

    if menu < 2:
        print ("dat not 1 ur 2 sry")
        time.sleep(1)
        menu()

def game():
    print ("nuw u ply mi gme u lke it")

def helpGame():
    print ("dis da halp u liek it")
menu()

That doesn't work for me, and I have never had direct function calling work inside of if statements and I have had to implement "seg-ways" which call the function.

Does this work for any of you? Is it possible it is my Python installation? Thanks!


回答1:


raw_input() returns a string, you are using a number in your if statements, change this line:

menu = raw_input("1.)Ply Da Dogi gam\n2.)Halp\n")

to this:

menu = int(raw_input("1.)Ply Da Dogi gam\n2.)Halp\n"))

You will want to look in dealing with error conditions next though.




回答2:


As you add more options, the if statements get unwieldly. Try out this dictionary based structure instead.

def menu():
    print ("dogz r a supar hahrd tin 2 matsr it tak yrs 2 mastr ut u nw git 2 "
           "exprince it. pik a tin 2 du:\n")
    prompt = "1.)Ply Da Dogi gam\n2.)Halp\n"
    {'1': game, '2': helpGame}.get(raw_input(prompt), menu)()


来源:https://stackoverflow.com/questions/17688511/raw-input-if-statements-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!