我想创建一个可以在文本输入等于命令时调用的函数。
from os import system
from time import sleep
import ctypes
ctypes.windll.kernel32.SetConsoleTitleW('SimpleChat')
print('Hi, welcome to my basic chat engine!')
sleep(5)
system('cls')
username = input('Enter a username: ')
ctypes.windll.kernel32.SetConsoleTitleW('SimpleChat - ' + username)
system('cls')
def commands (command):
commandlist = ['/help','/clear', '/commands']
commanddict = {'/help' : 'help', '/clear' : 'clear', '/commands' : 'commands'}
for possibility in commandlist:
if command == possibilty:
commanddict[possibility]()
break
def textInput (text):
if text[0] == '/':
commands(text)
第24行可以调用函数吗?我想象它会起作用的方式是,它将找到键“可能性”的条目,然后将其作为函数调用,但是我不确定。
如果以前的代码不起作用,那会是什么?
假设您的代码中有一个名为help
,,clear
...的函数,如下所示。
def help():
print("help!")
然后,下面的commands
函数将做您想要的。请注意,该函数可以用作Python中字典的值。
def commands (command):
command_dict = {'/help' : help, '/clear' : clear, '/commands' : commands}
func = command_dict.get(command)
if func is not None:
func()
else:
print("I don't have such a command: %s" % command)
我猜应该将其中'/commands'
的value(command
函数)command_dict
更改为另一个函数。如果键入“命令”,程序将崩溃。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句