Python使用If,Els根据输入切换显示

2024-09-29 07:32:17 发布

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

我想使用IF/Else或Switch根据输入值显示打印文本。并让我知道如何使用下面的代码开关情况

 # OnButtonOK after clicking it, display the input value    
  def OnButtonOK(self):
    Input = self.entrytext.get()
    # self.text.insert(END, Input + '\n')
    # self.scroll.config(Input = self.text.yview)
    print Input
    useroption = atoi(Input)
    # self.OnButtonClick();
    if (useroption == 1):
            print "input is output"
        self.SubMenu1();
    else:
        print "Error:Invalid"

    return;

def SubMenu1(self):
        print 'SubMenu1'
    return;

def SubMenu2(self):
        print 'SubMenu2'
    return;

def SubMenu3(self):
        print 'SubMenu3'
    return;

我只能打印其他部分:

if (useroption == 1):
            print "input is output"
        self.SubMenu1();
    else:
        print "Error:Invalid"

让我知道我到底错在哪里


Tags: textselfinputoutputreturnifisdef
2条回答

我认为您的代码中存在缩进问题: Python使用4个空格(可以使用1个空格,但4是一个很好的实践)缩进语言。表示if/else语句如下:

if a == 1:
    print("A = 1") # 4 spaces w.r.t to above statement
elif a == 2:
    print("A = 2")
elif a ==3:
    print("A = 4")
else:
    print("A = pta nahi")

您可以使用上面的if/else语句作为切换案例,您的缩进问题也将得到解决

这是一个简单的初学者的错误,你正在缩进它:

if (useroption == 1):
        print "input is output"
    self.SubMenu1();
else:
    print "Error:Invalid"

应该是

if (useroption == 1):
    print "input is output" # You had an indent too many here
    self.SubMenu1();
else:
    print "Error:Invalid"

Python对缩进敏感;缩进太多或太少都会破坏代码

相关问题 更多 >