使用字典调用方法时我得到这个错误(Python)

问题描述 投票:-1回答:3

我想要做的是根据用户放置程序的数字打开文件夹,浏览器,或者通过字典关闭,其中每个数字都起作用。问题是它在所有情况下都返回none,而不是返回或函数。

输入0时,应关闭程序。

输入1时,应打开Windows 7的默认.mp3。

输入2时,您应该只打开默认音乐文件夹。

输入3时,只需在屏幕上输入“3”即可。

最后输入666,谷歌浏览器是用我放的URL打开的。

如果放入另一个号码应该留下“无效号码”

 import webbrowser
 import subprocess
 import sys
 opened = True

   def  one():

      print("Opening explorer.exe")
      #subprocess.Popen(r'explorer /select,"C:\Users\reciclo"')
      subprocess.call("explorer C:\\Users\\Public\\Music\\Sample 
      Music\Kalimba.mp3", shell=True)
      return "opened"
   def zero():

      print("Exit the program")
      opened = False
      return "Exit"
   def two():

      subprocess.call("explorer C:\\Users\\Public\\Music\\Sample Music", 
      shell=True)

      return "two"
  def three():


      return "three"
  def demon():

      demon_url = 'https://piv.pivpiv.dk/'
      chrome_path = 'C:/Program Files 
      (x86)/Google/Chrome/Application/chrome.exe %s'
      webbrowser.get(chrome_path).open(demon_url)

      return "invoked"
  def switch_demo(var):

  switcher = {
            0: zero,
            1: one,
            2: two,
            3: three,

           666: demon,

  }
   var = switcher.get(var, "Invalid num")
   while opened:
 if opened == True:
  var = int(input("enter a number between 1 and 9999999999 "))
  print(switch_demo(var)))

 elif opened== False:
  print("Goout")
  sys.exit()
python python-3.x function dictionary switch-statement
3个回答
0
投票

字典值作为要调用的函数:

切换器[0]()

def switch_demo(var):
    switcher = {
        0: zero,
        1: one,
        2: two,
        3: three,

        666: demon,
    }
    #var = switcher.get(var, "Invalid num")
    switcher[int(var)]() # exec function

-

def switch_demo(var):
    switcher = {
        0: zero,
        1: one,
        2: two,
        3: three,

        666: demon,
    }
    #var = switcher.get(var, "Invalid num")
    return (switcher[int(var)]())

while opened:

    if opened == True:
        var = int(input("enter a number between 1 and 9999999999 "))
        print (switch_demo(var))

    elif opened == False:
        print("Goout")

0
投票

你忘记从switch_demo()返回一个值,请检查以下代码:

 def switch_demo(var):

    switcher = {
            0: zero,
            1: one,
            2: two,
            3: three,

           666: demon,

    }
    return switcher.get(var, "Invalid num")


while opened:
    if opened == True:
        var = int(input("enter a number between 1 and 9999999999 "))
        print(switch_demo(var)))

    elif opened== False:

print("Goout")
sys.exit()

0
投票

@Mahmoud Elshahat是对的,你必须从switch_demo返回一个函数。另外,将print(switch_demo(var)))改为print(switch_demo(var)())。它可以像这样重写以使其更有意义:

var = "something"
function = switch_demo(var)
print(function())

这实际上会调用function并打印出它返回的任何内容,如果这是你想要的。

© www.soinside.com 2019 - 2024. All rights reserved.